blob: 62a460afa00eceaf460b9daefe214aeedc4ef5fc [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
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000023#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000025
26namespace art {
27
28void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000029 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000030 blocks_.Add(block);
31}
32
Nicolas Geoffray804d0932014-05-02 08:46:00 +010033void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000034 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000035 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000036}
37
Roland Levillainfc600dc2014-12-02 17:16:31 +000038static void RemoveAsUser(HInstruction* instruction) {
39 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000040 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000041 }
42
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010043 for (HEnvironment* environment = instruction->GetEnvironment();
44 environment != nullptr;
45 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000046 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000047 if (environment->GetInstructionAt(i) != nullptr) {
48 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000049 }
50 }
51 }
52}
53
54void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
55 for (size_t i = 0; i < blocks_.Size(); ++i) {
56 if (!visited.IsBitSet(i)) {
57 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010058 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000059 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
60 RemoveAsUser(it.Current());
61 }
62 }
63 }
64}
65
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010067 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000068 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000069 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +000071 for (HBasicBlock* successor : block->GetSuccessors()) {
72 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +000073 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010074 // Remove the block from the list of blocks, so that further analyses
75 // never see it.
76 blocks_.Put(i, nullptr);
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);
Vladimir Marko60584552015-09-03 13:35:12 +000089 for (HBasicBlock* successor : block->GetSuccessors()) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000090 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091 successor->AddBackEdge(block);
92 } else {
93 VisitBlockForBackEdges(successor, visited, visiting);
94 }
95 }
96 visiting->ClearBit(id);
97}
98
99void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100100 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
101 // edges. This invariant simplifies building SSA form because Phis cannot
102 // collect both normal- and exceptional-flow values at the same time.
103 SimplifyCatchBlocks();
104
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000105 ArenaBitVector visited(arena_, blocks_.Size(), false);
106
David Brazdilffee3d32015-07-06 11:48:53 +0100107 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000108 FindBackEdges(&visited);
109
David Brazdilffee3d32015-07-06 11:48:53 +0100110 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 // the initial DFS as users from other instructions, so that
112 // users can be safely removed before uses later.
113 RemoveInstructionsAsUsersFromDeadBlocks(visited);
114
David Brazdilffee3d32015-07-06 11:48:53 +0100115 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000117 // predecessors list of live blocks.
118 RemoveDeadBlocks(visited);
119
David Brazdilffee3d32015-07-06 11:48:53 +0100120 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100121 // dominators and the reverse post order.
122 SimplifyCFG();
123
David Brazdilffee3d32015-07-06 11:48:53 +0100124 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100125 ComputeDominanceInformation();
126}
127
128void HGraph::ClearDominanceInformation() {
129 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
130 it.Current()->ClearDominanceInformation();
131 }
132 reverse_post_order_.Reset();
133}
134
135void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000136 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100137 dominator_ = nullptr;
138}
139
140void HGraph::ComputeDominanceInformation() {
141 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000142 GrowableArray<size_t> visits(arena_, blocks_.Size());
143 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100144 reverse_post_order_.Add(entry_block_);
Vladimir Marko60584552015-09-03 13:35:12 +0000145 for (HBasicBlock* successor : entry_block_->GetSuccessors()) {
146 VisitBlockForDominatorTree(successor, entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147 }
148}
149
150HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
151 ArenaBitVector visited(arena_, blocks_.Size(), false);
152 // Walk the dominator tree of the first block and mark the visited blocks.
153 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000154 visited.SetBit(first->GetBlockId());
155 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157 // Walk the dominator tree of the second block until a marked block is found.
158 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000159 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000160 return second;
161 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000162 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000163 }
164 LOG(ERROR) << "Could not find common dominator";
165 return nullptr;
166}
167
168void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
169 HBasicBlock* predecessor,
170 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000171 if (block->GetDominator() == nullptr) {
172 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000173 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000174 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000175 }
176
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000177 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000178 // Once all the forward edges have been visited, we know the immediate
179 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000180 if (visits->Get(block->GetBlockId()) ==
Vladimir Marko60584552015-09-03 13:35:12 +0000181 block->GetPredecessors().size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100182 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100183 reverse_post_order_.Add(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000184 for (HBasicBlock* successor : block->GetSuccessors()) {
185 VisitBlockForDominatorTree(successor, block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000186 }
187 }
188}
189
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000190void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100191 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100192 SsaBuilder ssa_builder(this);
193 ssa_builder.BuildSsa();
194}
195
David Brazdilfc6a86a2015-06-26 10:33:45 +0000196HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000197 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
198 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000199 // Use `InsertBetween` to ensure the predecessor index and successor index of
200 // `block` and `successor` are preserved.
201 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000202 return new_block;
203}
204
205void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
206 // Insert a new node between `block` and `successor` to split the
207 // critical edge.
208 HBasicBlock* new_block = SplitEdge(block, successor);
209 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 if (successor->IsLoopHeader()) {
211 // If we split at a back edge boundary, make the new block the back edge.
212 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000213 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100214 info->RemoveBackEdge(block);
215 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100216 }
217 }
218}
219
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100220void HGraph::SimplifyLoop(HBasicBlock* header) {
221 HLoopInformation* info = header->GetLoopInformation();
222
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100223 // Make sure the loop has only one pre header. This simplifies SSA building by having
224 // to just look at the pre header to know which locals are initialized at entry of the
225 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000226 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100227 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100228 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100229 AddBlock(pre_header);
230 pre_header->AddInstruction(new (arena_) HGoto());
231
Vladimir Marko60584552015-09-03 13:35:12 +0000232 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
233 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100234 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100235 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100236 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100237 }
238 }
239 pre_header->AddSuccessor(header);
240 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100241
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100242 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Marko60584552015-09-03 13:35:12 +0000243 if (info->IsBackEdge(*header->GetPredecessor(0))) {
244 HBasicBlock* to_swap = header->GetPredecessor(0);
245 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
246 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100247 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000248 header->predecessors_[pred] = to_swap;
249 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100250 break;
251 }
252 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100253 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100254
255 // Place the suspend check at the beginning of the header, so that live registers
256 // will be known when allocating registers. Note that code generation can still
257 // generate the suspend check at the back edge, but needs to be careful with
258 // loop phi spill slots (which are not written to at back edge).
259 HInstruction* first_instruction = header->GetFirstInstruction();
260 if (!first_instruction->IsSuspendCheck()) {
261 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
262 header->InsertInstructionBefore(check, first_instruction);
263 first_instruction = check;
264 }
265 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100266}
267
David Brazdilffee3d32015-07-06 11:48:53 +0100268static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Marko60584552015-09-03 13:35:12 +0000269 HBasicBlock* predecessor = block.GetPredecessor(pred_idx);
David Brazdilffee3d32015-07-06 11:48:53 +0100270 if (!predecessor->EndsWithTryBoundary()) {
271 // Only edges from HTryBoundary can be exceptional.
272 return false;
273 }
274 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
275 if (try_boundary->GetNormalFlowSuccessor() == &block) {
276 // This block is the normal-flow successor of `try_boundary`, but it could
277 // also be one of its exception handlers if catch blocks have not been
278 // simplified yet. Predecessors are unordered, so we will consider the first
279 // occurrence to be the normal edge and a possible second occurrence to be
280 // the exceptional edge.
281 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
282 } else {
283 // This is not the normal-flow successor of `try_boundary`, hence it must be
284 // one of its exception handlers.
285 DCHECK(try_boundary->HasExceptionHandler(block));
286 return true;
287 }
288}
289
290void HGraph::SimplifyCatchBlocks() {
291 for (size_t i = 0; i < blocks_.Size(); ++i) {
292 HBasicBlock* catch_block = blocks_.Get(i);
293 if (!catch_block->IsCatchBlock()) {
294 continue;
295 }
296
297 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100299 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
300 exceptional_predecessors_only = false;
301 break;
302 }
303 }
304
305 if (!exceptional_predecessors_only) {
306 // Catch block has normal-flow predecessors and needs to be simplified.
307 // Splitting the block before its first instruction moves all its
308 // instructions into `normal_block` and links the two blocks with a Goto.
309 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
310 // leaving `catch_block` with the exceptional edges only.
311 // Note that catch blocks with normal-flow predecessors cannot begin with
312 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
313 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
314 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000315 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100316 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000317 catch_block->GetPredecessor(j)->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100318 --j;
319 }
320 }
321 }
322 }
323}
324
325void HGraph::ComputeTryBlockInformation() {
326 // Iterate in reverse post order to propagate try membership information from
327 // predecessors to their successors.
328 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
329 HBasicBlock* block = it.Current();
330 if (block->IsEntryBlock() || block->IsCatchBlock()) {
331 // Catch blocks after simplification have only exceptional predecessors
332 // and hence are never in tries.
333 continue;
334 }
335
336 // Infer try membership from the first predecessor. Having simplified loops,
337 // the first predecessor can never be a back edge and therefore it must have
338 // been visited already and had its try membership set.
Vladimir Marko60584552015-09-03 13:35:12 +0000339 HBasicBlock* first_predecessor = block->GetPredecessor(0);
David Brazdilffee3d32015-07-06 11:48:53 +0100340 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100341 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
342 if (try_entry != nullptr) {
343 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
344 }
David Brazdilffee3d32015-07-06 11:48:53 +0100345 }
346}
347
David Brazdilbbd733e2015-08-18 17:48:17 +0100348bool HGraph::HasTryCatch() const {
349 for (size_t i = 0, e = blocks_.Size(); i < e; ++i) {
350 HBasicBlock* block = blocks_.Get(i);
351 if (block != nullptr && (block->IsTryBlock() || block->IsCatchBlock())) {
352 return true;
353 }
354 }
355 return false;
356}
357
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100358void HGraph::SimplifyCFG() {
359 // Simplify the CFG for future analysis, and code generation:
360 // (1): Split critical edges.
361 // (2): Simplify loops by having only one back edge, and one preheader.
362 for (size_t i = 0; i < blocks_.Size(); ++i) {
363 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100364 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100365 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000366 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
367 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100368 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000369 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100370 SplitCriticalEdge(block, successor);
371 --j;
372 }
373 }
374 }
375 if (block->IsLoopHeader()) {
376 SimplifyLoop(block);
377 }
378 }
379}
380
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000381bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100382 // Order does not matter.
383 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
384 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100385 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100386 if (block->IsCatchBlock()) {
387 // TODO: Dealing with exceptional back edges could be tricky because
388 // they only approximate the real control flow. Bail out for now.
389 return false;
390 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100391 HLoopInformation* info = block->GetLoopInformation();
392 if (!info->Populate()) {
393 // Abort if the loop is non natural. We currently bailout in such cases.
394 return false;
395 }
396 }
397 }
398 return true;
399}
400
David Brazdil8d5b8b22015-03-24 10:51:52 +0000401void HGraph::InsertConstant(HConstant* constant) {
402 // New constants are inserted before the final control-flow instruction
403 // of the graph, or at its end if called from the graph builder.
404 if (entry_block_->EndsWithControlFlowInstruction()) {
405 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000406 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000407 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000408 }
409}
410
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000411HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100412 // For simplicity, don't bother reviving the cached null constant if it is
413 // not null and not in a block. Otherwise, we need to clear the instruction
414 // id and/or any invariants the graph is assuming when adding new instructions.
415 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000416 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000417 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000418 }
419 return cached_null_constant_;
420}
421
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100422HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100423 // For simplicity, don't bother reviving the cached current method if it is
424 // not null and not in a block. Otherwise, we need to clear the instruction
425 // id and/or any invariants the graph is assuming when adding new instructions.
426 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700427 cached_current_method_ = new (arena_) HCurrentMethod(
428 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100429 if (entry_block_->GetFirstInstruction() == nullptr) {
430 entry_block_->AddInstruction(cached_current_method_);
431 } else {
432 entry_block_->InsertInstructionBefore(
433 cached_current_method_, entry_block_->GetFirstInstruction());
434 }
435 }
436 return cached_current_method_;
437}
438
David Brazdil8d5b8b22015-03-24 10:51:52 +0000439HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
440 switch (type) {
441 case Primitive::Type::kPrimBoolean:
442 DCHECK(IsUint<1>(value));
443 FALLTHROUGH_INTENDED;
444 case Primitive::Type::kPrimByte:
445 case Primitive::Type::kPrimChar:
446 case Primitive::Type::kPrimShort:
447 case Primitive::Type::kPrimInt:
448 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
449 return GetIntConstant(static_cast<int32_t>(value));
450
451 case Primitive::Type::kPrimLong:
452 return GetLongConstant(value);
453
454 default:
455 LOG(FATAL) << "Unsupported constant type";
456 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000457 }
David Brazdil46e2a392015-03-16 17:31:52 +0000458}
459
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000460void HGraph::CacheFloatConstant(HFloatConstant* constant) {
461 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
462 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
463 cached_float_constants_.Overwrite(value, constant);
464}
465
466void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
467 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
468 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
469 cached_double_constants_.Overwrite(value, constant);
470}
471
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000472void HLoopInformation::Add(HBasicBlock* block) {
473 blocks_.SetBit(block->GetBlockId());
474}
475
David Brazdil46e2a392015-03-16 17:31:52 +0000476void HLoopInformation::Remove(HBasicBlock* block) {
477 blocks_.ClearBit(block->GetBlockId());
478}
479
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100480void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
481 if (blocks_.IsBitSet(block->GetBlockId())) {
482 return;
483 }
484
485 blocks_.SetBit(block->GetBlockId());
486 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000487 for (HBasicBlock* predecessor : block->GetPredecessors()) {
488 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100489 }
490}
491
492bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100493 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100494 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
495 HBasicBlock* back_edge = GetBackEdges().Get(i);
496 DCHECK(back_edge->GetDominator() != nullptr);
497 if (!header_->Dominates(back_edge)) {
498 // This loop is not natural. Do not bother going further.
499 return false;
500 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100501
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100502 // Populate this loop: starting with the back edge, recursively add predecessors
503 // that are not already part of that loop. Set the header as part of the loop
504 // to end the recursion.
505 // This is a recursive implementation of the algorithm described in
506 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
507 blocks_.SetBit(header_->GetBlockId());
508 PopulateRecursive(back_edge);
509 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100510 return true;
511}
512
David Brazdila4b8c212015-05-07 09:59:30 +0100513void HLoopInformation::Update() {
514 HGraph* graph = header_->GetGraph();
515 for (uint32_t id : blocks_.Indexes()) {
516 HBasicBlock* block = graph->GetBlocks().Get(id);
517 // Reset loop information of non-header blocks inside the loop, except
518 // members of inner nested loops because those should already have been
519 // updated by their own LoopInformation.
520 if (block->GetLoopInformation() == this && block != header_) {
521 block->SetLoopInformation(nullptr);
522 }
523 }
524 blocks_.ClearAllBits();
525
526 if (back_edges_.IsEmpty()) {
527 // The loop has been dismantled, delete its suspend check and remove info
528 // from the header.
529 DCHECK(HasSuspendCheck());
530 header_->RemoveInstruction(suspend_check_);
531 header_->SetLoopInformation(nullptr);
532 header_ = nullptr;
533 suspend_check_ = nullptr;
534 } else {
535 if (kIsDebugBuild) {
536 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
537 DCHECK(header_->Dominates(back_edges_.Get(i)));
538 }
539 }
540 // This loop still has reachable back edges. Repopulate the list of blocks.
541 bool populate_successful = Populate();
542 DCHECK(populate_successful);
543 }
544}
545
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100546HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100547 return header_->GetDominator();
548}
549
550bool HLoopInformation::Contains(const HBasicBlock& block) const {
551 return blocks_.IsBitSet(block.GetBlockId());
552}
553
554bool HLoopInformation::IsIn(const HLoopInformation& other) const {
555 return other.blocks_.IsBitSet(header_->GetBlockId());
556}
557
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100558size_t HLoopInformation::GetLifetimeEnd() const {
559 size_t last_position = 0;
560 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
561 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
562 }
563 return last_position;
564}
565
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100566bool HBasicBlock::Dominates(HBasicBlock* other) const {
567 // Walk up the dominator tree from `other`, to find out if `this`
568 // is an ancestor.
569 HBasicBlock* current = other;
570 while (current != nullptr) {
571 if (current == this) {
572 return true;
573 }
574 current = current->GetDominator();
575 }
576 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100577}
578
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100579static void UpdateInputsUsers(HInstruction* instruction) {
580 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
581 instruction->InputAt(i)->AddUseAt(instruction, i);
582 }
583 // Environment should be created later.
584 DCHECK(!instruction->HasEnvironment());
585}
586
Roland Levillainccc07a92014-09-16 14:48:16 +0100587void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
588 HInstruction* replacement) {
589 DCHECK(initial->GetBlock() == this);
590 InsertInstructionBefore(replacement, initial);
591 initial->ReplaceWith(replacement);
592 RemoveInstruction(initial);
593}
594
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100595static void Add(HInstructionList* instruction_list,
596 HBasicBlock* block,
597 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000598 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000599 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100600 instruction->SetBlock(block);
601 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100602 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100603 instruction_list->AddInstruction(instruction);
604}
605
606void HBasicBlock::AddInstruction(HInstruction* instruction) {
607 Add(&instructions_, this, instruction);
608}
609
610void HBasicBlock::AddPhi(HPhi* phi) {
611 Add(&phis_, this, phi);
612}
613
David Brazdilc3d743f2015-04-22 13:40:50 +0100614void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
615 DCHECK(!cursor->IsPhi());
616 DCHECK(!instruction->IsPhi());
617 DCHECK_EQ(instruction->GetId(), -1);
618 DCHECK_NE(cursor->GetId(), -1);
619 DCHECK_EQ(cursor->GetBlock(), this);
620 DCHECK(!instruction->IsControlFlow());
621 instruction->SetBlock(this);
622 instruction->SetId(GetGraph()->GetNextInstructionId());
623 UpdateInputsUsers(instruction);
624 instructions_.InsertInstructionBefore(instruction, cursor);
625}
626
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100627void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
628 DCHECK(!cursor->IsPhi());
629 DCHECK(!instruction->IsPhi());
630 DCHECK_EQ(instruction->GetId(), -1);
631 DCHECK_NE(cursor->GetId(), -1);
632 DCHECK_EQ(cursor->GetBlock(), this);
633 DCHECK(!instruction->IsControlFlow());
634 DCHECK(!cursor->IsControlFlow());
635 instruction->SetBlock(this);
636 instruction->SetId(GetGraph()->GetNextInstructionId());
637 UpdateInputsUsers(instruction);
638 instructions_.InsertInstructionAfter(instruction, cursor);
639}
640
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100641void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
642 DCHECK_EQ(phi->GetId(), -1);
643 DCHECK_NE(cursor->GetId(), -1);
644 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100645 phi->SetBlock(this);
646 phi->SetId(GetGraph()->GetNextInstructionId());
647 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100648 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100649}
650
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100651static void Remove(HInstructionList* instruction_list,
652 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000653 HInstruction* instruction,
654 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100655 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100656 instruction->SetBlock(nullptr);
657 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000658 if (ensure_safety) {
659 DCHECK(instruction->GetUses().IsEmpty());
660 DCHECK(instruction->GetEnvUses().IsEmpty());
661 RemoveAsUser(instruction);
662 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100663}
664
David Brazdil1abb4192015-02-17 18:33:36 +0000665void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100666 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000667 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100668}
669
David Brazdil1abb4192015-02-17 18:33:36 +0000670void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
671 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100672}
673
David Brazdilc7508e92015-04-27 13:28:57 +0100674void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
675 if (instruction->IsPhi()) {
676 RemovePhi(instruction->AsPhi(), ensure_safety);
677 } else {
678 RemoveInstruction(instruction, ensure_safety);
679 }
680}
681
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100682void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
683 for (size_t i = 0; i < locals.Size(); i++) {
684 HInstruction* instruction = locals.Get(i);
685 SetRawEnvAt(i, instruction);
686 if (instruction != nullptr) {
687 instruction->AddEnvUseAt(this, i);
688 }
689 }
690}
691
David Brazdiled596192015-01-23 10:39:45 +0000692void HEnvironment::CopyFrom(HEnvironment* env) {
693 for (size_t i = 0; i < env->Size(); i++) {
694 HInstruction* instruction = env->GetInstructionAt(i);
695 SetRawEnvAt(i, instruction);
696 if (instruction != nullptr) {
697 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100698 }
David Brazdiled596192015-01-23 10:39:45 +0000699 }
700}
701
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700702void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
703 HBasicBlock* loop_header) {
704 DCHECK(loop_header->IsLoopHeader());
705 for (size_t i = 0; i < env->Size(); i++) {
706 HInstruction* instruction = env->GetInstructionAt(i);
707 SetRawEnvAt(i, instruction);
708 if (instruction == nullptr) {
709 continue;
710 }
711 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
712 // At the end of the loop pre-header, the corresponding value for instruction
713 // is the first input of the phi.
714 HInstruction* initial = instruction->AsPhi()->InputAt(0);
715 DCHECK(initial->GetBlock()->Dominates(loop_header));
716 SetRawEnvAt(i, initial);
717 initial->AddEnvUseAt(this, i);
718 } else {
719 instruction->AddEnvUseAt(this, i);
720 }
721 }
722}
723
David Brazdil1abb4192015-02-17 18:33:36 +0000724void HEnvironment::RemoveAsUserOfInput(size_t index) const {
725 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
726 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100727}
728
Calin Juravle77520bc2015-01-12 18:45:46 +0000729HInstruction* HInstruction::GetNextDisregardingMoves() const {
730 HInstruction* next = GetNext();
731 while (next != nullptr && next->IsParallelMove()) {
732 next = next->GetNext();
733 }
734 return next;
735}
736
737HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
738 HInstruction* previous = GetPrevious();
739 while (previous != nullptr && previous->IsParallelMove()) {
740 previous = previous->GetPrevious();
741 }
742 return previous;
743}
744
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100745void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000746 if (first_instruction_ == nullptr) {
747 DCHECK(last_instruction_ == nullptr);
748 first_instruction_ = last_instruction_ = instruction;
749 } else {
750 last_instruction_->next_ = instruction;
751 instruction->previous_ = last_instruction_;
752 last_instruction_ = instruction;
753 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000754}
755
David Brazdilc3d743f2015-04-22 13:40:50 +0100756void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
757 DCHECK(Contains(cursor));
758 if (cursor == first_instruction_) {
759 cursor->previous_ = instruction;
760 instruction->next_ = cursor;
761 first_instruction_ = instruction;
762 } else {
763 instruction->previous_ = cursor->previous_;
764 instruction->next_ = cursor;
765 cursor->previous_ = instruction;
766 instruction->previous_->next_ = instruction;
767 }
768}
769
770void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
771 DCHECK(Contains(cursor));
772 if (cursor == last_instruction_) {
773 cursor->next_ = instruction;
774 instruction->previous_ = cursor;
775 last_instruction_ = instruction;
776 } else {
777 instruction->next_ = cursor->next_;
778 instruction->previous_ = cursor;
779 cursor->next_ = instruction;
780 instruction->next_->previous_ = instruction;
781 }
782}
783
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100784void HInstructionList::RemoveInstruction(HInstruction* instruction) {
785 if (instruction->previous_ != nullptr) {
786 instruction->previous_->next_ = instruction->next_;
787 }
788 if (instruction->next_ != nullptr) {
789 instruction->next_->previous_ = instruction->previous_;
790 }
791 if (instruction == first_instruction_) {
792 first_instruction_ = instruction->next_;
793 }
794 if (instruction == last_instruction_) {
795 last_instruction_ = instruction->previous_;
796 }
797}
798
Roland Levillain6b469232014-09-25 10:10:38 +0100799bool HInstructionList::Contains(HInstruction* instruction) const {
800 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
801 if (it.Current() == instruction) {
802 return true;
803 }
804 }
805 return false;
806}
807
Roland Levillainccc07a92014-09-16 14:48:16 +0100808bool HInstructionList::FoundBefore(const HInstruction* instruction1,
809 const HInstruction* instruction2) const {
810 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
811 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
812 if (it.Current() == instruction1) {
813 return true;
814 }
815 if (it.Current() == instruction2) {
816 return false;
817 }
818 }
819 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
820 return true;
821}
822
Roland Levillain6c82d402014-10-13 16:10:27 +0100823bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
824 if (other_instruction == this) {
825 // An instruction does not strictly dominate itself.
826 return false;
827 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100828 HBasicBlock* block = GetBlock();
829 HBasicBlock* other_block = other_instruction->GetBlock();
830 if (block != other_block) {
831 return GetBlock()->Dominates(other_instruction->GetBlock());
832 } else {
833 // If both instructions are in the same block, ensure this
834 // instruction comes before `other_instruction`.
835 if (IsPhi()) {
836 if (!other_instruction->IsPhi()) {
837 // Phis appear before non phi-instructions so this instruction
838 // dominates `other_instruction`.
839 return true;
840 } else {
841 // There is no order among phis.
842 LOG(FATAL) << "There is no dominance between phis of a same block.";
843 return false;
844 }
845 } else {
846 // `this` is not a phi.
847 if (other_instruction->IsPhi()) {
848 // Phis appear before non phi-instructions so this instruction
849 // does not dominate `other_instruction`.
850 return false;
851 } else {
852 // Check whether this instruction comes before
853 // `other_instruction` in the instruction list.
854 return block->GetInstructions().FoundBefore(this, other_instruction);
855 }
856 }
857 }
858}
859
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100860void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100861 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000862 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
863 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100864 HInstruction* user = current->GetUser();
865 size_t input_index = current->GetIndex();
866 user->SetRawInputAt(input_index, other);
867 other->AddUseAt(user, input_index);
868 }
869
David Brazdiled596192015-01-23 10:39:45 +0000870 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
871 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100872 HEnvironment* user = current->GetUser();
873 size_t input_index = current->GetIndex();
874 user->SetRawEnvAt(input_index, other);
875 other->AddEnvUseAt(user, input_index);
876 }
877
David Brazdiled596192015-01-23 10:39:45 +0000878 uses_.Clear();
879 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100880}
881
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100882void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000883 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100884 SetRawInputAt(index, replacement);
885 replacement->AddUseAt(this, index);
886}
887
Nicolas Geoffray39468442014-09-02 15:17:15 +0100888size_t HInstruction::EnvironmentSize() const {
889 return HasEnvironment() ? environment_->Size() : 0;
890}
891
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100892void HPhi::AddInput(HInstruction* input) {
893 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000894 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895 input->AddUseAt(this, inputs_.Size() - 1);
896}
897
David Brazdil2d7352b2015-04-20 14:52:42 +0100898void HPhi::RemoveInputAt(size_t index) {
899 RemoveAsUserOfInput(index);
900 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100901 for (size_t i = index, e = InputCount(); i < e; ++i) {
902 InputRecordAt(i).GetUseNode()->SetIndex(i);
903 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100904}
905
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100906#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000907void H##name::Accept(HGraphVisitor* visitor) { \
908 visitor->Visit##name(this); \
909}
910
911FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
912
913#undef DEFINE_ACCEPT
914
915void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100916 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
917 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000918 HBasicBlock* block = blocks.Get(i);
919 if (block != nullptr) {
920 VisitBasicBlock(block);
921 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000922 }
923}
924
Roland Levillain633021e2014-10-01 14:12:25 +0100925void HGraphVisitor::VisitReversePostOrder() {
926 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
927 VisitBasicBlock(it.Current());
928 }
929}
930
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000931void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100932 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100933 it.Current()->Accept(this);
934 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100935 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000936 it.Current()->Accept(this);
937 }
938}
939
Mark Mendelle82549b2015-05-06 10:55:34 -0400940HConstant* HTypeConversion::TryStaticEvaluation() const {
941 HGraph* graph = GetBlock()->GetGraph();
942 if (GetInput()->IsIntConstant()) {
943 int32_t value = GetInput()->AsIntConstant()->GetValue();
944 switch (GetResultType()) {
945 case Primitive::kPrimLong:
946 return graph->GetLongConstant(static_cast<int64_t>(value));
947 case Primitive::kPrimFloat:
948 return graph->GetFloatConstant(static_cast<float>(value));
949 case Primitive::kPrimDouble:
950 return graph->GetDoubleConstant(static_cast<double>(value));
951 default:
952 return nullptr;
953 }
954 } else if (GetInput()->IsLongConstant()) {
955 int64_t value = GetInput()->AsLongConstant()->GetValue();
956 switch (GetResultType()) {
957 case Primitive::kPrimInt:
958 return graph->GetIntConstant(static_cast<int32_t>(value));
959 case Primitive::kPrimFloat:
960 return graph->GetFloatConstant(static_cast<float>(value));
961 case Primitive::kPrimDouble:
962 return graph->GetDoubleConstant(static_cast<double>(value));
963 default:
964 return nullptr;
965 }
966 } else if (GetInput()->IsFloatConstant()) {
967 float value = GetInput()->AsFloatConstant()->GetValue();
968 switch (GetResultType()) {
969 case Primitive::kPrimInt:
970 if (std::isnan(value))
971 return graph->GetIntConstant(0);
972 if (value >= kPrimIntMax)
973 return graph->GetIntConstant(kPrimIntMax);
974 if (value <= kPrimIntMin)
975 return graph->GetIntConstant(kPrimIntMin);
976 return graph->GetIntConstant(static_cast<int32_t>(value));
977 case Primitive::kPrimLong:
978 if (std::isnan(value))
979 return graph->GetLongConstant(0);
980 if (value >= kPrimLongMax)
981 return graph->GetLongConstant(kPrimLongMax);
982 if (value <= kPrimLongMin)
983 return graph->GetLongConstant(kPrimLongMin);
984 return graph->GetLongConstant(static_cast<int64_t>(value));
985 case Primitive::kPrimDouble:
986 return graph->GetDoubleConstant(static_cast<double>(value));
987 default:
988 return nullptr;
989 }
990 } else if (GetInput()->IsDoubleConstant()) {
991 double value = GetInput()->AsDoubleConstant()->GetValue();
992 switch (GetResultType()) {
993 case Primitive::kPrimInt:
994 if (std::isnan(value))
995 return graph->GetIntConstant(0);
996 if (value >= kPrimIntMax)
997 return graph->GetIntConstant(kPrimIntMax);
998 if (value <= kPrimLongMin)
999 return graph->GetIntConstant(kPrimIntMin);
1000 return graph->GetIntConstant(static_cast<int32_t>(value));
1001 case Primitive::kPrimLong:
1002 if (std::isnan(value))
1003 return graph->GetLongConstant(0);
1004 if (value >= kPrimLongMax)
1005 return graph->GetLongConstant(kPrimLongMax);
1006 if (value <= kPrimLongMin)
1007 return graph->GetLongConstant(kPrimLongMin);
1008 return graph->GetLongConstant(static_cast<int64_t>(value));
1009 case Primitive::kPrimFloat:
1010 return graph->GetFloatConstant(static_cast<float>(value));
1011 default:
1012 return nullptr;
1013 }
1014 }
1015 return nullptr;
1016}
1017
Roland Levillain9240d6a2014-10-20 16:47:04 +01001018HConstant* HUnaryOperation::TryStaticEvaluation() const {
1019 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001020 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001021 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001022 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001023 }
1024 return nullptr;
1025}
1026
1027HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001028 if (GetLeft()->IsIntConstant()) {
1029 if (GetRight()->IsIntConstant()) {
1030 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1031 } else if (GetRight()->IsLongConstant()) {
1032 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1033 }
1034 } else if (GetLeft()->IsLongConstant()) {
1035 if (GetRight()->IsIntConstant()) {
1036 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1037 } else if (GetRight()->IsLongConstant()) {
1038 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001039 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001040 }
1041 return nullptr;
1042}
Dave Allison20dfc792014-06-16 20:44:29 -07001043
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001044HConstant* HBinaryOperation::GetConstantRight() const {
1045 if (GetRight()->IsConstant()) {
1046 return GetRight()->AsConstant();
1047 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1048 return GetLeft()->AsConstant();
1049 } else {
1050 return nullptr;
1051 }
1052}
1053
1054// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001055// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001056HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1057 HInstruction* most_constant_right = GetConstantRight();
1058 if (most_constant_right == nullptr) {
1059 return nullptr;
1060 } else if (most_constant_right == GetLeft()) {
1061 return GetRight();
1062 } else {
1063 return GetLeft();
1064 }
1065}
1066
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001067bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1068 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001069}
1070
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001071bool HInstruction::Equals(HInstruction* other) const {
1072 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001073 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001074 if (!InstructionDataEquals(other)) return false;
1075 if (GetType() != other->GetType()) return false;
1076 if (InputCount() != other->InputCount()) return false;
1077
1078 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1079 if (InputAt(i) != other->InputAt(i)) return false;
1080 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001081 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001082 return true;
1083}
1084
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001085std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1086#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1087 switch (rhs) {
1088 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1089 default:
1090 os << "Unknown instruction kind " << static_cast<int>(rhs);
1091 break;
1092 }
1093#undef DECLARE_CASE
1094 return os;
1095}
1096
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001097void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001098 next_->previous_ = previous_;
1099 if (previous_ != nullptr) {
1100 previous_->next_ = next_;
1101 }
1102 if (block_->instructions_.first_instruction_ == this) {
1103 block_->instructions_.first_instruction_ = next_;
1104 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001105 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001106
1107 previous_ = cursor->previous_;
1108 if (previous_ != nullptr) {
1109 previous_->next_ = this;
1110 }
1111 next_ = cursor;
1112 cursor->previous_ = this;
1113 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001114
1115 if (block_->instructions_.first_instruction_ == cursor) {
1116 block_->instructions_.first_instruction_ = this;
1117 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001118}
1119
David Brazdilfc6a86a2015-06-26 10:33:45 +00001120HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1121 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1122 DCHECK_EQ(cursor->GetBlock(), this);
1123
1124 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1125 new_block->instructions_.first_instruction_ = cursor;
1126 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1127 instructions_.last_instruction_ = cursor->previous_;
1128 if (cursor->previous_ == nullptr) {
1129 instructions_.first_instruction_ = nullptr;
1130 } else {
1131 cursor->previous_->next_ = nullptr;
1132 cursor->previous_ = nullptr;
1133 }
1134
1135 new_block->instructions_.SetBlockOfInstructions(new_block);
1136 AddInstruction(new (GetGraph()->GetArena()) HGoto());
1137
Vladimir Marko60584552015-09-03 13:35:12 +00001138 for (HBasicBlock* successor : GetSuccessors()) {
1139 new_block->successors_.push_back(successor);
1140 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001141 }
Vladimir Marko60584552015-09-03 13:35:12 +00001142 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001143 AddSuccessor(new_block);
1144
David Brazdil56e1acc2015-06-30 15:41:36 +01001145 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001146 return new_block;
1147}
1148
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001149HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1150 DCHECK(!cursor->IsControlFlow());
1151 DCHECK_NE(instructions_.last_instruction_, cursor);
1152 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001153
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001154 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1155 new_block->instructions_.first_instruction_ = cursor->GetNext();
1156 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1157 cursor->next_->previous_ = nullptr;
1158 cursor->next_ = nullptr;
1159 instructions_.last_instruction_ = cursor;
1160
1161 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001162 for (HBasicBlock* successor : GetSuccessors()) {
1163 new_block->successors_.push_back(successor);
1164 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001165 }
Vladimir Marko60584552015-09-03 13:35:12 +00001166 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001167
Vladimir Marko60584552015-09-03 13:35:12 +00001168 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001169 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001170 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001171 }
Vladimir Marko60584552015-09-03 13:35:12 +00001172 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001173 return new_block;
1174}
1175
David Brazdilec16f792015-08-19 15:04:01 +01001176const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001177 if (EndsWithTryBoundary()) {
1178 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1179 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001180 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001181 return try_boundary;
1182 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001183 DCHECK(IsTryBlock());
1184 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001185 return nullptr;
1186 }
David Brazdilec16f792015-08-19 15:04:01 +01001187 } else if (IsTryBlock()) {
1188 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001189 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001190 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001191 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001192}
1193
1194static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1195 return block.GetPhis().IsEmpty()
1196 && !block.GetInstructions().IsEmpty()
1197 && block.GetFirstInstruction() == block.GetLastInstruction();
1198}
1199
David Brazdil46e2a392015-03-16 17:31:52 +00001200bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001201 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1202}
1203
1204bool HBasicBlock::IsSingleTryBoundary() const {
1205 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001206}
1207
David Brazdil8d5b8b22015-03-24 10:51:52 +00001208bool HBasicBlock::EndsWithControlFlowInstruction() const {
1209 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1210}
1211
David Brazdilb2bd1c52015-03-25 11:17:37 +00001212bool HBasicBlock::EndsWithIf() const {
1213 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1214}
1215
David Brazdilffee3d32015-07-06 11:48:53 +01001216bool HBasicBlock::EndsWithTryBoundary() const {
1217 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1218}
1219
David Brazdilb2bd1c52015-03-25 11:17:37 +00001220bool HBasicBlock::HasSinglePhi() const {
1221 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1222}
1223
David Brazdilffee3d32015-07-06 11:48:53 +01001224bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001225 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001226 return false;
1227 }
1228
David Brazdilb618ade2015-07-29 10:31:29 +01001229 // Exception handlers need to be stored in the same order.
1230 for (HExceptionHandlerIterator it1(*this), it2(other);
1231 !it1.Done();
1232 it1.Advance(), it2.Advance()) {
1233 DCHECK(!it2.Done());
1234 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001235 return false;
1236 }
1237 }
1238 return true;
1239}
1240
David Brazdil2d7352b2015-04-20 14:52:42 +01001241size_t HInstructionList::CountSize() const {
1242 size_t size = 0;
1243 HInstruction* current = first_instruction_;
1244 for (; current != nullptr; current = current->GetNext()) {
1245 size++;
1246 }
1247 return size;
1248}
1249
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001250void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1251 for (HInstruction* current = first_instruction_;
1252 current != nullptr;
1253 current = current->GetNext()) {
1254 current->SetBlock(block);
1255 }
1256}
1257
1258void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1259 DCHECK(Contains(cursor));
1260 if (!instruction_list.IsEmpty()) {
1261 if (cursor == last_instruction_) {
1262 last_instruction_ = instruction_list.last_instruction_;
1263 } else {
1264 cursor->next_->previous_ = instruction_list.last_instruction_;
1265 }
1266 instruction_list.last_instruction_->next_ = cursor->next_;
1267 cursor->next_ = instruction_list.first_instruction_;
1268 instruction_list.first_instruction_->previous_ = cursor;
1269 }
1270}
1271
1272void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001273 if (IsEmpty()) {
1274 first_instruction_ = instruction_list.first_instruction_;
1275 last_instruction_ = instruction_list.last_instruction_;
1276 } else {
1277 AddAfter(last_instruction_, instruction_list);
1278 }
1279}
1280
David Brazdil2d7352b2015-04-20 14:52:42 +01001281void HBasicBlock::DisconnectAndDelete() {
1282 // Dominators must be removed after all the blocks they dominate. This way
1283 // a loop header is removed last, a requirement for correct loop information
1284 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001285 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001286
David Brazdil2d7352b2015-04-20 14:52:42 +01001287 // Remove the block from all loops it is included in.
1288 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1289 HLoopInformation* loop_info = it.Current();
1290 loop_info->Remove(this);
1291 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001292 // If this was the last back edge of the loop, we deliberately leave the
1293 // loop in an inconsistent state and will fail SSAChecker unless the
1294 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001295 loop_info->RemoveBackEdge(this);
1296 }
1297 }
1298
1299 // Disconnect the block from its predecessors and update their control-flow
1300 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001301 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001302 HInstruction* last_instruction = predecessor->GetLastInstruction();
1303 predecessor->RemoveInstruction(last_instruction);
1304 predecessor->RemoveSuccessor(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001305 if (predecessor->GetSuccessors().size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001306 DCHECK(last_instruction->IsIf());
1307 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1308 } else {
1309 // The predecessor has no remaining successors and therefore must be dead.
1310 // We deliberately leave it without a control-flow instruction so that the
1311 // SSAChecker fails unless it is not removed during the pass too.
Vladimir Marko60584552015-09-03 13:35:12 +00001312 DCHECK_EQ(predecessor->GetSuccessors().size(), 0u);
David Brazdil2d7352b2015-04-20 14:52:42 +01001313 }
David Brazdil46e2a392015-03-16 17:31:52 +00001314 }
Vladimir Marko60584552015-09-03 13:35:12 +00001315 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001316
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001317 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001318 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001319 // Delete this block from the list of predecessors.
1320 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001321 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001322
1323 // Check that `successor` has other predecessors, otherwise `this` is the
1324 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001325 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001326
David Brazdil2d7352b2015-04-20 14:52:42 +01001327 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001328 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001329 // The successor has just one predecessor left. Replace phis with the only
1330 // remaining input.
1331 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1332 HPhi* phi = phi_it.Current()->AsPhi();
1333 phi->ReplaceWith(phi->InputAt(1 - this_index));
1334 successor->RemovePhi(phi);
1335 }
1336 } else {
1337 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1338 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1339 }
1340 }
1341 }
Vladimir Marko60584552015-09-03 13:35:12 +00001342 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001343
1344 // Disconnect from the dominator.
1345 dominator_->RemoveDominatedBlock(this);
1346 SetDominator(nullptr);
1347
1348 // Delete from the graph. The function safely deletes remaining instructions
1349 // and updates the reverse post order.
1350 graph_->DeleteDeadBlock(this);
1351 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001352}
1353
1354void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001355 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001356 DCHECK(ContainsElement(dominated_blocks_, other));
1357 DCHECK_EQ(GetSingleSuccessor(), other);
1358 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001359 DCHECK(other->GetPhis().IsEmpty());
1360
David Brazdil2d7352b2015-04-20 14:52:42 +01001361 // Move instructions from `other` to `this`.
1362 DCHECK(EndsWithControlFlowInstruction());
1363 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001364 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001365 other->instructions_.SetBlockOfInstructions(this);
1366 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001367
David Brazdil2d7352b2015-04-20 14:52:42 +01001368 // Remove `other` from the loops it is included in.
1369 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1370 HLoopInformation* loop_info = it.Current();
1371 loop_info->Remove(other);
1372 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001373 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001374 }
1375 }
1376
1377 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001378 successors_.clear();
1379 while (!other->successors_.empty()) {
1380 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001381 successor->ReplacePredecessor(other, this);
1382 }
1383
David Brazdil2d7352b2015-04-20 14:52:42 +01001384 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001385 RemoveDominatedBlock(other);
1386 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1387 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001388 dominated->SetDominator(this);
1389 }
Vladimir Marko60584552015-09-03 13:35:12 +00001390 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001391 other->dominator_ = nullptr;
1392
1393 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001394 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001395
1396 // Delete `other` from the graph. The function updates reverse post order.
1397 graph_->DeleteDeadBlock(other);
1398 other->SetGraph(nullptr);
1399}
1400
1401void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1402 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001403 DCHECK(GetDominatedBlocks().empty());
1404 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001405 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001406 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001407 DCHECK(other->GetPhis().IsEmpty());
1408 DCHECK(!other->IsInLoop());
1409
1410 // Move instructions from `other` to `this`.
1411 instructions_.Add(other->GetInstructions());
1412 other->instructions_.SetBlockOfInstructions(this);
1413
1414 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001415 successors_.clear();
1416 while (!other->successors_.empty()) {
1417 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001418 successor->ReplacePredecessor(other, this);
1419 }
1420
1421 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001422 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1423 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001424 dominated->SetDominator(this);
1425 }
Vladimir Marko60584552015-09-03 13:35:12 +00001426 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001427 other->dominator_ = nullptr;
1428 other->graph_ = nullptr;
1429}
1430
1431void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001432 while (!GetPredecessors().empty()) {
1433 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001434 predecessor->ReplaceSuccessor(this, other);
1435 }
Vladimir Marko60584552015-09-03 13:35:12 +00001436 while (!GetSuccessors().empty()) {
1437 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001438 successor->ReplacePredecessor(this, other);
1439 }
Vladimir Marko60584552015-09-03 13:35:12 +00001440 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1441 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001442 }
1443 GetDominator()->ReplaceDominatedBlock(this, other);
1444 other->SetDominator(GetDominator());
1445 dominator_ = nullptr;
1446 graph_ = nullptr;
1447}
1448
1449// Create space in `blocks` for adding `number_of_new_blocks` entries
1450// starting at location `at`. Blocks after `at` are moved accordingly.
1451static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1452 size_t number_of_new_blocks,
1453 size_t at) {
1454 size_t old_size = blocks->Size();
1455 size_t new_size = old_size + number_of_new_blocks;
1456 blocks->SetSize(new_size);
1457 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1458 blocks->Put(j, blocks->Get(i));
1459 }
1460}
1461
David Brazdil2d7352b2015-04-20 14:52:42 +01001462void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1463 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001464 DCHECK(block->GetSuccessors().empty());
1465 DCHECK(block->GetPredecessors().empty());
1466 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001467 DCHECK(block->GetDominator() == nullptr);
1468
1469 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1470 block->RemoveInstruction(it.Current());
1471 }
1472 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1473 block->RemovePhi(it.Current()->AsPhi());
1474 }
1475
David Brazdilc7af85d2015-05-26 12:05:55 +01001476 if (block->IsExitBlock()) {
1477 exit_block_ = nullptr;
1478 }
1479
David Brazdil2d7352b2015-04-20 14:52:42 +01001480 reverse_post_order_.Delete(block);
1481 blocks_.Put(block->GetBlockId(), nullptr);
1482}
1483
Calin Juravle2e768302015-07-28 14:41:11 +00001484HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001485 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001486 // Update the environments in this graph to have the invoke's environment
1487 // as parent.
1488 {
1489 HReversePostOrderIterator it(*this);
1490 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1491 for (; !it.Done(); it.Advance()) {
1492 HBasicBlock* block = it.Current();
1493 for (HInstructionIterator instr_it(block->GetInstructions());
1494 !instr_it.Done();
1495 instr_it.Advance()) {
1496 HInstruction* current = instr_it.Current();
1497 if (current->NeedsEnvironment()) {
1498 current->GetEnvironment()->SetAndCopyParentChain(
1499 outer_graph->GetArena(), invoke->GetEnvironment());
1500 }
1501 }
1502 }
1503 }
1504 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1505 if (HasBoundsChecks()) {
1506 outer_graph->SetHasBoundsChecks(true);
1507 }
1508
Calin Juravle2e768302015-07-28 14:41:11 +00001509 HInstruction* return_value = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001510 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001511 // Simple case of an entry block, a body block, and an exit block.
1512 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001513 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001514 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1515 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001516 DCHECK(!body->IsExitBlock());
1517 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001519 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1520 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001521
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001522 // Replace the invoke with the return value of the inlined graph.
1523 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001524 return_value = last->InputAt(0);
1525 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001526 } else {
1527 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001528 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001529
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001530 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001531 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001532 // Need to inline multiple blocks. We split `invoke`'s block
1533 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001534 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001535 // with the second half.
1536 ArenaAllocator* allocator = outer_graph->GetArena();
1537 HBasicBlock* at = invoke->GetBlock();
1538 HBasicBlock* to = at->SplitAfter(invoke);
1539
Vladimir Marko60584552015-09-03 13:35:12 +00001540 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001541 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001542 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543 exit_block_->ReplaceWith(to);
1544
1545 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001546 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001547 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1548 if (to->GetPredecessors().size() == 1) {
1549 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001550 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001551 if (!returns_void) {
1552 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001553 }
1554 predecessor->AddInstruction(new (allocator) HGoto());
1555 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001556 } else {
1557 if (!returns_void) {
1558 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001559 return_value = new (allocator) HPhi(
1560 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001561 to->AddPhi(return_value->AsPhi());
1562 }
Vladimir Marko60584552015-09-03 13:35:12 +00001563 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001564 HInstruction* last = predecessor->GetLastInstruction();
1565 if (!returns_void) {
1566 return_value->AsPhi()->AddInput(last->InputAt(0));
1567 }
1568 predecessor->AddInstruction(new (allocator) HGoto());
1569 predecessor->RemoveInstruction(last);
1570 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001571 }
1572
1573 if (return_value != nullptr) {
1574 invoke->ReplaceWith(return_value);
1575 }
1576
1577 // Update the meta information surrounding blocks:
1578 // (1) the graph they are now in,
1579 // (2) the reverse post order of that graph,
1580 // (3) the potential loop information they are now in.
1581
1582 // We don't add the entry block, the exit block, and the first block, which
1583 // has been merged with `at`.
1584 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1585
1586 // We add the `to` block.
1587 static constexpr int kNumberOfNewBlocksInCaller = 1;
1588 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1589 + kNumberOfNewBlocksInCaller;
1590
1591 // Find the location of `at` in the outer graph's reverse post order. The new
1592 // blocks will be added after it.
1593 size_t index_of_at = 0;
1594 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1595 index_of_at++;
1596 }
1597 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1598
1599 // Do a reverse post order of the blocks in the callee and do (1), (2),
1600 // and (3) to the blocks that apply.
1601 HLoopInformation* info = at->GetLoopInformation();
1602 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1603 HBasicBlock* current = it.Current();
1604 if (current != exit_block_ && current != entry_block_ && current != first) {
1605 DCHECK(!current->IsInLoop());
1606 DCHECK(current->GetGraph() == this);
1607 current->SetGraph(outer_graph);
1608 outer_graph->AddBlock(current);
1609 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1610 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001611 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001612 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1613 loop_it.Current()->Add(current);
1614 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001615 }
1616 }
1617 }
1618
1619 // Do (1), (2), and (3) to `to`.
1620 to->SetGraph(outer_graph);
1621 outer_graph->AddBlock(to);
1622 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1623 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001624 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001625 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1626 loop_it.Current()->Add(to);
1627 }
David Brazdil46e2a392015-03-16 17:31:52 +00001628 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001629 // Only `to` can become a back edge, as the inlined blocks
1630 // are predecessors of `to`.
1631 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001632 }
1633 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001634 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001635
David Brazdil05144f42015-04-16 15:18:00 +01001636 // Update the next instruction id of the outer graph, so that instructions
1637 // added later get bigger ids than those in the inner graph.
1638 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1639
1640 // Walk over the entry block and:
1641 // - Move constants from the entry block to the outer_graph's entry block,
1642 // - Replace HParameterValue instructions with their real value.
1643 // - Remove suspend checks, that hold an environment.
1644 // We must do this after the other blocks have been inlined, otherwise ids of
1645 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001646 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001647 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1648 HInstruction* current = it.Current();
1649 if (current->IsNullConstant()) {
1650 current->ReplaceWith(outer_graph->GetNullConstant());
1651 } else if (current->IsIntConstant()) {
1652 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1653 } else if (current->IsLongConstant()) {
1654 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001655 } else if (current->IsFloatConstant()) {
1656 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1657 } else if (current->IsDoubleConstant()) {
1658 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001659 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001660 if (kIsDebugBuild
1661 && invoke->IsInvokeStaticOrDirect()
1662 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1663 // Ensure we do not use the last input of `invoke`, as it
1664 // contains a clinit check which is not an actual argument.
1665 size_t last_input_index = invoke->InputCount() - 1;
1666 DCHECK(parameter_index != last_input_index);
1667 }
David Brazdil05144f42015-04-16 15:18:00 +01001668 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001669 } else if (current->IsCurrentMethod()) {
1670 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001671 } else {
1672 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1673 entry_block_->RemoveInstruction(current);
1674 }
1675 }
1676
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001677 // Finally remove the invoke from the caller.
1678 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001679
1680 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001681}
1682
Mingyao Yang3584bce2015-05-19 16:01:59 -07001683/*
1684 * Loop will be transformed to:
1685 * old_pre_header
1686 * |
1687 * if_block
1688 * / \
1689 * dummy_block deopt_block
1690 * \ /
1691 * new_pre_header
1692 * |
1693 * header
1694 */
1695void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1696 DCHECK(header->IsLoopHeader());
1697 HBasicBlock* pre_header = header->GetDominator();
1698
1699 // Need this to avoid critical edge.
1700 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1701 // Need this to avoid critical edge.
1702 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1703 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1704 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1705 AddBlock(if_block);
1706 AddBlock(dummy_block);
1707 AddBlock(deopt_block);
1708 AddBlock(new_pre_header);
1709
1710 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001711 pre_header->successors_.clear();
1712 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001713
1714 pre_header->AddSuccessor(if_block);
1715 if_block->AddSuccessor(dummy_block); // True successor
1716 if_block->AddSuccessor(deopt_block); // False successor
1717 dummy_block->AddSuccessor(new_pre_header);
1718 deopt_block->AddSuccessor(new_pre_header);
1719
Vladimir Marko60584552015-09-03 13:35:12 +00001720 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001721 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001722 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001723 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001724 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001725 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001726 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001727 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001728 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001729 header->SetDominator(new_pre_header);
1730
1731 size_t index_of_header = 0;
1732 while (reverse_post_order_.Get(index_of_header) != header) {
1733 index_of_header++;
1734 }
1735 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1736 reverse_post_order_.Put(index_of_header++, if_block);
1737 reverse_post_order_.Put(index_of_header++, dummy_block);
1738 reverse_post_order_.Put(index_of_header++, deopt_block);
1739 reverse_post_order_.Put(index_of_header++, new_pre_header);
1740
1741 HLoopInformation* info = pre_header->GetLoopInformation();
1742 if (info != nullptr) {
1743 if_block->SetLoopInformation(info);
1744 dummy_block->SetLoopInformation(info);
1745 deopt_block->SetLoopInformation(info);
1746 new_pre_header->SetLoopInformation(info);
1747 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1748 !loop_it.Done();
1749 loop_it.Advance()) {
1750 loop_it.Current()->Add(if_block);
1751 loop_it.Current()->Add(dummy_block);
1752 loop_it.Current()->Add(deopt_block);
1753 loop_it.Current()->Add(new_pre_header);
1754 }
1755 }
1756}
1757
Calin Juravle2e768302015-07-28 14:41:11 +00001758void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1759 if (kIsDebugBuild) {
1760 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1761 ScopedObjectAccess soa(Thread::Current());
1762 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1763 if (IsBoundType()) {
1764 // Having the test here spares us from making the method virtual just for
1765 // the sake of a DCHECK.
1766 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1767 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1768 << " upper_bound_rti: " << upper_bound_rti
1769 << " rti: " << rti;
1770 DCHECK(!upper_bound_rti.GetTypeHandle()->IsFinal() || rti.IsExact());
1771 }
1772 }
1773 reference_type_info_ = rti;
1774}
1775
1776ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1777
1778ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1779 : type_handle_(type_handle), is_exact_(is_exact) {
1780 if (kIsDebugBuild) {
1781 ScopedObjectAccess soa(Thread::Current());
1782 DCHECK(IsValidHandle(type_handle));
1783 }
1784}
1785
Calin Juravleacf735c2015-02-12 15:25:22 +00001786std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1787 ScopedObjectAccess soa(Thread::Current());
1788 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001789 << " is_valid=" << rhs.IsValid()
1790 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001791 << " is_exact=" << rhs.IsExact()
1792 << " ]";
1793 return os;
1794}
1795
Mark Mendellc4701932015-04-10 13:18:51 -04001796bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1797 // For now, assume that instructions in different blocks may use the
1798 // environment.
1799 // TODO: Use the control flow to decide if this is true.
1800 if (GetBlock() != other->GetBlock()) {
1801 return true;
1802 }
1803
1804 // We know that we are in the same block. Walk from 'this' to 'other',
1805 // checking to see if there is any instruction with an environment.
1806 HInstruction* current = this;
1807 for (; current != other && current != nullptr; current = current->GetNext()) {
1808 // This is a conservative check, as the instruction result may not be in
1809 // the referenced environment.
1810 if (current->HasEnvironment()) {
1811 return true;
1812 }
1813 }
1814
1815 // We should have been called with 'this' before 'other' in the block.
1816 // Just confirm this.
1817 DCHECK(current != nullptr);
1818 return false;
1819}
1820
1821void HInstruction::RemoveEnvironmentUsers() {
1822 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1823 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1824 HEnvironment* user = user_node->GetUser();
1825 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1826 }
1827 env_uses_.Clear();
1828}
1829
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001830} // namespace art