blob: a37298c76e5ddb9933b951f4496da6e21725fe24 [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"
Vladimir Marko391d01f2015-11-06 11:02:08 +000020#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010021#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010022#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010023#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010024#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010026#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000028
29namespace art {
30
31void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010032 block->SetBlockId(blocks_.size());
33 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000034}
35
Nicolas Geoffray804d0932014-05-02 08:46:00 +010036void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010037 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
38 DCHECK_EQ(visited->GetHighestBitSet(), -1);
39
40 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010041 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010042 // Number of successors visited from a given node, indexed by block id.
43 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
44 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
45 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
46 constexpr size_t kDefaultWorklistSize = 8;
47 worklist.reserve(kDefaultWorklistSize);
48 visited->SetBit(entry_block_->GetBlockId());
49 visiting.SetBit(entry_block_->GetBlockId());
50 worklist.push_back(entry_block_);
51
52 while (!worklist.empty()) {
53 HBasicBlock* current = worklist.back();
54 uint32_t current_id = current->GetBlockId();
55 if (successors_visited[current_id] == current->GetSuccessors().size()) {
56 visiting.ClearBit(current_id);
57 worklist.pop_back();
58 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010059 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
60 uint32_t successor_id = successor->GetBlockId();
61 if (visiting.IsBitSet(successor_id)) {
62 DCHECK(ContainsElement(worklist, successor));
63 successor->AddBackEdge(current);
64 } else if (!visited->IsBitSet(successor_id)) {
65 visited->SetBit(successor_id);
66 visiting.SetBit(successor_id);
67 worklist.push_back(successor);
68 }
69 }
70 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000071}
72
Roland Levillainfc600dc2014-12-02 17:16:31 +000073static void RemoveAsUser(HInstruction* instruction) {
74 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000075 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000076 }
77
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010078 for (HEnvironment* environment = instruction->GetEnvironment();
79 environment != nullptr;
80 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000081 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000082 if (environment->GetInstructionAt(i) != nullptr) {
83 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000084 }
85 }
86 }
87}
88
89void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010090 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000091 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010092 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010093 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
95 RemoveAsUser(it.Current());
96 }
97 }
98 }
99}
100
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100101void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100102 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100104 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100105 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000106 for (HBasicBlock* successor : block->GetSuccessors()) {
107 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000108 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100109 // Remove the block from the list of blocks, so that further analyses
110 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000112 }
113 }
114}
115
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000116void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100117 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
118 // edges. This invariant simplifies building SSA form because Phis cannot
119 // collect both normal- and exceptional-flow values at the same time.
120 SimplifyCatchBlocks();
121
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100122 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000123
David Brazdilffee3d32015-07-06 11:48:53 +0100124 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000125 FindBackEdges(&visited);
126
David Brazdilffee3d32015-07-06 11:48:53 +0100127 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000128 // the initial DFS as users from other instructions, so that
129 // users can be safely removed before uses later.
130 RemoveInstructionsAsUsersFromDeadBlocks(visited);
131
David Brazdilffee3d32015-07-06 11:48:53 +0100132 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000133 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000134 // predecessors list of live blocks.
135 RemoveDeadBlocks(visited);
136
David Brazdilffee3d32015-07-06 11:48:53 +0100137 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100138 // dominators and the reverse post order.
139 SimplifyCFG();
140
David Brazdilffee3d32015-07-06 11:48:53 +0100141 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100142 ComputeDominanceInformation();
143}
144
145void HGraph::ClearDominanceInformation() {
146 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
147 it.Current()->ClearDominanceInformation();
148 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100149 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100150}
151
152void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000153 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100154 dominator_ = nullptr;
155}
156
157void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100158 DCHECK(reverse_post_order_.empty());
159 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100160 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100161
162 // Number of visits of a given node, indexed by block id.
163 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
164 // Number of successors visited from a given node, indexed by block id.
165 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
166 // Nodes for which we need to visit successors.
167 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
168 constexpr size_t kDefaultWorklistSize = 8;
169 worklist.reserve(kDefaultWorklistSize);
170 worklist.push_back(entry_block_);
171
172 while (!worklist.empty()) {
173 HBasicBlock* current = worklist.back();
174 uint32_t current_id = current->GetBlockId();
175 if (successors_visited[current_id] == current->GetSuccessors().size()) {
176 worklist.pop_back();
177 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100178 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
179
180 if (successor->GetDominator() == nullptr) {
181 successor->SetDominator(current);
182 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000183 // The CommonDominator can work for multiple blocks as long as the
184 // domination information doesn't change. However, since we're changing
185 // that information here, we can use the finder only for pairs of blocks.
186 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100187 }
188
189 // Once all the forward edges have been visited, we know the immediate
190 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100191 if (++visits[successor->GetBlockId()] ==
192 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
193 successor->GetDominator()->AddDominatedBlock(successor);
194 reverse_post_order_.push_back(successor);
195 worklist.push_back(successor);
196 }
197 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000198 }
199}
200
Alex Light68289a52015-12-15 17:30:30 -0800201void HGraph::TransformToSsa() {
202 DCHECK(!reverse_post_order_.empty());
203 SsaBuilder ssa_builder(this);
204 ssa_builder.BuildSsa();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100205}
206
David Brazdilfc6a86a2015-06-26 10:33:45 +0000207HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000208 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
209 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000210 // Use `InsertBetween` to ensure the predecessor index and successor index of
211 // `block` and `successor` are preserved.
212 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000213 return new_block;
214}
215
216void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
217 // Insert a new node between `block` and `successor` to split the
218 // critical edge.
219 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600220 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100221 if (successor->IsLoopHeader()) {
222 // If we split at a back edge boundary, make the new block the back edge.
223 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000224 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100225 info->RemoveBackEdge(block);
226 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100227 }
228 }
229}
230
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100231void HGraph::SimplifyLoop(HBasicBlock* header) {
232 HLoopInformation* info = header->GetLoopInformation();
233
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100234 // Make sure the loop has only one pre header. This simplifies SSA building by having
235 // to just look at the pre header to know which locals are initialized at entry of the
236 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000237 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100238 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100239 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100240 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600241 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100242
Vladimir Marko60584552015-09-03 13:35:12 +0000243 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100244 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100245 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100246 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100247 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100248 }
249 }
250 pre_header->AddSuccessor(header);
251 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100252
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100253 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100254 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
255 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000256 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100257 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100258 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000259 header->predecessors_[pred] = to_swap;
260 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100261 break;
262 }
263 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100264 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100265
266 // Place the suspend check at the beginning of the header, so that live registers
267 // will be known when allocating registers. Note that code generation can still
268 // generate the suspend check at the back edge, but needs to be careful with
269 // loop phi spill slots (which are not written to at back edge).
270 HInstruction* first_instruction = header->GetFirstInstruction();
271 if (!first_instruction->IsSuspendCheck()) {
272 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
273 header->InsertInstructionBefore(check, first_instruction);
274 first_instruction = check;
275 }
276 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277}
278
David Brazdilffee3d32015-07-06 11:48:53 +0100279static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100280 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100281 if (!predecessor->EndsWithTryBoundary()) {
282 // Only edges from HTryBoundary can be exceptional.
283 return false;
284 }
285 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
286 if (try_boundary->GetNormalFlowSuccessor() == &block) {
287 // This block is the normal-flow successor of `try_boundary`, but it could
288 // also be one of its exception handlers if catch blocks have not been
289 // simplified yet. Predecessors are unordered, so we will consider the first
290 // occurrence to be the normal edge and a possible second occurrence to be
291 // the exceptional edge.
292 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
293 } else {
294 // This is not the normal-flow successor of `try_boundary`, hence it must be
295 // one of its exception handlers.
296 DCHECK(try_boundary->HasExceptionHandler(block));
297 return true;
298 }
299}
300
301void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100302 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
303 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
304 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
305 HBasicBlock* catch_block = blocks_[block_id];
David Brazdilffee3d32015-07-06 11:48:53 +0100306 if (!catch_block->IsCatchBlock()) {
307 continue;
308 }
309
310 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000311 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100312 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
313 exceptional_predecessors_only = false;
314 break;
315 }
316 }
317
318 if (!exceptional_predecessors_only) {
319 // Catch block has normal-flow predecessors and needs to be simplified.
320 // Splitting the block before its first instruction moves all its
321 // instructions into `normal_block` and links the two blocks with a Goto.
322 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
323 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000324 //
David Brazdilffee3d32015-07-06 11:48:53 +0100325 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000326 // a move-exception instruction, as guaranteed by the verifier. However,
327 // trivially dead predecessors are ignored by the verifier and such code
328 // has not been removed at this stage. We therefore ignore the assumption
329 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
330 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
331 if (normal_block == nullptr) {
332 // Catch block is either empty or only contains a move-exception. It must
333 // therefore be dead and will be removed during initial DCE. Do nothing.
334 DCHECK(!catch_block->EndsWithControlFlowInstruction());
335 } else {
336 // Catch block was split. Re-link normal-flow edges to the new block.
337 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
338 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
339 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
340 --j;
341 }
David Brazdilffee3d32015-07-06 11:48:53 +0100342 }
343 }
344 }
345 }
346}
347
348void HGraph::ComputeTryBlockInformation() {
349 // Iterate in reverse post order to propagate try membership information from
350 // predecessors to their successors.
351 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
352 HBasicBlock* block = it.Current();
353 if (block->IsEntryBlock() || block->IsCatchBlock()) {
354 // Catch blocks after simplification have only exceptional predecessors
355 // and hence are never in tries.
356 continue;
357 }
358
359 // Infer try membership from the first predecessor. Having simplified loops,
360 // the first predecessor can never be a back edge and therefore it must have
361 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100362 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100363 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100364 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000365 if (try_entry != nullptr &&
366 (block->GetTryCatchInformation() == nullptr ||
367 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
368 // We are either setting try block membership for the first time or it
369 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100370 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
371 }
David Brazdilffee3d32015-07-06 11:48:53 +0100372 }
373}
374
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100375void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000376// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100377 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000378 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100379 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
380 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
381 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
382 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100383 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000384 if (block->GetSuccessors().size() > 1) {
385 // Only split normal-flow edges. We cannot split exceptional edges as they
386 // are synthesized (approximate real control flow), and we do not need to
387 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000388 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
389 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
390 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100391 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000392 if (successor == exit_block_) {
393 // Throw->TryBoundary->Exit. Special case which we do not want to split
394 // because Goto->Exit is not allowed.
395 DCHECK(block->IsSingleTryBoundary());
396 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
397 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100398 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000399 // SplitCriticalEdge could have invalidated the `normal_successors`
400 // ArrayRef. We must re-acquire it.
401 normal_successors = block->GetNormalSuccessors();
402 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
403 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 }
405 }
406 }
407 if (block->IsLoopHeader()) {
408 SimplifyLoop(block);
409 }
410 }
411}
412
Alex Light68289a52015-12-15 17:30:30 -0800413bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100414 // Order does not matter.
415 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
416 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100417 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100418 if (block->IsCatchBlock()) {
419 // TODO: Dealing with exceptional back edges could be tricky because
420 // they only approximate the real control flow. Bail out for now.
Alex Light68289a52015-12-15 17:30:30 -0800421 return false;
David Brazdilffee3d32015-07-06 11:48:53 +0100422 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100423 HLoopInformation* info = block->GetLoopInformation();
424 if (!info->Populate()) {
425 // Abort if the loop is non natural. We currently bailout in such cases.
Alex Light68289a52015-12-15 17:30:30 -0800426 return false;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 }
428 }
429 }
Alex Light68289a52015-12-15 17:30:30 -0800430 return true;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100431}
432
David Brazdil8d5b8b22015-03-24 10:51:52 +0000433void HGraph::InsertConstant(HConstant* constant) {
434 // New constants are inserted before the final control-flow instruction
435 // of the graph, or at its end if called from the graph builder.
436 if (entry_block_->EndsWithControlFlowInstruction()) {
437 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000438 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000439 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000440 }
441}
442
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600443HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100444 // For simplicity, don't bother reviving the cached null constant if it is
445 // not null and not in a block. Otherwise, we need to clear the instruction
446 // id and/or any invariants the graph is assuming when adding new instructions.
447 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600448 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000449 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000450 }
451 return cached_null_constant_;
452}
453
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100454HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100455 // For simplicity, don't bother reviving the cached current method if it is
456 // not null and not in a block. Otherwise, we need to clear the instruction
457 // id and/or any invariants the graph is assuming when adding new instructions.
458 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700459 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600460 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
461 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100462 if (entry_block_->GetFirstInstruction() == nullptr) {
463 entry_block_->AddInstruction(cached_current_method_);
464 } else {
465 entry_block_->InsertInstructionBefore(
466 cached_current_method_, entry_block_->GetFirstInstruction());
467 }
468 }
469 return cached_current_method_;
470}
471
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600472HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000473 switch (type) {
474 case Primitive::Type::kPrimBoolean:
475 DCHECK(IsUint<1>(value));
476 FALLTHROUGH_INTENDED;
477 case Primitive::Type::kPrimByte:
478 case Primitive::Type::kPrimChar:
479 case Primitive::Type::kPrimShort:
480 case Primitive::Type::kPrimInt:
481 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600482 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000483
484 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600485 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000486
487 default:
488 LOG(FATAL) << "Unsupported constant type";
489 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000490 }
David Brazdil46e2a392015-03-16 17:31:52 +0000491}
492
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000493void HGraph::CacheFloatConstant(HFloatConstant* constant) {
494 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
495 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
496 cached_float_constants_.Overwrite(value, constant);
497}
498
499void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
500 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
501 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
502 cached_double_constants_.Overwrite(value, constant);
503}
504
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000505void HLoopInformation::Add(HBasicBlock* block) {
506 blocks_.SetBit(block->GetBlockId());
507}
508
David Brazdil46e2a392015-03-16 17:31:52 +0000509void HLoopInformation::Remove(HBasicBlock* block) {
510 blocks_.ClearBit(block->GetBlockId());
511}
512
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100513void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
514 if (blocks_.IsBitSet(block->GetBlockId())) {
515 return;
516 }
517
518 blocks_.SetBit(block->GetBlockId());
519 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000520 for (HBasicBlock* predecessor : block->GetPredecessors()) {
521 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100522 }
523}
524
525bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100526 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100527 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100528 DCHECK(back_edge->GetDominator() != nullptr);
529 if (!header_->Dominates(back_edge)) {
530 // This loop is not natural. Do not bother going further.
531 return false;
532 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100533
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100534 // Populate this loop: starting with the back edge, recursively add predecessors
535 // that are not already part of that loop. Set the header as part of the loop
536 // to end the recursion.
537 // This is a recursive implementation of the algorithm described in
538 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
539 blocks_.SetBit(header_->GetBlockId());
540 PopulateRecursive(back_edge);
541 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100542 return true;
543}
544
David Brazdila4b8c212015-05-07 09:59:30 +0100545void HLoopInformation::Update() {
546 HGraph* graph = header_->GetGraph();
547 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100548 HBasicBlock* block = graph->GetBlocks()[id];
David Brazdila4b8c212015-05-07 09:59:30 +0100549 // Reset loop information of non-header blocks inside the loop, except
550 // members of inner nested loops because those should already have been
551 // updated by their own LoopInformation.
552 if (block->GetLoopInformation() == this && block != header_) {
553 block->SetLoopInformation(nullptr);
554 }
555 }
556 blocks_.ClearAllBits();
557
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100558 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100559 // The loop has been dismantled, delete its suspend check and remove info
560 // from the header.
561 DCHECK(HasSuspendCheck());
562 header_->RemoveInstruction(suspend_check_);
563 header_->SetLoopInformation(nullptr);
564 header_ = nullptr;
565 suspend_check_ = nullptr;
566 } else {
567 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100568 for (HBasicBlock* back_edge : back_edges_) {
569 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100570 }
571 }
572 // This loop still has reachable back edges. Repopulate the list of blocks.
573 bool populate_successful = Populate();
574 DCHECK(populate_successful);
575 }
576}
577
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100578HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100579 return header_->GetDominator();
580}
581
582bool HLoopInformation::Contains(const HBasicBlock& block) const {
583 return blocks_.IsBitSet(block.GetBlockId());
584}
585
586bool HLoopInformation::IsIn(const HLoopInformation& other) const {
587 return other.blocks_.IsBitSet(header_->GetBlockId());
588}
589
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800590bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
591 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700592}
593
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100594size_t HLoopInformation::GetLifetimeEnd() const {
595 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100596 for (HBasicBlock* back_edge : GetBackEdges()) {
597 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100598 }
599 return last_position;
600}
601
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100602bool HBasicBlock::Dominates(HBasicBlock* other) const {
603 // Walk up the dominator tree from `other`, to find out if `this`
604 // is an ancestor.
605 HBasicBlock* current = other;
606 while (current != nullptr) {
607 if (current == this) {
608 return true;
609 }
610 current = current->GetDominator();
611 }
612 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100613}
614
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100615static void UpdateInputsUsers(HInstruction* instruction) {
616 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
617 instruction->InputAt(i)->AddUseAt(instruction, i);
618 }
619 // Environment should be created later.
620 DCHECK(!instruction->HasEnvironment());
621}
622
Roland Levillainccc07a92014-09-16 14:48:16 +0100623void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
624 HInstruction* replacement) {
625 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400626 if (initial->IsControlFlow()) {
627 // We can only replace a control flow instruction with another control flow instruction.
628 DCHECK(replacement->IsControlFlow());
629 DCHECK_EQ(replacement->GetId(), -1);
630 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
631 DCHECK_EQ(initial->GetBlock(), this);
632 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
633 DCHECK(initial->GetUses().IsEmpty());
634 DCHECK(initial->GetEnvUses().IsEmpty());
635 replacement->SetBlock(this);
636 replacement->SetId(GetGraph()->GetNextInstructionId());
637 instructions_.InsertInstructionBefore(replacement, initial);
638 UpdateInputsUsers(replacement);
639 } else {
640 InsertInstructionBefore(replacement, initial);
641 initial->ReplaceWith(replacement);
642 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100643 RemoveInstruction(initial);
644}
645
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100646static void Add(HInstructionList* instruction_list,
647 HBasicBlock* block,
648 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000649 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000650 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100651 instruction->SetBlock(block);
652 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100653 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100654 instruction_list->AddInstruction(instruction);
655}
656
657void HBasicBlock::AddInstruction(HInstruction* instruction) {
658 Add(&instructions_, this, instruction);
659}
660
661void HBasicBlock::AddPhi(HPhi* phi) {
662 Add(&phis_, this, phi);
663}
664
David Brazdilc3d743f2015-04-22 13:40:50 +0100665void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
666 DCHECK(!cursor->IsPhi());
667 DCHECK(!instruction->IsPhi());
668 DCHECK_EQ(instruction->GetId(), -1);
669 DCHECK_NE(cursor->GetId(), -1);
670 DCHECK_EQ(cursor->GetBlock(), this);
671 DCHECK(!instruction->IsControlFlow());
672 instruction->SetBlock(this);
673 instruction->SetId(GetGraph()->GetNextInstructionId());
674 UpdateInputsUsers(instruction);
675 instructions_.InsertInstructionBefore(instruction, cursor);
676}
677
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100678void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
679 DCHECK(!cursor->IsPhi());
680 DCHECK(!instruction->IsPhi());
681 DCHECK_EQ(instruction->GetId(), -1);
682 DCHECK_NE(cursor->GetId(), -1);
683 DCHECK_EQ(cursor->GetBlock(), this);
684 DCHECK(!instruction->IsControlFlow());
685 DCHECK(!cursor->IsControlFlow());
686 instruction->SetBlock(this);
687 instruction->SetId(GetGraph()->GetNextInstructionId());
688 UpdateInputsUsers(instruction);
689 instructions_.InsertInstructionAfter(instruction, cursor);
690}
691
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100692void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
693 DCHECK_EQ(phi->GetId(), -1);
694 DCHECK_NE(cursor->GetId(), -1);
695 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100696 phi->SetBlock(this);
697 phi->SetId(GetGraph()->GetNextInstructionId());
698 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100699 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100700}
701
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100702static void Remove(HInstructionList* instruction_list,
703 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000704 HInstruction* instruction,
705 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100706 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100707 instruction->SetBlock(nullptr);
708 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000709 if (ensure_safety) {
710 DCHECK(instruction->GetUses().IsEmpty());
711 DCHECK(instruction->GetEnvUses().IsEmpty());
712 RemoveAsUser(instruction);
713 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100714}
715
David Brazdil1abb4192015-02-17 18:33:36 +0000716void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100717 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000718 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100719}
720
David Brazdil1abb4192015-02-17 18:33:36 +0000721void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
722 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100723}
724
David Brazdilc7508e92015-04-27 13:28:57 +0100725void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
726 if (instruction->IsPhi()) {
727 RemovePhi(instruction->AsPhi(), ensure_safety);
728 } else {
729 RemoveInstruction(instruction, ensure_safety);
730 }
731}
732
Vladimir Marko71bf8092015-09-15 15:33:14 +0100733void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
734 for (size_t i = 0; i < locals.size(); i++) {
735 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100736 SetRawEnvAt(i, instruction);
737 if (instruction != nullptr) {
738 instruction->AddEnvUseAt(this, i);
739 }
740 }
741}
742
David Brazdiled596192015-01-23 10:39:45 +0000743void HEnvironment::CopyFrom(HEnvironment* env) {
744 for (size_t i = 0; i < env->Size(); i++) {
745 HInstruction* instruction = env->GetInstructionAt(i);
746 SetRawEnvAt(i, instruction);
747 if (instruction != nullptr) {
748 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100749 }
David Brazdiled596192015-01-23 10:39:45 +0000750 }
751}
752
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700753void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
754 HBasicBlock* loop_header) {
755 DCHECK(loop_header->IsLoopHeader());
756 for (size_t i = 0; i < env->Size(); i++) {
757 HInstruction* instruction = env->GetInstructionAt(i);
758 SetRawEnvAt(i, instruction);
759 if (instruction == nullptr) {
760 continue;
761 }
762 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
763 // At the end of the loop pre-header, the corresponding value for instruction
764 // is the first input of the phi.
765 HInstruction* initial = instruction->AsPhi()->InputAt(0);
766 DCHECK(initial->GetBlock()->Dominates(loop_header));
767 SetRawEnvAt(i, initial);
768 initial->AddEnvUseAt(this, i);
769 } else {
770 instruction->AddEnvUseAt(this, i);
771 }
772 }
773}
774
David Brazdil1abb4192015-02-17 18:33:36 +0000775void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100776 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000777 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100778}
779
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000780HInstruction::InstructionKind HInstruction::GetKind() const {
781 return GetKindInternal();
782}
783
Calin Juravle77520bc2015-01-12 18:45:46 +0000784HInstruction* HInstruction::GetNextDisregardingMoves() const {
785 HInstruction* next = GetNext();
786 while (next != nullptr && next->IsParallelMove()) {
787 next = next->GetNext();
788 }
789 return next;
790}
791
792HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
793 HInstruction* previous = GetPrevious();
794 while (previous != nullptr && previous->IsParallelMove()) {
795 previous = previous->GetPrevious();
796 }
797 return previous;
798}
799
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100800void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000801 if (first_instruction_ == nullptr) {
802 DCHECK(last_instruction_ == nullptr);
803 first_instruction_ = last_instruction_ = instruction;
804 } else {
805 last_instruction_->next_ = instruction;
806 instruction->previous_ = last_instruction_;
807 last_instruction_ = instruction;
808 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000809}
810
David Brazdilc3d743f2015-04-22 13:40:50 +0100811void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
812 DCHECK(Contains(cursor));
813 if (cursor == first_instruction_) {
814 cursor->previous_ = instruction;
815 instruction->next_ = cursor;
816 first_instruction_ = instruction;
817 } else {
818 instruction->previous_ = cursor->previous_;
819 instruction->next_ = cursor;
820 cursor->previous_ = instruction;
821 instruction->previous_->next_ = instruction;
822 }
823}
824
825void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
826 DCHECK(Contains(cursor));
827 if (cursor == last_instruction_) {
828 cursor->next_ = instruction;
829 instruction->previous_ = cursor;
830 last_instruction_ = instruction;
831 } else {
832 instruction->next_ = cursor->next_;
833 instruction->previous_ = cursor;
834 cursor->next_ = instruction;
835 instruction->next_->previous_ = instruction;
836 }
837}
838
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100839void HInstructionList::RemoveInstruction(HInstruction* instruction) {
840 if (instruction->previous_ != nullptr) {
841 instruction->previous_->next_ = instruction->next_;
842 }
843 if (instruction->next_ != nullptr) {
844 instruction->next_->previous_ = instruction->previous_;
845 }
846 if (instruction == first_instruction_) {
847 first_instruction_ = instruction->next_;
848 }
849 if (instruction == last_instruction_) {
850 last_instruction_ = instruction->previous_;
851 }
852}
853
Roland Levillain6b469232014-09-25 10:10:38 +0100854bool HInstructionList::Contains(HInstruction* instruction) const {
855 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
856 if (it.Current() == instruction) {
857 return true;
858 }
859 }
860 return false;
861}
862
Roland Levillainccc07a92014-09-16 14:48:16 +0100863bool HInstructionList::FoundBefore(const HInstruction* instruction1,
864 const HInstruction* instruction2) const {
865 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
866 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
867 if (it.Current() == instruction1) {
868 return true;
869 }
870 if (it.Current() == instruction2) {
871 return false;
872 }
873 }
874 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
875 return true;
876}
877
Roland Levillain6c82d402014-10-13 16:10:27 +0100878bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
879 if (other_instruction == this) {
880 // An instruction does not strictly dominate itself.
881 return false;
882 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100883 HBasicBlock* block = GetBlock();
884 HBasicBlock* other_block = other_instruction->GetBlock();
885 if (block != other_block) {
886 return GetBlock()->Dominates(other_instruction->GetBlock());
887 } else {
888 // If both instructions are in the same block, ensure this
889 // instruction comes before `other_instruction`.
890 if (IsPhi()) {
891 if (!other_instruction->IsPhi()) {
892 // Phis appear before non phi-instructions so this instruction
893 // dominates `other_instruction`.
894 return true;
895 } else {
896 // There is no order among phis.
897 LOG(FATAL) << "There is no dominance between phis of a same block.";
898 return false;
899 }
900 } else {
901 // `this` is not a phi.
902 if (other_instruction->IsPhi()) {
903 // Phis appear before non phi-instructions so this instruction
904 // does not dominate `other_instruction`.
905 return false;
906 } else {
907 // Check whether this instruction comes before
908 // `other_instruction` in the instruction list.
909 return block->GetInstructions().FoundBefore(this, other_instruction);
910 }
911 }
912 }
913}
914
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100915void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100916 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000917 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
918 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100919 HInstruction* user = current->GetUser();
920 size_t input_index = current->GetIndex();
921 user->SetRawInputAt(input_index, other);
922 other->AddUseAt(user, input_index);
923 }
924
David Brazdiled596192015-01-23 10:39:45 +0000925 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
926 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100927 HEnvironment* user = current->GetUser();
928 size_t input_index = current->GetIndex();
929 user->SetRawEnvAt(input_index, other);
930 other->AddEnvUseAt(user, input_index);
931 }
932
David Brazdiled596192015-01-23 10:39:45 +0000933 uses_.Clear();
934 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100935}
936
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100937void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000938 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100939 SetRawInputAt(index, replacement);
940 replacement->AddUseAt(this, index);
941}
942
Nicolas Geoffray39468442014-09-02 15:17:15 +0100943size_t HInstruction::EnvironmentSize() const {
944 return HasEnvironment() ? environment_->Size() : 0;
945}
946
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100947void HPhi::AddInput(HInstruction* input) {
948 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100949 inputs_.push_back(HUserRecord<HInstruction*>(input));
950 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100951}
952
David Brazdil2d7352b2015-04-20 14:52:42 +0100953void HPhi::RemoveInputAt(size_t index) {
954 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100955 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100956 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100957 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100958 InputRecordAt(i).GetUseNode()->SetIndex(i);
959 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100960}
961
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100962#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000963void H##name::Accept(HGraphVisitor* visitor) { \
964 visitor->Visit##name(this); \
965}
966
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000967FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000968
969#undef DEFINE_ACCEPT
970
971void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100972 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
973 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000974 if (block != nullptr) {
975 VisitBasicBlock(block);
976 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000977 }
978}
979
Roland Levillain633021e2014-10-01 14:12:25 +0100980void HGraphVisitor::VisitReversePostOrder() {
981 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
982 VisitBasicBlock(it.Current());
983 }
984}
985
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000986void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100987 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100988 it.Current()->Accept(this);
989 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100990 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000991 it.Current()->Accept(this);
992 }
993}
994
Mark Mendelle82549b2015-05-06 10:55:34 -0400995HConstant* HTypeConversion::TryStaticEvaluation() const {
996 HGraph* graph = GetBlock()->GetGraph();
997 if (GetInput()->IsIntConstant()) {
998 int32_t value = GetInput()->AsIntConstant()->GetValue();
999 switch (GetResultType()) {
1000 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001001 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001002 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001003 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001004 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001005 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001006 default:
1007 return nullptr;
1008 }
1009 } else if (GetInput()->IsLongConstant()) {
1010 int64_t value = GetInput()->AsLongConstant()->GetValue();
1011 switch (GetResultType()) {
1012 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001013 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001014 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001015 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001016 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001017 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001018 default:
1019 return nullptr;
1020 }
1021 } else if (GetInput()->IsFloatConstant()) {
1022 float value = GetInput()->AsFloatConstant()->GetValue();
1023 switch (GetResultType()) {
1024 case Primitive::kPrimInt:
1025 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001026 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001027 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001028 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001029 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001030 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1031 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001032 case Primitive::kPrimLong:
1033 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001034 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001035 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001036 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001037 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001038 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1039 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001040 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001041 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001042 default:
1043 return nullptr;
1044 }
1045 } else if (GetInput()->IsDoubleConstant()) {
1046 double value = GetInput()->AsDoubleConstant()->GetValue();
1047 switch (GetResultType()) {
1048 case Primitive::kPrimInt:
1049 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001050 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001051 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001052 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001053 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001054 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1055 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001056 case Primitive::kPrimLong:
1057 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001058 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001059 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001060 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001061 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001062 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1063 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001064 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001065 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001066 default:
1067 return nullptr;
1068 }
1069 }
1070 return nullptr;
1071}
1072
Roland Levillain9240d6a2014-10-20 16:47:04 +01001073HConstant* HUnaryOperation::TryStaticEvaluation() const {
1074 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001075 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001076 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001077 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001078 }
1079 return nullptr;
1080}
1081
1082HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001083 if (GetLeft()->IsIntConstant()) {
1084 if (GetRight()->IsIntConstant()) {
1085 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1086 } else if (GetRight()->IsLongConstant()) {
1087 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1088 }
1089 } else if (GetLeft()->IsLongConstant()) {
1090 if (GetRight()->IsIntConstant()) {
1091 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1092 } else if (GetRight()->IsLongConstant()) {
1093 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001094 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001095 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1096 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001097 }
1098 return nullptr;
1099}
Dave Allison20dfc792014-06-16 20:44:29 -07001100
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001101HConstant* HBinaryOperation::GetConstantRight() const {
1102 if (GetRight()->IsConstant()) {
1103 return GetRight()->AsConstant();
1104 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1105 return GetLeft()->AsConstant();
1106 } else {
1107 return nullptr;
1108 }
1109}
1110
1111// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001112// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001113HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1114 HInstruction* most_constant_right = GetConstantRight();
1115 if (most_constant_right == nullptr) {
1116 return nullptr;
1117 } else if (most_constant_right == GetLeft()) {
1118 return GetRight();
1119 } else {
1120 return GetLeft();
1121 }
1122}
1123
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001124bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1125 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001126}
1127
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001128bool HInstruction::Equals(HInstruction* other) const {
1129 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001130 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001131 if (!InstructionDataEquals(other)) return false;
1132 if (GetType() != other->GetType()) return false;
1133 if (InputCount() != other->InputCount()) return false;
1134
1135 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1136 if (InputAt(i) != other->InputAt(i)) return false;
1137 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001138 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001139 return true;
1140}
1141
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001142std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1143#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1144 switch (rhs) {
1145 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1146 default:
1147 os << "Unknown instruction kind " << static_cast<int>(rhs);
1148 break;
1149 }
1150#undef DECLARE_CASE
1151 return os;
1152}
1153
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001154void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001155 next_->previous_ = previous_;
1156 if (previous_ != nullptr) {
1157 previous_->next_ = next_;
1158 }
1159 if (block_->instructions_.first_instruction_ == this) {
1160 block_->instructions_.first_instruction_ = next_;
1161 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001162 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001163
1164 previous_ = cursor->previous_;
1165 if (previous_ != nullptr) {
1166 previous_->next_ = this;
1167 }
1168 next_ = cursor;
1169 cursor->previous_ = this;
1170 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001171
1172 if (block_->instructions_.first_instruction_ == cursor) {
1173 block_->instructions_.first_instruction_ = this;
1174 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001175}
1176
Vladimir Markofb337ea2015-11-25 15:25:10 +00001177void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1178 DCHECK(!CanThrow());
1179 DCHECK(!HasSideEffects());
1180 DCHECK(!HasEnvironmentUses());
1181 DCHECK(HasNonEnvironmentUses());
1182 DCHECK(!IsPhi()); // Makes no sense for Phi.
1183 DCHECK_EQ(InputCount(), 0u);
1184
1185 // Find the target block.
1186 HUseIterator<HInstruction*> uses_it(GetUses());
1187 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1188 uses_it.Advance();
1189 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1190 uses_it.Advance();
1191 }
1192 if (!uses_it.Done()) {
1193 // This instruction has uses in two or more blocks. Find the common dominator.
1194 CommonDominator finder(target_block);
1195 for (; !uses_it.Done(); uses_it.Advance()) {
1196 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1197 }
1198 target_block = finder.Get();
1199 DCHECK(target_block != nullptr);
1200 }
1201 // Move to the first dominator not in a loop.
1202 while (target_block->IsInLoop()) {
1203 target_block = target_block->GetDominator();
1204 DCHECK(target_block != nullptr);
1205 }
1206
1207 // Find insertion position.
1208 HInstruction* insert_pos = nullptr;
1209 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1210 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1211 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1212 insert_pos = uses_it2.Current()->GetUser();
1213 }
1214 }
1215 if (insert_pos == nullptr) {
1216 // No user in `target_block`, insert before the control flow instruction.
1217 insert_pos = target_block->GetLastInstruction();
1218 DCHECK(insert_pos->IsControlFlow());
1219 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1220 if (insert_pos->IsIf()) {
1221 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1222 if (if_input == insert_pos->GetPrevious()) {
1223 insert_pos = if_input;
1224 }
1225 }
1226 }
1227 MoveBefore(insert_pos);
1228}
1229
David Brazdilfc6a86a2015-06-26 10:33:45 +00001230HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001231 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001232 DCHECK_EQ(cursor->GetBlock(), this);
1233
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001234 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1235 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001236 new_block->instructions_.first_instruction_ = cursor;
1237 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1238 instructions_.last_instruction_ = cursor->previous_;
1239 if (cursor->previous_ == nullptr) {
1240 instructions_.first_instruction_ = nullptr;
1241 } else {
1242 cursor->previous_->next_ = nullptr;
1243 cursor->previous_ = nullptr;
1244 }
1245
1246 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001247 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001248
Vladimir Marko60584552015-09-03 13:35:12 +00001249 for (HBasicBlock* successor : GetSuccessors()) {
1250 new_block->successors_.push_back(successor);
1251 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001252 }
Vladimir Marko60584552015-09-03 13:35:12 +00001253 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001254 AddSuccessor(new_block);
1255
David Brazdil56e1acc2015-06-30 15:41:36 +01001256 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001257 return new_block;
1258}
1259
David Brazdild7558da2015-09-22 13:04:14 +01001260HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001261 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001262 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1263
1264 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1265
1266 for (HBasicBlock* predecessor : GetPredecessors()) {
1267 new_block->predecessors_.push_back(predecessor);
1268 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1269 }
1270 predecessors_.clear();
1271 AddPredecessor(new_block);
1272
1273 GetGraph()->AddBlock(new_block);
1274 return new_block;
1275}
1276
David Brazdil9bc43612015-11-05 21:25:24 +00001277HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1278 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1279 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1280
1281 HInstruction* first_insn = GetFirstInstruction();
1282 HInstruction* split_before = nullptr;
1283
1284 if (first_insn != nullptr && first_insn->IsLoadException()) {
1285 // Catch block starts with a LoadException. Split the block after
1286 // the StoreLocal and ClearException which must come after the load.
1287 DCHECK(first_insn->GetNext()->IsStoreLocal());
1288 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1289 split_before = first_insn->GetNext()->GetNext()->GetNext();
1290 } else {
1291 // Catch block does not load the exception. Split at the beginning
1292 // to create an empty catch block.
1293 split_before = first_insn;
1294 }
1295
1296 if (split_before == nullptr) {
1297 // Catch block has no instructions after the split point (must be dead).
1298 // Do not split it but rather signal error by returning nullptr.
1299 return nullptr;
1300 } else {
1301 return SplitBefore(split_before);
1302 }
1303}
1304
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001305HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1306 DCHECK(!cursor->IsControlFlow());
1307 DCHECK_NE(instructions_.last_instruction_, cursor);
1308 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001309
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001310 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1311 new_block->instructions_.first_instruction_ = cursor->GetNext();
1312 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1313 cursor->next_->previous_ = nullptr;
1314 cursor->next_ = nullptr;
1315 instructions_.last_instruction_ = cursor;
1316
1317 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001318 for (HBasicBlock* successor : GetSuccessors()) {
1319 new_block->successors_.push_back(successor);
1320 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001321 }
Vladimir Marko60584552015-09-03 13:35:12 +00001322 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001323
Vladimir Marko60584552015-09-03 13:35:12 +00001324 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001325 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001326 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001327 }
Vladimir Marko60584552015-09-03 13:35:12 +00001328 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001329 return new_block;
1330}
1331
David Brazdilec16f792015-08-19 15:04:01 +01001332const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001333 if (EndsWithTryBoundary()) {
1334 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1335 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001336 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001337 return try_boundary;
1338 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001339 DCHECK(IsTryBlock());
1340 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001341 return nullptr;
1342 }
David Brazdilec16f792015-08-19 15:04:01 +01001343 } else if (IsTryBlock()) {
1344 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001345 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001346 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001347 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001348}
1349
David Brazdild7558da2015-09-22 13:04:14 +01001350bool HBasicBlock::HasThrowingInstructions() const {
1351 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1352 if (it.Current()->CanThrow()) {
1353 return true;
1354 }
1355 }
1356 return false;
1357}
1358
David Brazdilfc6a86a2015-06-26 10:33:45 +00001359static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1360 return block.GetPhis().IsEmpty()
1361 && !block.GetInstructions().IsEmpty()
1362 && block.GetFirstInstruction() == block.GetLastInstruction();
1363}
1364
David Brazdil46e2a392015-03-16 17:31:52 +00001365bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001366 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1367}
1368
1369bool HBasicBlock::IsSingleTryBoundary() const {
1370 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001371}
1372
David Brazdil8d5b8b22015-03-24 10:51:52 +00001373bool HBasicBlock::EndsWithControlFlowInstruction() const {
1374 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1375}
1376
David Brazdilb2bd1c52015-03-25 11:17:37 +00001377bool HBasicBlock::EndsWithIf() const {
1378 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1379}
1380
David Brazdilffee3d32015-07-06 11:48:53 +01001381bool HBasicBlock::EndsWithTryBoundary() const {
1382 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1383}
1384
David Brazdilb2bd1c52015-03-25 11:17:37 +00001385bool HBasicBlock::HasSinglePhi() const {
1386 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1387}
1388
David Brazdild26a4112015-11-10 11:07:31 +00001389ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1390 if (EndsWithTryBoundary()) {
1391 // The normal-flow successor of HTryBoundary is always stored at index zero.
1392 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1393 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1394 } else {
1395 // All successors of blocks not ending with TryBoundary are normal.
1396 return ArrayRef<HBasicBlock* const>(successors_);
1397 }
1398}
1399
1400ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1401 if (EndsWithTryBoundary()) {
1402 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1403 } else {
1404 // Blocks not ending with TryBoundary do not have exceptional successors.
1405 return ArrayRef<HBasicBlock* const>();
1406 }
1407}
1408
David Brazdilffee3d32015-07-06 11:48:53 +01001409bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001410 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1411 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1412
1413 size_t length = handlers1.size();
1414 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001415 return false;
1416 }
1417
David Brazdilb618ade2015-07-29 10:31:29 +01001418 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001419 for (size_t i = 0; i < length; ++i) {
1420 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001421 return false;
1422 }
1423 }
1424 return true;
1425}
1426
David Brazdil2d7352b2015-04-20 14:52:42 +01001427size_t HInstructionList::CountSize() const {
1428 size_t size = 0;
1429 HInstruction* current = first_instruction_;
1430 for (; current != nullptr; current = current->GetNext()) {
1431 size++;
1432 }
1433 return size;
1434}
1435
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1437 for (HInstruction* current = first_instruction_;
1438 current != nullptr;
1439 current = current->GetNext()) {
1440 current->SetBlock(block);
1441 }
1442}
1443
1444void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1445 DCHECK(Contains(cursor));
1446 if (!instruction_list.IsEmpty()) {
1447 if (cursor == last_instruction_) {
1448 last_instruction_ = instruction_list.last_instruction_;
1449 } else {
1450 cursor->next_->previous_ = instruction_list.last_instruction_;
1451 }
1452 instruction_list.last_instruction_->next_ = cursor->next_;
1453 cursor->next_ = instruction_list.first_instruction_;
1454 instruction_list.first_instruction_->previous_ = cursor;
1455 }
1456}
1457
1458void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001459 if (IsEmpty()) {
1460 first_instruction_ = instruction_list.first_instruction_;
1461 last_instruction_ = instruction_list.last_instruction_;
1462 } else {
1463 AddAfter(last_instruction_, instruction_list);
1464 }
1465}
1466
David Brazdil04ff4e82015-12-10 13:54:52 +00001467// Should be called on instructions in a dead block in post order. This method
1468// assumes `insn` has been removed from all users with the exception of catch
1469// phis because of missing exceptional edges in the graph. It removes the
1470// instruction from catch phi uses, together with inputs of other catch phis in
1471// the catch block at the same index, as these must be dead too.
1472static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1473 DCHECK(!insn->HasEnvironmentUses());
1474 while (insn->HasNonEnvironmentUses()) {
1475 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1476 size_t use_index = use->GetIndex();
1477 HBasicBlock* user_block = use->GetUser()->GetBlock();
1478 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1479 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1480 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1481 }
1482 }
1483}
1484
David Brazdil2d7352b2015-04-20 14:52:42 +01001485void HBasicBlock::DisconnectAndDelete() {
1486 // Dominators must be removed after all the blocks they dominate. This way
1487 // a loop header is removed last, a requirement for correct loop information
1488 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001489 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001490
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001491 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001492 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1493 HLoopInformation* loop_info = it.Current();
1494 loop_info->Remove(this);
1495 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001496 // If this was the last back edge of the loop, we deliberately leave the
1497 // loop in an inconsistent state and will fail SSAChecker unless the
1498 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001499 loop_info->RemoveBackEdge(this);
1500 }
1501 }
1502
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001503 // (2) Disconnect the block from its predecessors and update their
1504 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001505 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001506 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001507 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1508 // This block is the only normal-flow successor of the TryBoundary which
1509 // makes `predecessor` dead. Since DCE removes blocks in post order,
1510 // exception handlers of this TryBoundary were already visited and any
1511 // remaining handlers therefore must be live. We remove `predecessor` from
1512 // their list of predecessors.
1513 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1514 while (predecessor->GetSuccessors().size() > 1) {
1515 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1516 DCHECK(handler->IsCatchBlock());
1517 predecessor->RemoveSuccessor(handler);
1518 handler->RemovePredecessor(predecessor);
1519 }
1520 }
1521
David Brazdil2d7352b2015-04-20 14:52:42 +01001522 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001523 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1524 if (num_pred_successors == 1u) {
1525 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001526 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1527 // successor. Replace those with a HGoto.
1528 DCHECK(last_instruction->IsIf() ||
1529 last_instruction->IsPackedSwitch() ||
1530 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001531 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001532 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001533 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001534 // The predecessor has no remaining successors and therefore must be dead.
1535 // We deliberately leave it without a control-flow instruction so that the
1536 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001537 predecessor->RemoveInstruction(last_instruction);
1538 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001539 // There are multiple successors left. The removed block might be a successor
1540 // of a PackedSwitch which will be completely removed (perhaps replaced with
1541 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1542 // case, leave `last_instruction` as is for now.
1543 DCHECK(last_instruction->IsPackedSwitch() ||
1544 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001545 }
David Brazdil46e2a392015-03-16 17:31:52 +00001546 }
Vladimir Marko60584552015-09-03 13:35:12 +00001547 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001548
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001549 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001550 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001551 // Delete this block from the list of predecessors.
1552 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001553 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001554
1555 // Check that `successor` has other predecessors, otherwise `this` is the
1556 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001557 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001558
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001559 // Remove this block's entries in the successor's phis. Skip exceptional
1560 // successors because catch phi inputs do not correspond to predecessor
1561 // blocks but throwing instructions. Their inputs will be updated in step (4).
1562 if (!successor->IsCatchBlock()) {
1563 if (successor->predecessors_.size() == 1u) {
1564 // The successor has just one predecessor left. Replace phis with the only
1565 // remaining input.
1566 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1567 HPhi* phi = phi_it.Current()->AsPhi();
1568 phi->ReplaceWith(phi->InputAt(1 - this_index));
1569 successor->RemovePhi(phi);
1570 }
1571 } else {
1572 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1573 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1574 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001575 }
1576 }
1577 }
Vladimir Marko60584552015-09-03 13:35:12 +00001578 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001579
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001580 // (4) Remove instructions and phis. Instructions should have no remaining uses
1581 // except in catch phis. If an instruction is used by a catch phi at `index`,
1582 // remove `index`-th input of all phis in the catch block since they are
1583 // guaranteed dead. Note that we may miss dead inputs this way but the
1584 // graph will always remain consistent.
1585 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1586 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001587 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001588 RemoveInstruction(insn);
1589 }
1590 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001591 HPhi* insn = it.Current()->AsPhi();
1592 RemoveUsesOfDeadInstruction(insn);
1593 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001594 }
1595
David Brazdil2d7352b2015-04-20 14:52:42 +01001596 // Disconnect from the dominator.
1597 dominator_->RemoveDominatedBlock(this);
1598 SetDominator(nullptr);
1599
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001600 // Delete from the graph, update reverse post order.
1601 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001602 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001603}
1604
1605void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001606 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001607 DCHECK(ContainsElement(dominated_blocks_, other));
1608 DCHECK_EQ(GetSingleSuccessor(), other);
1609 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001610 DCHECK(other->GetPhis().IsEmpty());
1611
David Brazdil2d7352b2015-04-20 14:52:42 +01001612 // Move instructions from `other` to `this`.
1613 DCHECK(EndsWithControlFlowInstruction());
1614 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001615 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001616 other->instructions_.SetBlockOfInstructions(this);
1617 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001618
David Brazdil2d7352b2015-04-20 14:52:42 +01001619 // Remove `other` from the loops it is included in.
1620 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1621 HLoopInformation* loop_info = it.Current();
1622 loop_info->Remove(other);
1623 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001624 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001625 }
1626 }
1627
1628 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001629 successors_.clear();
1630 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001631 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001632 successor->ReplacePredecessor(other, this);
1633 }
1634
David Brazdil2d7352b2015-04-20 14:52:42 +01001635 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001636 RemoveDominatedBlock(other);
1637 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1638 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001639 dominated->SetDominator(this);
1640 }
Vladimir Marko60584552015-09-03 13:35:12 +00001641 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001642 other->dominator_ = nullptr;
1643
1644 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001645 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001646
1647 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001648 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001649 other->SetGraph(nullptr);
1650}
1651
1652void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1653 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001654 DCHECK(GetDominatedBlocks().empty());
1655 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001656 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001657 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001658 DCHECK(other->GetPhis().IsEmpty());
1659 DCHECK(!other->IsInLoop());
1660
1661 // Move instructions from `other` to `this`.
1662 instructions_.Add(other->GetInstructions());
1663 other->instructions_.SetBlockOfInstructions(this);
1664
1665 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001666 successors_.clear();
1667 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001668 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001669 successor->ReplacePredecessor(other, this);
1670 }
1671
1672 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001673 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1674 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001675 dominated->SetDominator(this);
1676 }
Vladimir Marko60584552015-09-03 13:35:12 +00001677 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001678 other->dominator_ = nullptr;
1679 other->graph_ = nullptr;
1680}
1681
1682void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001683 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001684 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001685 predecessor->ReplaceSuccessor(this, other);
1686 }
Vladimir Marko60584552015-09-03 13:35:12 +00001687 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001688 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001689 successor->ReplacePredecessor(this, other);
1690 }
Vladimir Marko60584552015-09-03 13:35:12 +00001691 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1692 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001693 }
1694 GetDominator()->ReplaceDominatedBlock(this, other);
1695 other->SetDominator(GetDominator());
1696 dominator_ = nullptr;
1697 graph_ = nullptr;
1698}
1699
1700// Create space in `blocks` for adding `number_of_new_blocks` entries
1701// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001702static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001703 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001704 size_t after) {
1705 DCHECK_LT(after, blocks->size());
1706 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001707 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001708 blocks->resize(new_size);
1709 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001710}
1711
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001712void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001713 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001714 DCHECK(block->GetSuccessors().empty());
1715 DCHECK(block->GetPredecessors().empty());
1716 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001717 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001718 DCHECK(block->GetInstructions().IsEmpty());
1719 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001720
David Brazdilc7af85d2015-05-26 12:05:55 +01001721 if (block->IsExitBlock()) {
1722 exit_block_ = nullptr;
1723 }
1724
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001725 RemoveElement(reverse_post_order_, block);
1726 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001727}
1728
Calin Juravle2e768302015-07-28 14:41:11 +00001729HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001730 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001731 // Update the environments in this graph to have the invoke's environment
1732 // as parent.
1733 {
1734 HReversePostOrderIterator it(*this);
1735 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1736 for (; !it.Done(); it.Advance()) {
1737 HBasicBlock* block = it.Current();
1738 for (HInstructionIterator instr_it(block->GetInstructions());
1739 !instr_it.Done();
1740 instr_it.Advance()) {
1741 HInstruction* current = instr_it.Current();
1742 if (current->NeedsEnvironment()) {
1743 current->GetEnvironment()->SetAndCopyParentChain(
1744 outer_graph->GetArena(), invoke->GetEnvironment());
1745 }
1746 }
1747 }
1748 }
1749 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1750 if (HasBoundsChecks()) {
1751 outer_graph->SetHasBoundsChecks(true);
1752 }
1753
Calin Juravle2e768302015-07-28 14:41:11 +00001754 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001755 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001756 // Simple case of an entry block, a body block, and an exit block.
1757 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001758 HBasicBlock* body = GetBlocks()[1];
1759 DCHECK(GetBlocks()[0]->IsEntryBlock());
1760 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001761 DCHECK(!body->IsExitBlock());
1762 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001763
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001764 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1765 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001766
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001767 // Replace the invoke with the return value of the inlined graph.
1768 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001769 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001770 } else {
1771 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001772 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001773
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001774 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001775 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001776 // Need to inline multiple blocks. We split `invoke`'s block
1777 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001778 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001779 // with the second half.
1780 ArenaAllocator* allocator = outer_graph->GetArena();
1781 HBasicBlock* at = invoke->GetBlock();
1782 HBasicBlock* to = at->SplitAfter(invoke);
1783
Vladimir Markoec7802a2015-10-01 20:57:57 +01001784 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001785 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001787 exit_block_->ReplaceWith(to);
1788
1789 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001790 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001791 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001792 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001793 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001794 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001795 if (!returns_void) {
1796 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001797 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001798 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001799 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001800 } else {
1801 if (!returns_void) {
1802 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001803 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001804 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001805 to->AddPhi(return_value->AsPhi());
1806 }
Vladimir Marko60584552015-09-03 13:35:12 +00001807 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001808 HInstruction* last = predecessor->GetLastInstruction();
1809 if (!returns_void) {
1810 return_value->AsPhi()->AddInput(last->InputAt(0));
1811 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001812 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001813 predecessor->RemoveInstruction(last);
1814 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001815 }
1816
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001817 // Update the meta information surrounding blocks:
1818 // (1) the graph they are now in,
1819 // (2) the reverse post order of that graph,
David Brazdil95177982015-10-30 12:56:58 -05001820 // (3) the potential loop information they are now in,
1821 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001822 // Note that we do not need to update catch phi inputs because they
1823 // correspond to the register file of the outer method which the inlinee
1824 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001825
1826 // We don't add the entry block, the exit block, and the first block, which
1827 // has been merged with `at`.
1828 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1829
1830 // We add the `to` block.
1831 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001832 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001833 + kNumberOfNewBlocksInCaller;
1834
1835 // Find the location of `at` in the outer graph's reverse post order. The new
1836 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001837 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001838 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1839
David Brazdil95177982015-10-30 12:56:58 -05001840 HLoopInformation* loop_info = at->GetLoopInformation();
1841 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1842 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1843
1844 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1845 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001846 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1847 HBasicBlock* current = it.Current();
1848 if (current != exit_block_ && current != entry_block_ && current != first) {
1849 DCHECK(!current->IsInLoop());
David Brazdil95177982015-10-30 12:56:58 -05001850 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001851 DCHECK(current->GetGraph() == this);
1852 current->SetGraph(outer_graph);
1853 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001854 outer_graph->reverse_post_order_[++index_of_at] = current;
David Brazdil95177982015-10-30 12:56:58 -05001855 if (loop_info != nullptr) {
1856 current->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001857 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1858 loop_it.Current()->Add(current);
1859 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001860 }
David Brazdil95177982015-10-30 12:56:58 -05001861 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001862 }
1863 }
1864
David Brazdil95177982015-10-30 12:56:58 -05001865 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001866 to->SetGraph(outer_graph);
1867 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001868 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001869 if (loop_info != nullptr) {
1870 to->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001871 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1872 loop_it.Current()->Add(to);
1873 }
David Brazdil95177982015-10-30 12:56:58 -05001874 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001875 // Only `to` can become a back edge, as the inlined blocks
1876 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001877 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001878 }
1879 }
David Brazdil95177982015-10-30 12:56:58 -05001880 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001881 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001882
David Brazdil05144f42015-04-16 15:18:00 +01001883 // Update the next instruction id of the outer graph, so that instructions
1884 // added later get bigger ids than those in the inner graph.
1885 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1886
1887 // Walk over the entry block and:
1888 // - Move constants from the entry block to the outer_graph's entry block,
1889 // - Replace HParameterValue instructions with their real value.
1890 // - Remove suspend checks, that hold an environment.
1891 // We must do this after the other blocks have been inlined, otherwise ids of
1892 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001893 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001894 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1895 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001896 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001897 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001898 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001899 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001900 replacement = outer_graph->GetIntConstant(
1901 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001902 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001903 replacement = outer_graph->GetLongConstant(
1904 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001905 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001906 replacement = outer_graph->GetFloatConstant(
1907 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001908 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001909 replacement = outer_graph->GetDoubleConstant(
1910 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001911 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001912 if (kIsDebugBuild
1913 && invoke->IsInvokeStaticOrDirect()
1914 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1915 // Ensure we do not use the last input of `invoke`, as it
1916 // contains a clinit check which is not an actual argument.
1917 size_t last_input_index = invoke->InputCount() - 1;
1918 DCHECK(parameter_index != last_input_index);
1919 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001920 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001921 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001922 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01001923 } else {
1924 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1925 entry_block_->RemoveInstruction(current);
1926 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001927 if (replacement != nullptr) {
1928 current->ReplaceWith(replacement);
1929 // If the current is the return value then we need to update the latter.
1930 if (current == return_value) {
1931 DCHECK_EQ(entry_block_, return_value->GetBlock());
1932 return_value = replacement;
1933 }
1934 }
1935 }
1936
1937 if (return_value != nullptr) {
1938 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01001939 }
1940
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001941 // Finally remove the invoke from the caller.
1942 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001943
1944 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001945}
1946
Mingyao Yang3584bce2015-05-19 16:01:59 -07001947/*
1948 * Loop will be transformed to:
1949 * old_pre_header
1950 * |
1951 * if_block
1952 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08001953 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07001954 * \ /
1955 * new_pre_header
1956 * |
1957 * header
1958 */
1959void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1960 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08001961 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001962
Aart Bik3fc7f352015-11-20 22:03:03 -08001963 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07001964 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08001965 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1966 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07001967 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1968 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08001969 AddBlock(true_block);
1970 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001971 AddBlock(new_pre_header);
1972
Aart Bik3fc7f352015-11-20 22:03:03 -08001973 header->ReplacePredecessor(old_pre_header, new_pre_header);
1974 old_pre_header->successors_.clear();
1975 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001976
Aart Bik3fc7f352015-11-20 22:03:03 -08001977 old_pre_header->AddSuccessor(if_block);
1978 if_block->AddSuccessor(true_block); // True successor
1979 if_block->AddSuccessor(false_block); // False successor
1980 true_block->AddSuccessor(new_pre_header);
1981 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001982
Aart Bik3fc7f352015-11-20 22:03:03 -08001983 old_pre_header->dominated_blocks_.push_back(if_block);
1984 if_block->SetDominator(old_pre_header);
1985 if_block->dominated_blocks_.push_back(true_block);
1986 true_block->SetDominator(if_block);
1987 if_block->dominated_blocks_.push_back(false_block);
1988 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001989 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001990 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001991 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001992 header->SetDominator(new_pre_header);
1993
Aart Bik3fc7f352015-11-20 22:03:03 -08001994 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001995 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001996 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001997 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08001998 reverse_post_order_[index_of_header++] = true_block;
1999 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002000 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002001
Aart Bik3fc7f352015-11-20 22:03:03 -08002002 // Fix loop information.
2003 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2004 if (loop_info != nullptr) {
2005 if_block->SetLoopInformation(loop_info);
2006 true_block->SetLoopInformation(loop_info);
2007 false_block->SetLoopInformation(loop_info);
2008 new_pre_header->SetLoopInformation(loop_info);
2009 // Add blocks to all enveloping loops.
2010 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002011 !loop_it.Done();
2012 loop_it.Advance()) {
2013 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002014 loop_it.Current()->Add(true_block);
2015 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002016 loop_it.Current()->Add(new_pre_header);
2017 }
2018 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002019
2020 // Fix try/catch information.
2021 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2022 ? old_pre_header->GetTryCatchInformation()
2023 : nullptr;
2024 if_block->SetTryCatchInformation(try_catch_info);
2025 true_block->SetTryCatchInformation(try_catch_info);
2026 false_block->SetTryCatchInformation(try_catch_info);
2027 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002028}
2029
Calin Juravle2e768302015-07-28 14:41:11 +00002030void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2031 if (kIsDebugBuild) {
2032 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2033 ScopedObjectAccess soa(Thread::Current());
2034 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2035 if (IsBoundType()) {
2036 // Having the test here spares us from making the method virtual just for
2037 // the sake of a DCHECK.
2038 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
2039 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2040 << " upper_bound_rti: " << upper_bound_rti
2041 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01002042 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002043 }
2044 }
2045 reference_type_info_ = rti;
2046}
2047
2048ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2049
2050ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2051 : type_handle_(type_handle), is_exact_(is_exact) {
2052 if (kIsDebugBuild) {
2053 ScopedObjectAccess soa(Thread::Current());
2054 DCHECK(IsValidHandle(type_handle));
2055 }
2056}
2057
Calin Juravleacf735c2015-02-12 15:25:22 +00002058std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2059 ScopedObjectAccess soa(Thread::Current());
2060 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002061 << " is_valid=" << rhs.IsValid()
2062 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002063 << " is_exact=" << rhs.IsExact()
2064 << " ]";
2065 return os;
2066}
2067
Mark Mendellc4701932015-04-10 13:18:51 -04002068bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2069 // For now, assume that instructions in different blocks may use the
2070 // environment.
2071 // TODO: Use the control flow to decide if this is true.
2072 if (GetBlock() != other->GetBlock()) {
2073 return true;
2074 }
2075
2076 // We know that we are in the same block. Walk from 'this' to 'other',
2077 // checking to see if there is any instruction with an environment.
2078 HInstruction* current = this;
2079 for (; current != other && current != nullptr; current = current->GetNext()) {
2080 // This is a conservative check, as the instruction result may not be in
2081 // the referenced environment.
2082 if (current->HasEnvironment()) {
2083 return true;
2084 }
2085 }
2086
2087 // We should have been called with 'this' before 'other' in the block.
2088 // Just confirm this.
2089 DCHECK(current != nullptr);
2090 return false;
2091}
2092
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002093void HInvoke::SetIntrinsic(Intrinsics intrinsic,
2094 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache) {
2095 intrinsic_ = intrinsic;
2096 IntrinsicOptimizations opt(this);
2097 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2098 opt.SetDoesNotNeedDexCache();
2099 opt.SetDoesNotNeedEnvironment();
2100 }
2101}
2102
2103bool HInvoke::NeedsEnvironment() const {
2104 if (!IsIntrinsic()) {
2105 return true;
2106 }
2107 IntrinsicOptimizations opt(*this);
2108 return !opt.GetDoesNotNeedEnvironment();
2109}
2110
Vladimir Markodc151b22015-10-15 18:02:30 +01002111bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2112 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002113 return false;
2114 }
2115 if (!IsIntrinsic()) {
2116 return true;
2117 }
2118 IntrinsicOptimizations opt(*this);
2119 return !opt.GetDoesNotNeedDexCache();
2120}
2121
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002122void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2123 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2124 input->AddUseAt(this, index);
2125 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2126 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2127 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2128 InputRecordAt(i).GetUseNode()->SetIndex(i);
2129 }
2130}
2131
Vladimir Markob554b5a2015-11-06 12:57:55 +00002132void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2133 RemoveAsUserOfInput(index);
2134 inputs_.erase(inputs_.begin() + index);
2135 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2136 for (size_t i = index, e = InputCount(); i < e; ++i) {
2137 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2138 InputRecordAt(i).GetUseNode()->SetIndex(i);
2139 }
2140}
2141
Vladimir Markof64242a2015-12-01 14:58:23 +00002142std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2143 switch (rhs) {
2144 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2145 return os << "string_init";
2146 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2147 return os << "recursive";
2148 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2149 return os << "direct";
2150 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2151 return os << "direct_fixup";
2152 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2153 return os << "dex_cache_pc_relative";
2154 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2155 return os << "dex_cache_via_method";
2156 default:
2157 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2158 UNREACHABLE();
2159 }
2160}
2161
Vladimir Markofbb184a2015-11-13 14:47:00 +00002162std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2163 switch (rhs) {
2164 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2165 return os << "explicit";
2166 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2167 return os << "implicit";
2168 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2169 return os << "none";
2170 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002171 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2172 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002173 }
2174}
2175
Mark Mendellc4701932015-04-10 13:18:51 -04002176void HInstruction::RemoveEnvironmentUsers() {
2177 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2178 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2179 HEnvironment* user = user_node->GetUser();
2180 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2181 }
2182 env_uses_.Clear();
2183}
2184
Mark Mendellf6529172015-11-17 11:16:56 -05002185// Returns an instruction with the opposite boolean value from 'cond'.
2186HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2187 ArenaAllocator* allocator = GetArena();
2188
2189 if (cond->IsCondition() &&
2190 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2191 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2192 HInstruction* lhs = cond->InputAt(0);
2193 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002194 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002195 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2196 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2197 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2198 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2199 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2200 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2201 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2202 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2203 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2204 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2205 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002206 default:
2207 LOG(FATAL) << "Unexpected condition";
2208 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002209 }
2210 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2211 return replacement;
2212 } else if (cond->IsIntConstant()) {
2213 HIntConstant* int_const = cond->AsIntConstant();
2214 if (int_const->IsZero()) {
2215 return GetIntConstant(1);
2216 } else {
2217 DCHECK(int_const->IsOne());
2218 return GetIntConstant(0);
2219 }
2220 } else {
2221 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2222 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2223 return replacement;
2224 }
2225}
2226
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002227} // namespace art