blob: 54f4071e2210568d8e866c43601ebe159c4a64f5 [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"
David Brazdilbaf89b82015-09-15 11:36:54 +010023#include "mirror/class-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000024#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000026
27namespace art {
28
29void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010030 block->SetBlockId(blocks_.size());
31 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000032}
33
Nicolas Geoffray804d0932014-05-02 08:46:00 +010034void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010035 ArenaBitVector visiting(arena_, blocks_.size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000036 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000037}
38
Roland Levillainfc600dc2014-12-02 17:16:31 +000039static void RemoveAsUser(HInstruction* instruction) {
40 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000041 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000042 }
43
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010044 for (HEnvironment* environment = instruction->GetEnvironment();
45 environment != nullptr;
46 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000047 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000048 if (environment->GetInstructionAt(i) != nullptr) {
49 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000050 }
51 }
52 }
53}
54
55void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010056 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000057 if (!visited.IsBitSet(i)) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010058 HBasicBlock* block = GetBlock(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010059 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000060 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
61 RemoveAsUser(it.Current());
62 }
63 }
64 }
65}
66
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010067void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010068 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000069 if (!visited.IsBitSet(i)) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010070 HBasicBlock* block = GetBlock(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010071 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +000072 for (HBasicBlock* successor : block->GetSuccessors()) {
73 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +000074 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010075 // Remove the block from the list of blocks, so that further analyses
76 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010077 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000078 }
79 }
80}
81
82void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
83 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010084 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000085 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000086 if (visited->IsBitSet(id)) return;
87
88 visited->SetBit(id);
89 visiting->SetBit(id);
Vladimir Marko60584552015-09-03 13:35:12 +000090 for (HBasicBlock* successor : block->GetSuccessors()) {
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() {
David Brazdilffee3d32015-07-06 11:48:53 +0100101 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
102 // edges. This invariant simplifies building SSA form because Phis cannot
103 // collect both normal- and exceptional-flow values at the same time.
104 SimplifyCatchBlocks();
105
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100106 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000107
David Brazdilffee3d32015-07-06 11:48:53 +0100108 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 FindBackEdges(&visited);
110
David Brazdilffee3d32015-07-06 11:48:53 +0100111 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // the initial DFS as users from other instructions, so that
113 // users can be safely removed before uses later.
114 RemoveInstructionsAsUsersFromDeadBlocks(visited);
115
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000118 // predecessors list of live blocks.
119 RemoveDeadBlocks(visited);
120
David Brazdilffee3d32015-07-06 11:48:53 +0100121 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100122 // dominators and the reverse post order.
123 SimplifyCFG();
124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100126 ComputeDominanceInformation();
127}
128
129void HGraph::ClearDominanceInformation() {
130 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
131 it.Current()->ClearDominanceInformation();
132 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100134}
135
136void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000137 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100138 dominator_ = nullptr;
139}
140
141void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100142 DCHECK(reverse_post_order_.empty());
143 reverse_post_order_.reserve(blocks_.size());
144 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
145 reverse_post_order_.push_back(entry_block_);
Vladimir Marko60584552015-09-03 13:35:12 +0000146 for (HBasicBlock* successor : entry_block_->GetSuccessors()) {
147 VisitBlockForDominatorTree(successor, entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 }
149}
150
151HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100152 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000153 // Walk the dominator tree of the first block and mark the visited blocks.
154 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 visited.SetBit(first->GetBlockId());
156 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 }
158 // Walk the dominator tree of the second block until a marked block is found.
159 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000160 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000161 return second;
162 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000163 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000164 }
165 LOG(ERROR) << "Could not find common dominator";
166 return nullptr;
167}
168
169void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
170 HBasicBlock* predecessor,
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100171 ArenaVector<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000172 if (block->GetDominator() == nullptr) {
173 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000175 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000176 }
177
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.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100180 DCHECK_LT(block->GetBlockId(), visits->size());
181 if (++(*visits)[block->GetBlockId()] ==
Vladimir Marko60584552015-09-03 13:35:12 +0000182 block->GetPredecessors().size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100183 block->GetDominator()->AddDominatedBlock(block);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100184 reverse_post_order_.push_back(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000185 for (HBasicBlock* successor : block->GetSuccessors()) {
186 VisitBlockForDominatorTree(successor, block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 }
188 }
189}
190
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000191void HGraph::TransformToSsa() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100192 DCHECK(!reverse_post_order_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100193 SsaBuilder ssa_builder(this);
194 ssa_builder.BuildSsa();
195}
196
David Brazdilfc6a86a2015-06-26 10:33:45 +0000197HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000198 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
199 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000200 // Use `InsertBetween` to ensure the predecessor index and successor index of
201 // `block` and `successor` are preserved.
202 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000203 return new_block;
204}
205
206void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
207 // Insert a new node between `block` and `successor` to split the
208 // critical edge.
209 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600210 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211 if (successor->IsLoopHeader()) {
212 // If we split at a back edge boundary, make the new block the back edge.
213 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000214 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100215 info->RemoveBackEdge(block);
216 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100217 }
218 }
219}
220
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100221void HGraph::SimplifyLoop(HBasicBlock* header) {
222 HLoopInformation* info = header->GetLoopInformation();
223
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100224 // Make sure the loop has only one pre header. This simplifies SSA building by having
225 // to just look at the pre header to know which locals are initialized at entry of the
226 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000227 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100229 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100230 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600231 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232
Vladimir Marko60584552015-09-03 13:35:12 +0000233 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
234 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100235 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100236 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100237 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100238 }
239 }
240 pre_header->AddSuccessor(header);
241 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100242
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100243 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Marko60584552015-09-03 13:35:12 +0000244 if (info->IsBackEdge(*header->GetPredecessor(0))) {
245 HBasicBlock* to_swap = header->GetPredecessor(0);
246 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
247 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100248 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000249 header->predecessors_[pred] = to_swap;
250 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100251 break;
252 }
253 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100254 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100255
256 // Place the suspend check at the beginning of the header, so that live registers
257 // will be known when allocating registers. Note that code generation can still
258 // generate the suspend check at the back edge, but needs to be careful with
259 // loop phi spill slots (which are not written to at back edge).
260 HInstruction* first_instruction = header->GetFirstInstruction();
261 if (!first_instruction->IsSuspendCheck()) {
262 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
263 header->InsertInstructionBefore(check, first_instruction);
264 first_instruction = check;
265 }
266 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100267}
268
David Brazdilffee3d32015-07-06 11:48:53 +0100269static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Marko60584552015-09-03 13:35:12 +0000270 HBasicBlock* predecessor = block.GetPredecessor(pred_idx);
David Brazdilffee3d32015-07-06 11:48:53 +0100271 if (!predecessor->EndsWithTryBoundary()) {
272 // Only edges from HTryBoundary can be exceptional.
273 return false;
274 }
275 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
276 if (try_boundary->GetNormalFlowSuccessor() == &block) {
277 // This block is the normal-flow successor of `try_boundary`, but it could
278 // also be one of its exception handlers if catch blocks have not been
279 // simplified yet. Predecessors are unordered, so we will consider the first
280 // occurrence to be the normal edge and a possible second occurrence to be
281 // the exceptional edge.
282 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
283 } else {
284 // This is not the normal-flow successor of `try_boundary`, hence it must be
285 // one of its exception handlers.
286 DCHECK(try_boundary->HasExceptionHandler(block));
287 return true;
288 }
289}
290
291void HGraph::SimplifyCatchBlocks() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100292 for (HBasicBlock* catch_block : blocks_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100293 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
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100348void HGraph::SimplifyCFG() {
349 // Simplify the CFG for future analysis, and code generation:
350 // (1): Split critical edges.
351 // (2): Simplify loops by having only one back edge, and one preheader.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100352 for (HBasicBlock* block : blocks_) {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100353 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100354 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000355 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
356 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100357 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000358 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100359 SplitCriticalEdge(block, successor);
360 --j;
361 }
362 }
363 }
364 if (block->IsLoopHeader()) {
365 SimplifyLoop(block);
366 }
367 }
368}
369
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000370bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100371 // Order does not matter.
372 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
373 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100374 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100375 if (block->IsCatchBlock()) {
376 // TODO: Dealing with exceptional back edges could be tricky because
377 // they only approximate the real control flow. Bail out for now.
378 return false;
379 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100380 HLoopInformation* info = block->GetLoopInformation();
381 if (!info->Populate()) {
382 // Abort if the loop is non natural. We currently bailout in such cases.
383 return false;
384 }
385 }
386 }
387 return true;
388}
389
David Brazdil8d5b8b22015-03-24 10:51:52 +0000390void HGraph::InsertConstant(HConstant* constant) {
391 // New constants are inserted before the final control-flow instruction
392 // of the graph, or at its end if called from the graph builder.
393 if (entry_block_->EndsWithControlFlowInstruction()) {
394 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000395 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000396 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000397 }
398}
399
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600400HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100401 // For simplicity, don't bother reviving the cached null constant if it is
402 // not null and not in a block. Otherwise, we need to clear the instruction
403 // id and/or any invariants the graph is assuming when adding new instructions.
404 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600405 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000406 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000407 }
408 return cached_null_constant_;
409}
410
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100411HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100412 // For simplicity, don't bother reviving the cached current method 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_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700416 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600417 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
418 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100419 if (entry_block_->GetFirstInstruction() == nullptr) {
420 entry_block_->AddInstruction(cached_current_method_);
421 } else {
422 entry_block_->InsertInstructionBefore(
423 cached_current_method_, entry_block_->GetFirstInstruction());
424 }
425 }
426 return cached_current_method_;
427}
428
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600429HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000430 switch (type) {
431 case Primitive::Type::kPrimBoolean:
432 DCHECK(IsUint<1>(value));
433 FALLTHROUGH_INTENDED;
434 case Primitive::Type::kPrimByte:
435 case Primitive::Type::kPrimChar:
436 case Primitive::Type::kPrimShort:
437 case Primitive::Type::kPrimInt:
438 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600439 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000440
441 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600442 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000443
444 default:
445 LOG(FATAL) << "Unsupported constant type";
446 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000447 }
David Brazdil46e2a392015-03-16 17:31:52 +0000448}
449
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000450void HGraph::CacheFloatConstant(HFloatConstant* constant) {
451 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
452 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
453 cached_float_constants_.Overwrite(value, constant);
454}
455
456void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
457 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
458 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
459 cached_double_constants_.Overwrite(value, constant);
460}
461
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000462void HLoopInformation::Add(HBasicBlock* block) {
463 blocks_.SetBit(block->GetBlockId());
464}
465
David Brazdil46e2a392015-03-16 17:31:52 +0000466void HLoopInformation::Remove(HBasicBlock* block) {
467 blocks_.ClearBit(block->GetBlockId());
468}
469
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
471 if (blocks_.IsBitSet(block->GetBlockId())) {
472 return;
473 }
474
475 blocks_.SetBit(block->GetBlockId());
476 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000477 for (HBasicBlock* predecessor : block->GetPredecessors()) {
478 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100479 }
480}
481
482bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100483 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100484 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100485 DCHECK(back_edge->GetDominator() != nullptr);
486 if (!header_->Dominates(back_edge)) {
487 // This loop is not natural. Do not bother going further.
488 return false;
489 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100490
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100491 // Populate this loop: starting with the back edge, recursively add predecessors
492 // that are not already part of that loop. Set the header as part of the loop
493 // to end the recursion.
494 // This is a recursive implementation of the algorithm described in
495 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
496 blocks_.SetBit(header_->GetBlockId());
497 PopulateRecursive(back_edge);
498 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100499 return true;
500}
501
David Brazdila4b8c212015-05-07 09:59:30 +0100502void HLoopInformation::Update() {
503 HGraph* graph = header_->GetGraph();
504 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100505 HBasicBlock* block = graph->GetBlock(id);
David Brazdila4b8c212015-05-07 09:59:30 +0100506 // Reset loop information of non-header blocks inside the loop, except
507 // members of inner nested loops because those should already have been
508 // updated by their own LoopInformation.
509 if (block->GetLoopInformation() == this && block != header_) {
510 block->SetLoopInformation(nullptr);
511 }
512 }
513 blocks_.ClearAllBits();
514
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100515 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100516 // The loop has been dismantled, delete its suspend check and remove info
517 // from the header.
518 DCHECK(HasSuspendCheck());
519 header_->RemoveInstruction(suspend_check_);
520 header_->SetLoopInformation(nullptr);
521 header_ = nullptr;
522 suspend_check_ = nullptr;
523 } else {
524 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100525 for (HBasicBlock* back_edge : back_edges_) {
526 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100527 }
528 }
529 // This loop still has reachable back edges. Repopulate the list of blocks.
530 bool populate_successful = Populate();
531 DCHECK(populate_successful);
532 }
533}
534
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100535HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100536 return header_->GetDominator();
537}
538
539bool HLoopInformation::Contains(const HBasicBlock& block) const {
540 return blocks_.IsBitSet(block.GetBlockId());
541}
542
543bool HLoopInformation::IsIn(const HLoopInformation& other) const {
544 return other.blocks_.IsBitSet(header_->GetBlockId());
545}
546
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100547size_t HLoopInformation::GetLifetimeEnd() const {
548 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100549 for (HBasicBlock* back_edge : GetBackEdges()) {
550 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100551 }
552 return last_position;
553}
554
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100555bool HBasicBlock::Dominates(HBasicBlock* other) const {
556 // Walk up the dominator tree from `other`, to find out if `this`
557 // is an ancestor.
558 HBasicBlock* current = other;
559 while (current != nullptr) {
560 if (current == this) {
561 return true;
562 }
563 current = current->GetDominator();
564 }
565 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100566}
567
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100568static void UpdateInputsUsers(HInstruction* instruction) {
569 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
570 instruction->InputAt(i)->AddUseAt(instruction, i);
571 }
572 // Environment should be created later.
573 DCHECK(!instruction->HasEnvironment());
574}
575
Roland Levillainccc07a92014-09-16 14:48:16 +0100576void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
577 HInstruction* replacement) {
578 DCHECK(initial->GetBlock() == this);
579 InsertInstructionBefore(replacement, initial);
580 initial->ReplaceWith(replacement);
581 RemoveInstruction(initial);
582}
583
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100584static void Add(HInstructionList* instruction_list,
585 HBasicBlock* block,
586 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000587 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000588 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100589 instruction->SetBlock(block);
590 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100591 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100592 instruction_list->AddInstruction(instruction);
593}
594
595void HBasicBlock::AddInstruction(HInstruction* instruction) {
596 Add(&instructions_, this, instruction);
597}
598
599void HBasicBlock::AddPhi(HPhi* phi) {
600 Add(&phis_, this, phi);
601}
602
David Brazdilc3d743f2015-04-22 13:40:50 +0100603void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
604 DCHECK(!cursor->IsPhi());
605 DCHECK(!instruction->IsPhi());
606 DCHECK_EQ(instruction->GetId(), -1);
607 DCHECK_NE(cursor->GetId(), -1);
608 DCHECK_EQ(cursor->GetBlock(), this);
609 DCHECK(!instruction->IsControlFlow());
610 instruction->SetBlock(this);
611 instruction->SetId(GetGraph()->GetNextInstructionId());
612 UpdateInputsUsers(instruction);
613 instructions_.InsertInstructionBefore(instruction, cursor);
614}
615
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100616void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
617 DCHECK(!cursor->IsPhi());
618 DCHECK(!instruction->IsPhi());
619 DCHECK_EQ(instruction->GetId(), -1);
620 DCHECK_NE(cursor->GetId(), -1);
621 DCHECK_EQ(cursor->GetBlock(), this);
622 DCHECK(!instruction->IsControlFlow());
623 DCHECK(!cursor->IsControlFlow());
624 instruction->SetBlock(this);
625 instruction->SetId(GetGraph()->GetNextInstructionId());
626 UpdateInputsUsers(instruction);
627 instructions_.InsertInstructionAfter(instruction, cursor);
628}
629
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100630void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
631 DCHECK_EQ(phi->GetId(), -1);
632 DCHECK_NE(cursor->GetId(), -1);
633 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100634 phi->SetBlock(this);
635 phi->SetId(GetGraph()->GetNextInstructionId());
636 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100637 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100638}
639
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100640static void Remove(HInstructionList* instruction_list,
641 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000642 HInstruction* instruction,
643 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100644 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100645 instruction->SetBlock(nullptr);
646 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000647 if (ensure_safety) {
648 DCHECK(instruction->GetUses().IsEmpty());
649 DCHECK(instruction->GetEnvUses().IsEmpty());
650 RemoveAsUser(instruction);
651 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100652}
653
David Brazdil1abb4192015-02-17 18:33:36 +0000654void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100655 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000656 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657}
658
David Brazdil1abb4192015-02-17 18:33:36 +0000659void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
660 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100661}
662
David Brazdilc7508e92015-04-27 13:28:57 +0100663void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
664 if (instruction->IsPhi()) {
665 RemovePhi(instruction->AsPhi(), ensure_safety);
666 } else {
667 RemoveInstruction(instruction, ensure_safety);
668 }
669}
670
Vladimir Marko71bf8092015-09-15 15:33:14 +0100671void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
672 for (size_t i = 0; i < locals.size(); i++) {
673 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100674 SetRawEnvAt(i, instruction);
675 if (instruction != nullptr) {
676 instruction->AddEnvUseAt(this, i);
677 }
678 }
679}
680
David Brazdiled596192015-01-23 10:39:45 +0000681void HEnvironment::CopyFrom(HEnvironment* env) {
682 for (size_t i = 0; i < env->Size(); i++) {
683 HInstruction* instruction = env->GetInstructionAt(i);
684 SetRawEnvAt(i, instruction);
685 if (instruction != nullptr) {
686 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100687 }
David Brazdiled596192015-01-23 10:39:45 +0000688 }
689}
690
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700691void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
692 HBasicBlock* loop_header) {
693 DCHECK(loop_header->IsLoopHeader());
694 for (size_t i = 0; i < env->Size(); i++) {
695 HInstruction* instruction = env->GetInstructionAt(i);
696 SetRawEnvAt(i, instruction);
697 if (instruction == nullptr) {
698 continue;
699 }
700 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
701 // At the end of the loop pre-header, the corresponding value for instruction
702 // is the first input of the phi.
703 HInstruction* initial = instruction->AsPhi()->InputAt(0);
704 DCHECK(initial->GetBlock()->Dominates(loop_header));
705 SetRawEnvAt(i, initial);
706 initial->AddEnvUseAt(this, i);
707 } else {
708 instruction->AddEnvUseAt(this, i);
709 }
710 }
711}
712
David Brazdil1abb4192015-02-17 18:33:36 +0000713void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100714 DCHECK_LT(index, Size());
715 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000716 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100717}
718
Calin Juravle77520bc2015-01-12 18:45:46 +0000719HInstruction* HInstruction::GetNextDisregardingMoves() const {
720 HInstruction* next = GetNext();
721 while (next != nullptr && next->IsParallelMove()) {
722 next = next->GetNext();
723 }
724 return next;
725}
726
727HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
728 HInstruction* previous = GetPrevious();
729 while (previous != nullptr && previous->IsParallelMove()) {
730 previous = previous->GetPrevious();
731 }
732 return previous;
733}
734
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100735void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000736 if (first_instruction_ == nullptr) {
737 DCHECK(last_instruction_ == nullptr);
738 first_instruction_ = last_instruction_ = instruction;
739 } else {
740 last_instruction_->next_ = instruction;
741 instruction->previous_ = last_instruction_;
742 last_instruction_ = instruction;
743 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000744}
745
David Brazdilc3d743f2015-04-22 13:40:50 +0100746void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
747 DCHECK(Contains(cursor));
748 if (cursor == first_instruction_) {
749 cursor->previous_ = instruction;
750 instruction->next_ = cursor;
751 first_instruction_ = instruction;
752 } else {
753 instruction->previous_ = cursor->previous_;
754 instruction->next_ = cursor;
755 cursor->previous_ = instruction;
756 instruction->previous_->next_ = instruction;
757 }
758}
759
760void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
761 DCHECK(Contains(cursor));
762 if (cursor == last_instruction_) {
763 cursor->next_ = instruction;
764 instruction->previous_ = cursor;
765 last_instruction_ = instruction;
766 } else {
767 instruction->next_ = cursor->next_;
768 instruction->previous_ = cursor;
769 cursor->next_ = instruction;
770 instruction->next_->previous_ = instruction;
771 }
772}
773
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100774void HInstructionList::RemoveInstruction(HInstruction* instruction) {
775 if (instruction->previous_ != nullptr) {
776 instruction->previous_->next_ = instruction->next_;
777 }
778 if (instruction->next_ != nullptr) {
779 instruction->next_->previous_ = instruction->previous_;
780 }
781 if (instruction == first_instruction_) {
782 first_instruction_ = instruction->next_;
783 }
784 if (instruction == last_instruction_) {
785 last_instruction_ = instruction->previous_;
786 }
787}
788
Roland Levillain6b469232014-09-25 10:10:38 +0100789bool HInstructionList::Contains(HInstruction* instruction) const {
790 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
791 if (it.Current() == instruction) {
792 return true;
793 }
794 }
795 return false;
796}
797
Roland Levillainccc07a92014-09-16 14:48:16 +0100798bool HInstructionList::FoundBefore(const HInstruction* instruction1,
799 const HInstruction* instruction2) const {
800 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
801 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
802 if (it.Current() == instruction1) {
803 return true;
804 }
805 if (it.Current() == instruction2) {
806 return false;
807 }
808 }
809 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
810 return true;
811}
812
Roland Levillain6c82d402014-10-13 16:10:27 +0100813bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
814 if (other_instruction == this) {
815 // An instruction does not strictly dominate itself.
816 return false;
817 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100818 HBasicBlock* block = GetBlock();
819 HBasicBlock* other_block = other_instruction->GetBlock();
820 if (block != other_block) {
821 return GetBlock()->Dominates(other_instruction->GetBlock());
822 } else {
823 // If both instructions are in the same block, ensure this
824 // instruction comes before `other_instruction`.
825 if (IsPhi()) {
826 if (!other_instruction->IsPhi()) {
827 // Phis appear before non phi-instructions so this instruction
828 // dominates `other_instruction`.
829 return true;
830 } else {
831 // There is no order among phis.
832 LOG(FATAL) << "There is no dominance between phis of a same block.";
833 return false;
834 }
835 } else {
836 // `this` is not a phi.
837 if (other_instruction->IsPhi()) {
838 // Phis appear before non phi-instructions so this instruction
839 // does not dominate `other_instruction`.
840 return false;
841 } else {
842 // Check whether this instruction comes before
843 // `other_instruction` in the instruction list.
844 return block->GetInstructions().FoundBefore(this, other_instruction);
845 }
846 }
847 }
848}
849
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100850void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100851 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000852 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
853 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100854 HInstruction* user = current->GetUser();
855 size_t input_index = current->GetIndex();
856 user->SetRawInputAt(input_index, other);
857 other->AddUseAt(user, input_index);
858 }
859
David Brazdiled596192015-01-23 10:39:45 +0000860 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
861 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100862 HEnvironment* user = current->GetUser();
863 size_t input_index = current->GetIndex();
864 user->SetRawEnvAt(input_index, other);
865 other->AddEnvUseAt(user, input_index);
866 }
867
David Brazdiled596192015-01-23 10:39:45 +0000868 uses_.Clear();
869 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870}
871
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100872void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000873 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100874 SetRawInputAt(index, replacement);
875 replacement->AddUseAt(this, index);
876}
877
Nicolas Geoffray39468442014-09-02 15:17:15 +0100878size_t HInstruction::EnvironmentSize() const {
879 return HasEnvironment() ? environment_->Size() : 0;
880}
881
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100882void HPhi::AddInput(HInstruction* input) {
883 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100884 inputs_.push_back(HUserRecord<HInstruction*>(input));
885 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100886}
887
David Brazdil2d7352b2015-04-20 14:52:42 +0100888void HPhi::RemoveInputAt(size_t index) {
889 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100890 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100891 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100892 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100893 InputRecordAt(i).GetUseNode()->SetIndex(i);
894 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100895}
896
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100897#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000898void H##name::Accept(HGraphVisitor* visitor) { \
899 visitor->Visit##name(this); \
900}
901
902FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
903
904#undef DEFINE_ACCEPT
905
906void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100907 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
908 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000909 if (block != nullptr) {
910 VisitBasicBlock(block);
911 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000912 }
913}
914
Roland Levillain633021e2014-10-01 14:12:25 +0100915void HGraphVisitor::VisitReversePostOrder() {
916 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
917 VisitBasicBlock(it.Current());
918 }
919}
920
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000921void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100922 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100923 it.Current()->Accept(this);
924 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100925 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000926 it.Current()->Accept(this);
927 }
928}
929
Mark Mendelle82549b2015-05-06 10:55:34 -0400930HConstant* HTypeConversion::TryStaticEvaluation() const {
931 HGraph* graph = GetBlock()->GetGraph();
932 if (GetInput()->IsIntConstant()) {
933 int32_t value = GetInput()->AsIntConstant()->GetValue();
934 switch (GetResultType()) {
935 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600936 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400937 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600938 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400939 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600940 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400941 default:
942 return nullptr;
943 }
944 } else if (GetInput()->IsLongConstant()) {
945 int64_t value = GetInput()->AsLongConstant()->GetValue();
946 switch (GetResultType()) {
947 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600948 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400949 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600950 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400951 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600952 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400953 default:
954 return nullptr;
955 }
956 } else if (GetInput()->IsFloatConstant()) {
957 float value = GetInput()->AsFloatConstant()->GetValue();
958 switch (GetResultType()) {
959 case Primitive::kPrimInt:
960 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600961 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400962 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600963 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400964 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600965 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
966 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400967 case Primitive::kPrimLong:
968 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600969 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400970 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600971 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400972 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600973 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
974 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400975 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600976 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400977 default:
978 return nullptr;
979 }
980 } else if (GetInput()->IsDoubleConstant()) {
981 double value = GetInput()->AsDoubleConstant()->GetValue();
982 switch (GetResultType()) {
983 case Primitive::kPrimInt:
984 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600985 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400986 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600987 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400988 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600989 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
990 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400991 case Primitive::kPrimLong:
992 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600993 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400994 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600995 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400996 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600997 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
998 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400999 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001000 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001001 default:
1002 return nullptr;
1003 }
1004 }
1005 return nullptr;
1006}
1007
Roland Levillain9240d6a2014-10-20 16:47:04 +01001008HConstant* HUnaryOperation::TryStaticEvaluation() const {
1009 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001010 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001011 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001012 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001013 }
1014 return nullptr;
1015}
1016
1017HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001018 if (GetLeft()->IsIntConstant()) {
1019 if (GetRight()->IsIntConstant()) {
1020 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1021 } else if (GetRight()->IsLongConstant()) {
1022 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1023 }
1024 } else if (GetLeft()->IsLongConstant()) {
1025 if (GetRight()->IsIntConstant()) {
1026 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1027 } else if (GetRight()->IsLongConstant()) {
1028 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001029 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001030 }
1031 return nullptr;
1032}
Dave Allison20dfc792014-06-16 20:44:29 -07001033
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001034HConstant* HBinaryOperation::GetConstantRight() const {
1035 if (GetRight()->IsConstant()) {
1036 return GetRight()->AsConstant();
1037 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1038 return GetLeft()->AsConstant();
1039 } else {
1040 return nullptr;
1041 }
1042}
1043
1044// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001045// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001046HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1047 HInstruction* most_constant_right = GetConstantRight();
1048 if (most_constant_right == nullptr) {
1049 return nullptr;
1050 } else if (most_constant_right == GetLeft()) {
1051 return GetRight();
1052 } else {
1053 return GetLeft();
1054 }
1055}
1056
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001057bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1058 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001059}
1060
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001061bool HInstruction::Equals(HInstruction* other) const {
1062 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001063 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001064 if (!InstructionDataEquals(other)) return false;
1065 if (GetType() != other->GetType()) return false;
1066 if (InputCount() != other->InputCount()) return false;
1067
1068 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1069 if (InputAt(i) != other->InputAt(i)) return false;
1070 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001071 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001072 return true;
1073}
1074
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001075std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1076#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1077 switch (rhs) {
1078 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1079 default:
1080 os << "Unknown instruction kind " << static_cast<int>(rhs);
1081 break;
1082 }
1083#undef DECLARE_CASE
1084 return os;
1085}
1086
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001087void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001088 next_->previous_ = previous_;
1089 if (previous_ != nullptr) {
1090 previous_->next_ = next_;
1091 }
1092 if (block_->instructions_.first_instruction_ == this) {
1093 block_->instructions_.first_instruction_ = next_;
1094 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001095 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001096
1097 previous_ = cursor->previous_;
1098 if (previous_ != nullptr) {
1099 previous_->next_ = this;
1100 }
1101 next_ = cursor;
1102 cursor->previous_ = this;
1103 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001104
1105 if (block_->instructions_.first_instruction_ == cursor) {
1106 block_->instructions_.first_instruction_ = this;
1107 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001108}
1109
David Brazdilfc6a86a2015-06-26 10:33:45 +00001110HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1111 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1112 DCHECK_EQ(cursor->GetBlock(), this);
1113
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001114 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1115 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001116 new_block->instructions_.first_instruction_ = cursor;
1117 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1118 instructions_.last_instruction_ = cursor->previous_;
1119 if (cursor->previous_ == nullptr) {
1120 instructions_.first_instruction_ = nullptr;
1121 } else {
1122 cursor->previous_->next_ = nullptr;
1123 cursor->previous_ = nullptr;
1124 }
1125
1126 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001127 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001128
Vladimir Marko60584552015-09-03 13:35:12 +00001129 for (HBasicBlock* successor : GetSuccessors()) {
1130 new_block->successors_.push_back(successor);
1131 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001132 }
Vladimir Marko60584552015-09-03 13:35:12 +00001133 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001134 AddSuccessor(new_block);
1135
David Brazdil56e1acc2015-06-30 15:41:36 +01001136 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001137 return new_block;
1138}
1139
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001140HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1141 DCHECK(!cursor->IsControlFlow());
1142 DCHECK_NE(instructions_.last_instruction_, cursor);
1143 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001144
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001145 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1146 new_block->instructions_.first_instruction_ = cursor->GetNext();
1147 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1148 cursor->next_->previous_ = nullptr;
1149 cursor->next_ = nullptr;
1150 instructions_.last_instruction_ = cursor;
1151
1152 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001153 for (HBasicBlock* successor : GetSuccessors()) {
1154 new_block->successors_.push_back(successor);
1155 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001156 }
Vladimir Marko60584552015-09-03 13:35:12 +00001157 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001158
Vladimir Marko60584552015-09-03 13:35:12 +00001159 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001160 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001161 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001162 }
Vladimir Marko60584552015-09-03 13:35:12 +00001163 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001164 return new_block;
1165}
1166
David Brazdilec16f792015-08-19 15:04:01 +01001167const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001168 if (EndsWithTryBoundary()) {
1169 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1170 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001171 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001172 return try_boundary;
1173 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001174 DCHECK(IsTryBlock());
1175 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001176 return nullptr;
1177 }
David Brazdilec16f792015-08-19 15:04:01 +01001178 } else if (IsTryBlock()) {
1179 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001180 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001181 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001182 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001183}
1184
1185static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1186 return block.GetPhis().IsEmpty()
1187 && !block.GetInstructions().IsEmpty()
1188 && block.GetFirstInstruction() == block.GetLastInstruction();
1189}
1190
David Brazdil46e2a392015-03-16 17:31:52 +00001191bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001192 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1193}
1194
1195bool HBasicBlock::IsSingleTryBoundary() const {
1196 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001197}
1198
David Brazdil8d5b8b22015-03-24 10:51:52 +00001199bool HBasicBlock::EndsWithControlFlowInstruction() const {
1200 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1201}
1202
David Brazdilb2bd1c52015-03-25 11:17:37 +00001203bool HBasicBlock::EndsWithIf() const {
1204 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1205}
1206
David Brazdilffee3d32015-07-06 11:48:53 +01001207bool HBasicBlock::EndsWithTryBoundary() const {
1208 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1209}
1210
David Brazdilb2bd1c52015-03-25 11:17:37 +00001211bool HBasicBlock::HasSinglePhi() const {
1212 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1213}
1214
David Brazdilffee3d32015-07-06 11:48:53 +01001215bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001216 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001217 return false;
1218 }
1219
David Brazdilb618ade2015-07-29 10:31:29 +01001220 // Exception handlers need to be stored in the same order.
1221 for (HExceptionHandlerIterator it1(*this), it2(other);
1222 !it1.Done();
1223 it1.Advance(), it2.Advance()) {
1224 DCHECK(!it2.Done());
1225 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001226 return false;
1227 }
1228 }
1229 return true;
1230}
1231
David Brazdil2d7352b2015-04-20 14:52:42 +01001232size_t HInstructionList::CountSize() const {
1233 size_t size = 0;
1234 HInstruction* current = first_instruction_;
1235 for (; current != nullptr; current = current->GetNext()) {
1236 size++;
1237 }
1238 return size;
1239}
1240
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001241void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1242 for (HInstruction* current = first_instruction_;
1243 current != nullptr;
1244 current = current->GetNext()) {
1245 current->SetBlock(block);
1246 }
1247}
1248
1249void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1250 DCHECK(Contains(cursor));
1251 if (!instruction_list.IsEmpty()) {
1252 if (cursor == last_instruction_) {
1253 last_instruction_ = instruction_list.last_instruction_;
1254 } else {
1255 cursor->next_->previous_ = instruction_list.last_instruction_;
1256 }
1257 instruction_list.last_instruction_->next_ = cursor->next_;
1258 cursor->next_ = instruction_list.first_instruction_;
1259 instruction_list.first_instruction_->previous_ = cursor;
1260 }
1261}
1262
1263void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001264 if (IsEmpty()) {
1265 first_instruction_ = instruction_list.first_instruction_;
1266 last_instruction_ = instruction_list.last_instruction_;
1267 } else {
1268 AddAfter(last_instruction_, instruction_list);
1269 }
1270}
1271
David Brazdil2d7352b2015-04-20 14:52:42 +01001272void HBasicBlock::DisconnectAndDelete() {
1273 // Dominators must be removed after all the blocks they dominate. This way
1274 // a loop header is removed last, a requirement for correct loop information
1275 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001276 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001277
David Brazdil2d7352b2015-04-20 14:52:42 +01001278 // Remove the block from all loops it is included in.
1279 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1280 HLoopInformation* loop_info = it.Current();
1281 loop_info->Remove(this);
1282 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001283 // If this was the last back edge of the loop, we deliberately leave the
1284 // loop in an inconsistent state and will fail SSAChecker unless the
1285 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001286 loop_info->RemoveBackEdge(this);
1287 }
1288 }
1289
1290 // Disconnect the block from its predecessors and update their control-flow
1291 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001292 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001293 HInstruction* last_instruction = predecessor->GetLastInstruction();
1294 predecessor->RemoveInstruction(last_instruction);
1295 predecessor->RemoveSuccessor(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001296 if (predecessor->GetSuccessors().size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001297 DCHECK(last_instruction->IsIf());
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001298 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001299 } else {
1300 // The predecessor has no remaining successors and therefore must be dead.
1301 // We deliberately leave it without a control-flow instruction so that the
1302 // SSAChecker fails unless it is not removed during the pass too.
Vladimir Marko60584552015-09-03 13:35:12 +00001303 DCHECK_EQ(predecessor->GetSuccessors().size(), 0u);
David Brazdil2d7352b2015-04-20 14:52:42 +01001304 }
David Brazdil46e2a392015-03-16 17:31:52 +00001305 }
Vladimir Marko60584552015-09-03 13:35:12 +00001306 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001307
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001308 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001309 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001310 // Delete this block from the list of predecessors.
1311 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001312 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001313
1314 // Check that `successor` has other predecessors, otherwise `this` is the
1315 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001316 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001317
David Brazdil2d7352b2015-04-20 14:52:42 +01001318 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001319 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001320 // The successor has just one predecessor left. Replace phis with the only
1321 // remaining input.
1322 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1323 HPhi* phi = phi_it.Current()->AsPhi();
1324 phi->ReplaceWith(phi->InputAt(1 - this_index));
1325 successor->RemovePhi(phi);
1326 }
1327 } else {
1328 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1329 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1330 }
1331 }
1332 }
Vladimir Marko60584552015-09-03 13:35:12 +00001333 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001334
1335 // Disconnect from the dominator.
1336 dominator_->RemoveDominatedBlock(this);
1337 SetDominator(nullptr);
1338
1339 // Delete from the graph. The function safely deletes remaining instructions
1340 // and updates the reverse post order.
1341 graph_->DeleteDeadBlock(this);
1342 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001343}
1344
1345void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001346 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001347 DCHECK(ContainsElement(dominated_blocks_, other));
1348 DCHECK_EQ(GetSingleSuccessor(), other);
1349 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001350 DCHECK(other->GetPhis().IsEmpty());
1351
David Brazdil2d7352b2015-04-20 14:52:42 +01001352 // Move instructions from `other` to `this`.
1353 DCHECK(EndsWithControlFlowInstruction());
1354 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001355 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001356 other->instructions_.SetBlockOfInstructions(this);
1357 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001358
David Brazdil2d7352b2015-04-20 14:52:42 +01001359 // Remove `other` from the loops it is included in.
1360 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1361 HLoopInformation* loop_info = it.Current();
1362 loop_info->Remove(other);
1363 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001364 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001365 }
1366 }
1367
1368 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001369 successors_.clear();
1370 while (!other->successors_.empty()) {
1371 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001372 successor->ReplacePredecessor(other, this);
1373 }
1374
David Brazdil2d7352b2015-04-20 14:52:42 +01001375 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001376 RemoveDominatedBlock(other);
1377 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1378 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001379 dominated->SetDominator(this);
1380 }
Vladimir Marko60584552015-09-03 13:35:12 +00001381 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001382 other->dominator_ = nullptr;
1383
1384 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001385 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001386
1387 // Delete `other` from the graph. The function updates reverse post order.
1388 graph_->DeleteDeadBlock(other);
1389 other->SetGraph(nullptr);
1390}
1391
1392void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1393 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001394 DCHECK(GetDominatedBlocks().empty());
1395 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001396 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001397 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001398 DCHECK(other->GetPhis().IsEmpty());
1399 DCHECK(!other->IsInLoop());
1400
1401 // Move instructions from `other` to `this`.
1402 instructions_.Add(other->GetInstructions());
1403 other->instructions_.SetBlockOfInstructions(this);
1404
1405 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001406 successors_.clear();
1407 while (!other->successors_.empty()) {
1408 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001409 successor->ReplacePredecessor(other, this);
1410 }
1411
1412 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001413 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1414 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001415 dominated->SetDominator(this);
1416 }
Vladimir Marko60584552015-09-03 13:35:12 +00001417 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001418 other->dominator_ = nullptr;
1419 other->graph_ = nullptr;
1420}
1421
1422void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001423 while (!GetPredecessors().empty()) {
1424 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001425 predecessor->ReplaceSuccessor(this, other);
1426 }
Vladimir Marko60584552015-09-03 13:35:12 +00001427 while (!GetSuccessors().empty()) {
1428 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001429 successor->ReplacePredecessor(this, other);
1430 }
Vladimir Marko60584552015-09-03 13:35:12 +00001431 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1432 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001433 }
1434 GetDominator()->ReplaceDominatedBlock(this, other);
1435 other->SetDominator(GetDominator());
1436 dominator_ = nullptr;
1437 graph_ = nullptr;
1438}
1439
1440// Create space in `blocks` for adding `number_of_new_blocks` entries
1441// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001442static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001443 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001444 size_t after) {
1445 DCHECK_LT(after, blocks->size());
1446 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001447 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001448 blocks->resize(new_size);
1449 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001450}
1451
David Brazdil2d7352b2015-04-20 14:52:42 +01001452void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1453 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001454 DCHECK(block->GetSuccessors().empty());
1455 DCHECK(block->GetPredecessors().empty());
1456 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001457 DCHECK(block->GetDominator() == nullptr);
1458
1459 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1460 block->RemoveInstruction(it.Current());
1461 }
1462 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1463 block->RemovePhi(it.Current()->AsPhi());
1464 }
1465
David Brazdilc7af85d2015-05-26 12:05:55 +01001466 if (block->IsExitBlock()) {
1467 exit_block_ = nullptr;
1468 }
1469
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001470 RemoveElement(reverse_post_order_, block);
1471 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001472}
1473
Calin Juravle2e768302015-07-28 14:41:11 +00001474HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001475 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001476 // Update the environments in this graph to have the invoke's environment
1477 // as parent.
1478 {
1479 HReversePostOrderIterator it(*this);
1480 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1481 for (; !it.Done(); it.Advance()) {
1482 HBasicBlock* block = it.Current();
1483 for (HInstructionIterator instr_it(block->GetInstructions());
1484 !instr_it.Done();
1485 instr_it.Advance()) {
1486 HInstruction* current = instr_it.Current();
1487 if (current->NeedsEnvironment()) {
1488 current->GetEnvironment()->SetAndCopyParentChain(
1489 outer_graph->GetArena(), invoke->GetEnvironment());
1490 }
1491 }
1492 }
1493 }
1494 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1495 if (HasBoundsChecks()) {
1496 outer_graph->SetHasBoundsChecks(true);
1497 }
1498
Calin Juravle2e768302015-07-28 14:41:11 +00001499 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001500 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001501 // Simple case of an entry block, a body block, and an exit block.
1502 // Put the body block's instruction into `invoke`'s block.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001503 HBasicBlock* body = GetBlock(1);
1504 DCHECK(GetBlock(0)->IsEntryBlock());
1505 DCHECK(GetBlock(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001506 DCHECK(!body->IsExitBlock());
1507 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001508
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001509 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1510 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001511
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001512 // Replace the invoke with the return value of the inlined graph.
1513 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001514 return_value = last->InputAt(0);
1515 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001516 } else {
1517 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001519
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001520 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001521 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001522 // Need to inline multiple blocks. We split `invoke`'s block
1523 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001524 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001525 // with the second half.
1526 ArenaAllocator* allocator = outer_graph->GetArena();
1527 HBasicBlock* at = invoke->GetBlock();
1528 HBasicBlock* to = at->SplitAfter(invoke);
1529
Vladimir Marko60584552015-09-03 13:35:12 +00001530 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001531 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001532 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001533 exit_block_->ReplaceWith(to);
1534
1535 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001536 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001537 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1538 if (to->GetPredecessors().size() == 1) {
1539 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001540 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001541 if (!returns_void) {
1542 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001544 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001545 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001546 } else {
1547 if (!returns_void) {
1548 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001549 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001550 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001551 to->AddPhi(return_value->AsPhi());
1552 }
Vladimir Marko60584552015-09-03 13:35:12 +00001553 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001554 HInstruction* last = predecessor->GetLastInstruction();
1555 if (!returns_void) {
1556 return_value->AsPhi()->AddInput(last->InputAt(0));
1557 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001558 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001559 predecessor->RemoveInstruction(last);
1560 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001561 }
1562
1563 if (return_value != nullptr) {
1564 invoke->ReplaceWith(return_value);
1565 }
1566
1567 // Update the meta information surrounding blocks:
1568 // (1) the graph they are now in,
1569 // (2) the reverse post order of that graph,
1570 // (3) the potential loop information they are now in.
1571
1572 // We don't add the entry block, the exit block, and the first block, which
1573 // has been merged with `at`.
1574 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1575
1576 // We add the `to` block.
1577 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001578 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001579 + kNumberOfNewBlocksInCaller;
1580
1581 // Find the location of `at` in the outer graph's reverse post order. The new
1582 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001583 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001584 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1585
1586 // Do a reverse post order of the blocks in the callee and do (1), (2),
1587 // and (3) to the blocks that apply.
1588 HLoopInformation* info = at->GetLoopInformation();
1589 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1590 HBasicBlock* current = it.Current();
1591 if (current != exit_block_ && current != entry_block_ && current != first) {
1592 DCHECK(!current->IsInLoop());
1593 DCHECK(current->GetGraph() == this);
1594 current->SetGraph(outer_graph);
1595 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001596 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001597 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001598 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001599 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1600 loop_it.Current()->Add(current);
1601 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001602 }
1603 }
1604 }
1605
1606 // Do (1), (2), and (3) to `to`.
1607 to->SetGraph(outer_graph);
1608 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001609 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001610 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001611 to->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(to);
1614 }
David Brazdil46e2a392015-03-16 17:31:52 +00001615 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001616 // Only `to` can become a back edge, as the inlined blocks
1617 // are predecessors of `to`.
1618 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001619 }
1620 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001621 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001622
David Brazdil05144f42015-04-16 15:18:00 +01001623 // Update the next instruction id of the outer graph, so that instructions
1624 // added later get bigger ids than those in the inner graph.
1625 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1626
1627 // Walk over the entry block and:
1628 // - Move constants from the entry block to the outer_graph's entry block,
1629 // - Replace HParameterValue instructions with their real value.
1630 // - Remove suspend checks, that hold an environment.
1631 // We must do this after the other blocks have been inlined, otherwise ids of
1632 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001633 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001634 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1635 HInstruction* current = it.Current();
1636 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001637 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001638 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001639 current->ReplaceWith(outer_graph->GetIntConstant(
1640 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001641 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001642 current->ReplaceWith(outer_graph->GetLongConstant(
1643 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001644 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001645 current->ReplaceWith(outer_graph->GetFloatConstant(
1646 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001647 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001648 current->ReplaceWith(outer_graph->GetDoubleConstant(
1649 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001650 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001651 if (kIsDebugBuild
1652 && invoke->IsInvokeStaticOrDirect()
1653 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1654 // Ensure we do not use the last input of `invoke`, as it
1655 // contains a clinit check which is not an actual argument.
1656 size_t last_input_index = invoke->InputCount() - 1;
1657 DCHECK(parameter_index != last_input_index);
1658 }
David Brazdil05144f42015-04-16 15:18:00 +01001659 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001660 } else if (current->IsCurrentMethod()) {
1661 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001662 } else {
1663 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1664 entry_block_->RemoveInstruction(current);
1665 }
1666 }
1667
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001668 // Finally remove the invoke from the caller.
1669 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001670
1671 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001672}
1673
Mingyao Yang3584bce2015-05-19 16:01:59 -07001674/*
1675 * Loop will be transformed to:
1676 * old_pre_header
1677 * |
1678 * if_block
1679 * / \
1680 * dummy_block deopt_block
1681 * \ /
1682 * new_pre_header
1683 * |
1684 * header
1685 */
1686void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1687 DCHECK(header->IsLoopHeader());
1688 HBasicBlock* pre_header = header->GetDominator();
1689
1690 // Need this to avoid critical edge.
1691 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1692 // Need this to avoid critical edge.
1693 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1694 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1695 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1696 AddBlock(if_block);
1697 AddBlock(dummy_block);
1698 AddBlock(deopt_block);
1699 AddBlock(new_pre_header);
1700
1701 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001702 pre_header->successors_.clear();
1703 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001704
1705 pre_header->AddSuccessor(if_block);
1706 if_block->AddSuccessor(dummy_block); // True successor
1707 if_block->AddSuccessor(deopt_block); // False successor
1708 dummy_block->AddSuccessor(new_pre_header);
1709 deopt_block->AddSuccessor(new_pre_header);
1710
Vladimir Marko60584552015-09-03 13:35:12 +00001711 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001712 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001713 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001714 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001715 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001716 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001717 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001718 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001719 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001720 header->SetDominator(new_pre_header);
1721
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001722 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001723 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001724 reverse_post_order_[index_of_header++] = if_block;
1725 reverse_post_order_[index_of_header++] = dummy_block;
1726 reverse_post_order_[index_of_header++] = deopt_block;
1727 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001728
1729 HLoopInformation* info = pre_header->GetLoopInformation();
1730 if (info != nullptr) {
1731 if_block->SetLoopInformation(info);
1732 dummy_block->SetLoopInformation(info);
1733 deopt_block->SetLoopInformation(info);
1734 new_pre_header->SetLoopInformation(info);
1735 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1736 !loop_it.Done();
1737 loop_it.Advance()) {
1738 loop_it.Current()->Add(if_block);
1739 loop_it.Current()->Add(dummy_block);
1740 loop_it.Current()->Add(deopt_block);
1741 loop_it.Current()->Add(new_pre_header);
1742 }
1743 }
1744}
1745
Calin Juravle2e768302015-07-28 14:41:11 +00001746void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1747 if (kIsDebugBuild) {
1748 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1749 ScopedObjectAccess soa(Thread::Current());
1750 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1751 if (IsBoundType()) {
1752 // Having the test here spares us from making the method virtual just for
1753 // the sake of a DCHECK.
1754 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1755 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1756 << " upper_bound_rti: " << upper_bound_rti
1757 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001758 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001759 }
1760 }
1761 reference_type_info_ = rti;
1762}
1763
1764ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1765
1766ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1767 : type_handle_(type_handle), is_exact_(is_exact) {
1768 if (kIsDebugBuild) {
1769 ScopedObjectAccess soa(Thread::Current());
1770 DCHECK(IsValidHandle(type_handle));
1771 }
1772}
1773
Calin Juravleacf735c2015-02-12 15:25:22 +00001774std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1775 ScopedObjectAccess soa(Thread::Current());
1776 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001777 << " is_valid=" << rhs.IsValid()
1778 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001779 << " is_exact=" << rhs.IsExact()
1780 << " ]";
1781 return os;
1782}
1783
Mark Mendellc4701932015-04-10 13:18:51 -04001784bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1785 // For now, assume that instructions in different blocks may use the
1786 // environment.
1787 // TODO: Use the control flow to decide if this is true.
1788 if (GetBlock() != other->GetBlock()) {
1789 return true;
1790 }
1791
1792 // We know that we are in the same block. Walk from 'this' to 'other',
1793 // checking to see if there is any instruction with an environment.
1794 HInstruction* current = this;
1795 for (; current != other && current != nullptr; current = current->GetNext()) {
1796 // This is a conservative check, as the instruction result may not be in
1797 // the referenced environment.
1798 if (current->HasEnvironment()) {
1799 return true;
1800 }
1801 }
1802
1803 // We should have been called with 'this' before 'other' in the block.
1804 // Just confirm this.
1805 DCHECK(current != nullptr);
1806 return false;
1807}
1808
1809void HInstruction::RemoveEnvironmentUsers() {
1810 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1811 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1812 HEnvironment* user = user_node->GetUser();
1813 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1814 }
1815 env_uses_.Clear();
1816}
1817
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001818} // namespace art