blob: 24a89bca4ec19ab1cbbb7080af64716849c62c25 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010023#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010025#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000026#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027
28namespace art {
29
30void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010031 block->SetBlockId(blocks_.size());
32 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033}
34
Nicolas Geoffray804d0932014-05-02 08:46:00 +010035void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010036 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
37 DCHECK_EQ(visited->GetHighestBitSet(), -1);
38
39 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010040 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010041 // Number of successors visited from a given node, indexed by block id.
42 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
43 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
44 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
45 constexpr size_t kDefaultWorklistSize = 8;
46 worklist.reserve(kDefaultWorklistSize);
47 visited->SetBit(entry_block_->GetBlockId());
48 visiting.SetBit(entry_block_->GetBlockId());
49 worklist.push_back(entry_block_);
50
51 while (!worklist.empty()) {
52 HBasicBlock* current = worklist.back();
53 uint32_t current_id = current->GetBlockId();
54 if (successors_visited[current_id] == current->GetSuccessors().size()) {
55 visiting.ClearBit(current_id);
56 worklist.pop_back();
57 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
59 uint32_t successor_id = successor->GetBlockId();
60 if (visiting.IsBitSet(successor_id)) {
61 DCHECK(ContainsElement(worklist, successor));
62 successor->AddBackEdge(current);
63 } else if (!visited->IsBitSet(successor_id)) {
64 visited->SetBit(successor_id);
65 visiting.SetBit(successor_id);
66 worklist.push_back(successor);
67 }
68 }
69 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000070}
71
Roland Levillainfc600dc2014-12-02 17:16:31 +000072static void RemoveAsUser(HInstruction* instruction) {
73 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000074 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000075 }
76
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010077 for (HEnvironment* environment = instruction->GetEnvironment();
78 environment != nullptr;
79 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000080 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000081 if (environment->GetInstructionAt(i) != nullptr) {
82 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000083 }
84 }
85 }
86}
87
88void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010089 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000090 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010091 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010092 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
94 RemoveAsUser(it.Current());
95 }
96 }
97 }
98}
99
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100100void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100101 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000102 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100103 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100104 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000105 for (HBasicBlock* successor : block->GetSuccessors()) {
106 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000107 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100108 // Remove the block from the list of blocks, so that further analyses
109 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000111 }
112 }
113}
114
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000115void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
117 // edges. This invariant simplifies building SSA form because Phis cannot
118 // collect both normal- and exceptional-flow values at the same time.
119 SimplifyCatchBlocks();
120
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100121 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000122
David Brazdilffee3d32015-07-06 11:48:53 +0100123 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 FindBackEdges(&visited);
125
David Brazdilffee3d32015-07-06 11:48:53 +0100126 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000127 // the initial DFS as users from other instructions, so that
128 // users can be safely removed before uses later.
129 RemoveInstructionsAsUsersFromDeadBlocks(visited);
130
David Brazdilffee3d32015-07-06 11:48:53 +0100131 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000132 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 // predecessors list of live blocks.
134 RemoveDeadBlocks(visited);
135
David Brazdilffee3d32015-07-06 11:48:53 +0100136 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100137 // dominators and the reverse post order.
138 SimplifyCFG();
139
David Brazdilffee3d32015-07-06 11:48:53 +0100140 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100141 ComputeDominanceInformation();
142}
143
144void HGraph::ClearDominanceInformation() {
145 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
146 it.Current()->ClearDominanceInformation();
147 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100148 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100149}
150
151void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000152 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100153 dominator_ = nullptr;
154}
155
156void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100157 DCHECK(reverse_post_order_.empty());
158 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100159 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100160
161 // Number of visits of a given node, indexed by block id.
162 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
163 // Number of successors visited from a given node, indexed by block id.
164 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
165 // Nodes for which we need to visit successors.
166 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
167 constexpr size_t kDefaultWorklistSize = 8;
168 worklist.reserve(kDefaultWorklistSize);
169 worklist.push_back(entry_block_);
170
171 while (!worklist.empty()) {
172 HBasicBlock* current = worklist.back();
173 uint32_t current_id = current->GetBlockId();
174 if (successors_visited[current_id] == current->GetSuccessors().size()) {
175 worklist.pop_back();
176 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100177 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
178
179 if (successor->GetDominator() == nullptr) {
180 successor->SetDominator(current);
181 } else {
182 successor->SetDominator(FindCommonDominator(successor->GetDominator(), current));
183 }
184
185 // Once all the forward edges have been visited, we know the immediate
186 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100187 if (++visits[successor->GetBlockId()] ==
188 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
189 successor->GetDominator()->AddDominatedBlock(successor);
190 reverse_post_order_.push_back(successor);
191 worklist.push_back(successor);
192 }
193 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000194 }
195}
196
197HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100198 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000199 // Walk the dominator tree of the first block and mark the visited blocks.
200 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000201 visited.SetBit(first->GetBlockId());
202 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000203 }
204 // Walk the dominator tree of the second block until a marked block is found.
205 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000206 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000207 return second;
208 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000209 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000210 }
211 LOG(ERROR) << "Could not find common dominator";
212 return nullptr;
213}
214
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000215void HGraph::TransformToSsa() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100216 DCHECK(!reverse_post_order_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100217 SsaBuilder ssa_builder(this);
218 ssa_builder.BuildSsa();
219}
220
David Brazdilfc6a86a2015-06-26 10:33:45 +0000221HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000222 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
223 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000224 // Use `InsertBetween` to ensure the predecessor index and successor index of
225 // `block` and `successor` are preserved.
226 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000227 return new_block;
228}
229
230void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
231 // Insert a new node between `block` and `successor` to split the
232 // critical edge.
233 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600234 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100235 if (successor->IsLoopHeader()) {
236 // If we split at a back edge boundary, make the new block the back edge.
237 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000238 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100239 info->RemoveBackEdge(block);
240 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100241 }
242 }
243}
244
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100245void HGraph::SimplifyLoop(HBasicBlock* header) {
246 HLoopInformation* info = header->GetLoopInformation();
247
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100248 // Make sure the loop has only one pre header. This simplifies SSA building by having
249 // to just look at the pre header to know which locals are initialized at entry of the
250 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000251 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100252 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100253 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100254 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600255 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100256
Vladimir Marko60584552015-09-03 13:35:12 +0000257 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100258 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100259 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100260 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100261 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100262 }
263 }
264 pre_header->AddSuccessor(header);
265 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100266
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100267 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100268 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
269 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000270 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100271 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100272 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000273 header->predecessors_[pred] = to_swap;
274 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100275 break;
276 }
277 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100278 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100279
280 // Place the suspend check at the beginning of the header, so that live registers
281 // will be known when allocating registers. Note that code generation can still
282 // generate the suspend check at the back edge, but needs to be careful with
283 // loop phi spill slots (which are not written to at back edge).
284 HInstruction* first_instruction = header->GetFirstInstruction();
285 if (!first_instruction->IsSuspendCheck()) {
286 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
287 header->InsertInstructionBefore(check, first_instruction);
288 first_instruction = check;
289 }
290 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100291}
292
David Brazdilffee3d32015-07-06 11:48:53 +0100293static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100294 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100295 if (!predecessor->EndsWithTryBoundary()) {
296 // Only edges from HTryBoundary can be exceptional.
297 return false;
298 }
299 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
300 if (try_boundary->GetNormalFlowSuccessor() == &block) {
301 // This block is the normal-flow successor of `try_boundary`, but it could
302 // also be one of its exception handlers if catch blocks have not been
303 // simplified yet. Predecessors are unordered, so we will consider the first
304 // occurrence to be the normal edge and a possible second occurrence to be
305 // the exceptional edge.
306 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
307 } else {
308 // This is not the normal-flow successor of `try_boundary`, hence it must be
309 // one of its exception handlers.
310 DCHECK(try_boundary->HasExceptionHandler(block));
311 return true;
312 }
313}
314
315void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100316 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
317 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
318 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
319 HBasicBlock* catch_block = blocks_[block_id];
David Brazdilffee3d32015-07-06 11:48:53 +0100320 if (!catch_block->IsCatchBlock()) {
321 continue;
322 }
323
324 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000325 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100326 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
327 exceptional_predecessors_only = false;
328 break;
329 }
330 }
331
332 if (!exceptional_predecessors_only) {
333 // Catch block has normal-flow predecessors and needs to be simplified.
334 // Splitting the block before its first instruction moves all its
335 // instructions into `normal_block` and links the two blocks with a Goto.
336 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
337 // leaving `catch_block` with the exceptional edges only.
338 // Note that catch blocks with normal-flow predecessors cannot begin with
339 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
340 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
341 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000342 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100343 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100344 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100345 --j;
346 }
347 }
348 }
349 }
350}
351
352void HGraph::ComputeTryBlockInformation() {
353 // Iterate in reverse post order to propagate try membership information from
354 // predecessors to their successors.
355 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
356 HBasicBlock* block = it.Current();
357 if (block->IsEntryBlock() || block->IsCatchBlock()) {
358 // Catch blocks after simplification have only exceptional predecessors
359 // and hence are never in tries.
360 continue;
361 }
362
363 // Infer try membership from the first predecessor. Having simplified loops,
364 // the first predecessor can never be a back edge and therefore it must have
365 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100366 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100367 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100368 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
369 if (try_entry != nullptr) {
370 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() {
376 // Simplify the CFG for future analysis, and code generation:
377 // (1): Split critical edges.
378 // (2): Simplify loops by having only one back edge, and 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 Brazdilffee3d32015-07-06 11:48:53 +0100384 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000385 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100386 HBasicBlock* successor = block->GetSuccessors()[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100387 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000388 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100389 SplitCriticalEdge(block, successor);
390 --j;
391 }
392 }
393 }
394 if (block->IsLoopHeader()) {
395 SimplifyLoop(block);
396 }
397 }
398}
399
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000400bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100401 // Order does not matter.
402 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
403 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100405 if (block->IsCatchBlock()) {
406 // TODO: Dealing with exceptional back edges could be tricky because
407 // they only approximate the real control flow. Bail out for now.
408 return false;
409 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100410 HLoopInformation* info = block->GetLoopInformation();
411 if (!info->Populate()) {
412 // Abort if the loop is non natural. We currently bailout in such cases.
413 return false;
414 }
415 }
416 }
417 return true;
418}
419
David Brazdil8d5b8b22015-03-24 10:51:52 +0000420void HGraph::InsertConstant(HConstant* constant) {
421 // New constants are inserted before the final control-flow instruction
422 // of the graph, or at its end if called from the graph builder.
423 if (entry_block_->EndsWithControlFlowInstruction()) {
424 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000425 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000426 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000427 }
428}
429
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600430HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100431 // For simplicity, don't bother reviving the cached null constant if it is
432 // not null and not in a block. Otherwise, we need to clear the instruction
433 // id and/or any invariants the graph is assuming when adding new instructions.
434 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600435 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000436 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000437 }
438 return cached_null_constant_;
439}
440
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100441HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100442 // For simplicity, don't bother reviving the cached current method if it is
443 // not null and not in a block. Otherwise, we need to clear the instruction
444 // id and/or any invariants the graph is assuming when adding new instructions.
445 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600447 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
448 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100449 if (entry_block_->GetFirstInstruction() == nullptr) {
450 entry_block_->AddInstruction(cached_current_method_);
451 } else {
452 entry_block_->InsertInstructionBefore(
453 cached_current_method_, entry_block_->GetFirstInstruction());
454 }
455 }
456 return cached_current_method_;
457}
458
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600459HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000460 switch (type) {
461 case Primitive::Type::kPrimBoolean:
462 DCHECK(IsUint<1>(value));
463 FALLTHROUGH_INTENDED;
464 case Primitive::Type::kPrimByte:
465 case Primitive::Type::kPrimChar:
466 case Primitive::Type::kPrimShort:
467 case Primitive::Type::kPrimInt:
468 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600469 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000470
471 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600472 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000473
474 default:
475 LOG(FATAL) << "Unsupported constant type";
476 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000477 }
David Brazdil46e2a392015-03-16 17:31:52 +0000478}
479
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000480void HGraph::CacheFloatConstant(HFloatConstant* constant) {
481 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
482 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
483 cached_float_constants_.Overwrite(value, constant);
484}
485
486void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
487 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
488 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
489 cached_double_constants_.Overwrite(value, constant);
490}
491
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000492void HLoopInformation::Add(HBasicBlock* block) {
493 blocks_.SetBit(block->GetBlockId());
494}
495
David Brazdil46e2a392015-03-16 17:31:52 +0000496void HLoopInformation::Remove(HBasicBlock* block) {
497 blocks_.ClearBit(block->GetBlockId());
498}
499
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100500void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
501 if (blocks_.IsBitSet(block->GetBlockId())) {
502 return;
503 }
504
505 blocks_.SetBit(block->GetBlockId());
506 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000507 for (HBasicBlock* predecessor : block->GetPredecessors()) {
508 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100509 }
510}
511
512bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100513 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100514 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100515 DCHECK(back_edge->GetDominator() != nullptr);
516 if (!header_->Dominates(back_edge)) {
517 // This loop is not natural. Do not bother going further.
518 return false;
519 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100520
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100521 // Populate this loop: starting with the back edge, recursively add predecessors
522 // that are not already part of that loop. Set the header as part of the loop
523 // to end the recursion.
524 // This is a recursive implementation of the algorithm described in
525 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
526 blocks_.SetBit(header_->GetBlockId());
527 PopulateRecursive(back_edge);
528 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100529 return true;
530}
531
David Brazdila4b8c212015-05-07 09:59:30 +0100532void HLoopInformation::Update() {
533 HGraph* graph = header_->GetGraph();
534 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100535 HBasicBlock* block = graph->GetBlocks()[id];
David Brazdila4b8c212015-05-07 09:59:30 +0100536 // Reset loop information of non-header blocks inside the loop, except
537 // members of inner nested loops because those should already have been
538 // updated by their own LoopInformation.
539 if (block->GetLoopInformation() == this && block != header_) {
540 block->SetLoopInformation(nullptr);
541 }
542 }
543 blocks_.ClearAllBits();
544
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100545 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100546 // The loop has been dismantled, delete its suspend check and remove info
547 // from the header.
548 DCHECK(HasSuspendCheck());
549 header_->RemoveInstruction(suspend_check_);
550 header_->SetLoopInformation(nullptr);
551 header_ = nullptr;
552 suspend_check_ = nullptr;
553 } else {
554 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100555 for (HBasicBlock* back_edge : back_edges_) {
556 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100557 }
558 }
559 // This loop still has reachable back edges. Repopulate the list of blocks.
560 bool populate_successful = Populate();
561 DCHECK(populate_successful);
562 }
563}
564
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100565HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100566 return header_->GetDominator();
567}
568
569bool HLoopInformation::Contains(const HBasicBlock& block) const {
570 return blocks_.IsBitSet(block.GetBlockId());
571}
572
573bool HLoopInformation::IsIn(const HLoopInformation& other) const {
574 return other.blocks_.IsBitSet(header_->GetBlockId());
575}
576
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100577size_t HLoopInformation::GetLifetimeEnd() const {
578 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100579 for (HBasicBlock* back_edge : GetBackEdges()) {
580 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100581 }
582 return last_position;
583}
584
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100585bool HBasicBlock::Dominates(HBasicBlock* other) const {
586 // Walk up the dominator tree from `other`, to find out if `this`
587 // is an ancestor.
588 HBasicBlock* current = other;
589 while (current != nullptr) {
590 if (current == this) {
591 return true;
592 }
593 current = current->GetDominator();
594 }
595 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100596}
597
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100598static void UpdateInputsUsers(HInstruction* instruction) {
599 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
600 instruction->InputAt(i)->AddUseAt(instruction, i);
601 }
602 // Environment should be created later.
603 DCHECK(!instruction->HasEnvironment());
604}
605
Roland Levillainccc07a92014-09-16 14:48:16 +0100606void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
607 HInstruction* replacement) {
608 DCHECK(initial->GetBlock() == this);
609 InsertInstructionBefore(replacement, initial);
610 initial->ReplaceWith(replacement);
611 RemoveInstruction(initial);
612}
613
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100614static void Add(HInstructionList* instruction_list,
615 HBasicBlock* block,
616 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000617 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000618 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100619 instruction->SetBlock(block);
620 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100621 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100622 instruction_list->AddInstruction(instruction);
623}
624
625void HBasicBlock::AddInstruction(HInstruction* instruction) {
626 Add(&instructions_, this, instruction);
627}
628
629void HBasicBlock::AddPhi(HPhi* phi) {
630 Add(&phis_, this, phi);
631}
632
David Brazdilc3d743f2015-04-22 13:40:50 +0100633void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
634 DCHECK(!cursor->IsPhi());
635 DCHECK(!instruction->IsPhi());
636 DCHECK_EQ(instruction->GetId(), -1);
637 DCHECK_NE(cursor->GetId(), -1);
638 DCHECK_EQ(cursor->GetBlock(), this);
639 DCHECK(!instruction->IsControlFlow());
640 instruction->SetBlock(this);
641 instruction->SetId(GetGraph()->GetNextInstructionId());
642 UpdateInputsUsers(instruction);
643 instructions_.InsertInstructionBefore(instruction, cursor);
644}
645
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100646void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
647 DCHECK(!cursor->IsPhi());
648 DCHECK(!instruction->IsPhi());
649 DCHECK_EQ(instruction->GetId(), -1);
650 DCHECK_NE(cursor->GetId(), -1);
651 DCHECK_EQ(cursor->GetBlock(), this);
652 DCHECK(!instruction->IsControlFlow());
653 DCHECK(!cursor->IsControlFlow());
654 instruction->SetBlock(this);
655 instruction->SetId(GetGraph()->GetNextInstructionId());
656 UpdateInputsUsers(instruction);
657 instructions_.InsertInstructionAfter(instruction, cursor);
658}
659
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100660void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
661 DCHECK_EQ(phi->GetId(), -1);
662 DCHECK_NE(cursor->GetId(), -1);
663 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100664 phi->SetBlock(this);
665 phi->SetId(GetGraph()->GetNextInstructionId());
666 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100667 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100668}
669
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100670static void Remove(HInstructionList* instruction_list,
671 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000672 HInstruction* instruction,
673 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100674 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100675 instruction->SetBlock(nullptr);
676 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000677 if (ensure_safety) {
678 DCHECK(instruction->GetUses().IsEmpty());
679 DCHECK(instruction->GetEnvUses().IsEmpty());
680 RemoveAsUser(instruction);
681 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100682}
683
David Brazdil1abb4192015-02-17 18:33:36 +0000684void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100685 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000686 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100687}
688
David Brazdil1abb4192015-02-17 18:33:36 +0000689void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
690 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100691}
692
David Brazdilc7508e92015-04-27 13:28:57 +0100693void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
694 if (instruction->IsPhi()) {
695 RemovePhi(instruction->AsPhi(), ensure_safety);
696 } else {
697 RemoveInstruction(instruction, ensure_safety);
698 }
699}
700
Vladimir Marko71bf8092015-09-15 15:33:14 +0100701void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
702 for (size_t i = 0; i < locals.size(); i++) {
703 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100704 SetRawEnvAt(i, instruction);
705 if (instruction != nullptr) {
706 instruction->AddEnvUseAt(this, i);
707 }
708 }
709}
710
David Brazdiled596192015-01-23 10:39:45 +0000711void HEnvironment::CopyFrom(HEnvironment* env) {
712 for (size_t i = 0; i < env->Size(); i++) {
713 HInstruction* instruction = env->GetInstructionAt(i);
714 SetRawEnvAt(i, instruction);
715 if (instruction != nullptr) {
716 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100717 }
David Brazdiled596192015-01-23 10:39:45 +0000718 }
719}
720
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700721void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
722 HBasicBlock* loop_header) {
723 DCHECK(loop_header->IsLoopHeader());
724 for (size_t i = 0; i < env->Size(); i++) {
725 HInstruction* instruction = env->GetInstructionAt(i);
726 SetRawEnvAt(i, instruction);
727 if (instruction == nullptr) {
728 continue;
729 }
730 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
731 // At the end of the loop pre-header, the corresponding value for instruction
732 // is the first input of the phi.
733 HInstruction* initial = instruction->AsPhi()->InputAt(0);
734 DCHECK(initial->GetBlock()->Dominates(loop_header));
735 SetRawEnvAt(i, initial);
736 initial->AddEnvUseAt(this, i);
737 } else {
738 instruction->AddEnvUseAt(this, i);
739 }
740 }
741}
742
David Brazdil1abb4192015-02-17 18:33:36 +0000743void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100744 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000745 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746}
747
Calin Juravle77520bc2015-01-12 18:45:46 +0000748HInstruction* HInstruction::GetNextDisregardingMoves() const {
749 HInstruction* next = GetNext();
750 while (next != nullptr && next->IsParallelMove()) {
751 next = next->GetNext();
752 }
753 return next;
754}
755
756HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
757 HInstruction* previous = GetPrevious();
758 while (previous != nullptr && previous->IsParallelMove()) {
759 previous = previous->GetPrevious();
760 }
761 return previous;
762}
763
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100764void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000765 if (first_instruction_ == nullptr) {
766 DCHECK(last_instruction_ == nullptr);
767 first_instruction_ = last_instruction_ = instruction;
768 } else {
769 last_instruction_->next_ = instruction;
770 instruction->previous_ = last_instruction_;
771 last_instruction_ = instruction;
772 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000773}
774
David Brazdilc3d743f2015-04-22 13:40:50 +0100775void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
776 DCHECK(Contains(cursor));
777 if (cursor == first_instruction_) {
778 cursor->previous_ = instruction;
779 instruction->next_ = cursor;
780 first_instruction_ = instruction;
781 } else {
782 instruction->previous_ = cursor->previous_;
783 instruction->next_ = cursor;
784 cursor->previous_ = instruction;
785 instruction->previous_->next_ = instruction;
786 }
787}
788
789void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
790 DCHECK(Contains(cursor));
791 if (cursor == last_instruction_) {
792 cursor->next_ = instruction;
793 instruction->previous_ = cursor;
794 last_instruction_ = instruction;
795 } else {
796 instruction->next_ = cursor->next_;
797 instruction->previous_ = cursor;
798 cursor->next_ = instruction;
799 instruction->next_->previous_ = instruction;
800 }
801}
802
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100803void HInstructionList::RemoveInstruction(HInstruction* instruction) {
804 if (instruction->previous_ != nullptr) {
805 instruction->previous_->next_ = instruction->next_;
806 }
807 if (instruction->next_ != nullptr) {
808 instruction->next_->previous_ = instruction->previous_;
809 }
810 if (instruction == first_instruction_) {
811 first_instruction_ = instruction->next_;
812 }
813 if (instruction == last_instruction_) {
814 last_instruction_ = instruction->previous_;
815 }
816}
817
Roland Levillain6b469232014-09-25 10:10:38 +0100818bool HInstructionList::Contains(HInstruction* instruction) const {
819 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
820 if (it.Current() == instruction) {
821 return true;
822 }
823 }
824 return false;
825}
826
Roland Levillainccc07a92014-09-16 14:48:16 +0100827bool HInstructionList::FoundBefore(const HInstruction* instruction1,
828 const HInstruction* instruction2) const {
829 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
830 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
831 if (it.Current() == instruction1) {
832 return true;
833 }
834 if (it.Current() == instruction2) {
835 return false;
836 }
837 }
838 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
839 return true;
840}
841
Roland Levillain6c82d402014-10-13 16:10:27 +0100842bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
843 if (other_instruction == this) {
844 // An instruction does not strictly dominate itself.
845 return false;
846 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100847 HBasicBlock* block = GetBlock();
848 HBasicBlock* other_block = other_instruction->GetBlock();
849 if (block != other_block) {
850 return GetBlock()->Dominates(other_instruction->GetBlock());
851 } else {
852 // If both instructions are in the same block, ensure this
853 // instruction comes before `other_instruction`.
854 if (IsPhi()) {
855 if (!other_instruction->IsPhi()) {
856 // Phis appear before non phi-instructions so this instruction
857 // dominates `other_instruction`.
858 return true;
859 } else {
860 // There is no order among phis.
861 LOG(FATAL) << "There is no dominance between phis of a same block.";
862 return false;
863 }
864 } else {
865 // `this` is not a phi.
866 if (other_instruction->IsPhi()) {
867 // Phis appear before non phi-instructions so this instruction
868 // does not dominate `other_instruction`.
869 return false;
870 } else {
871 // Check whether this instruction comes before
872 // `other_instruction` in the instruction list.
873 return block->GetInstructions().FoundBefore(this, other_instruction);
874 }
875 }
876 }
877}
878
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100879void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100880 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000881 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
882 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883 HInstruction* user = current->GetUser();
884 size_t input_index = current->GetIndex();
885 user->SetRawInputAt(input_index, other);
886 other->AddUseAt(user, input_index);
887 }
888
David Brazdiled596192015-01-23 10:39:45 +0000889 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
890 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100891 HEnvironment* user = current->GetUser();
892 size_t input_index = current->GetIndex();
893 user->SetRawEnvAt(input_index, other);
894 other->AddEnvUseAt(user, input_index);
895 }
896
David Brazdiled596192015-01-23 10:39:45 +0000897 uses_.Clear();
898 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100899}
900
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100901void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000902 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100903 SetRawInputAt(index, replacement);
904 replacement->AddUseAt(this, index);
905}
906
Nicolas Geoffray39468442014-09-02 15:17:15 +0100907size_t HInstruction::EnvironmentSize() const {
908 return HasEnvironment() ? environment_->Size() : 0;
909}
910
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100911void HPhi::AddInput(HInstruction* input) {
912 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100913 inputs_.push_back(HUserRecord<HInstruction*>(input));
914 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100915}
916
David Brazdil2d7352b2015-04-20 14:52:42 +0100917void HPhi::RemoveInputAt(size_t index) {
918 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100919 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100920 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100921 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100922 InputRecordAt(i).GetUseNode()->SetIndex(i);
923 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100924}
925
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100926#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000927void H##name::Accept(HGraphVisitor* visitor) { \
928 visitor->Visit##name(this); \
929}
930
931FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
932
933#undef DEFINE_ACCEPT
934
935void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100936 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
937 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000938 if (block != nullptr) {
939 VisitBasicBlock(block);
940 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000941 }
942}
943
Roland Levillain633021e2014-10-01 14:12:25 +0100944void HGraphVisitor::VisitReversePostOrder() {
945 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
946 VisitBasicBlock(it.Current());
947 }
948}
949
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000950void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100951 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100952 it.Current()->Accept(this);
953 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100954 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000955 it.Current()->Accept(this);
956 }
957}
958
Mark Mendelle82549b2015-05-06 10:55:34 -0400959HConstant* HTypeConversion::TryStaticEvaluation() const {
960 HGraph* graph = GetBlock()->GetGraph();
961 if (GetInput()->IsIntConstant()) {
962 int32_t value = GetInput()->AsIntConstant()->GetValue();
963 switch (GetResultType()) {
964 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600965 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400966 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600967 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400968 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600969 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400970 default:
971 return nullptr;
972 }
973 } else if (GetInput()->IsLongConstant()) {
974 int64_t value = GetInput()->AsLongConstant()->GetValue();
975 switch (GetResultType()) {
976 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600977 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400978 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600979 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400980 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600981 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400982 default:
983 return nullptr;
984 }
985 } else if (GetInput()->IsFloatConstant()) {
986 float value = GetInput()->AsFloatConstant()->GetValue();
987 switch (GetResultType()) {
988 case Primitive::kPrimInt:
989 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600990 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400991 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600992 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400993 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600994 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
995 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400996 case Primitive::kPrimLong:
997 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600998 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400999 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001000 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001001 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001002 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1003 return graph->GetLongConstant(static_cast<int64_t>(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()->IsDoubleConstant()) {
1010 double value = GetInput()->AsDoubleConstant()->GetValue();
1011 switch (GetResultType()) {
1012 case Primitive::kPrimInt:
1013 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001014 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001015 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001016 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001017 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001018 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1019 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001020 case Primitive::kPrimLong:
1021 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001022 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001023 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001024 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001025 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001026 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1027 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001028 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001029 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001030 default:
1031 return nullptr;
1032 }
1033 }
1034 return nullptr;
1035}
1036
Roland Levillain9240d6a2014-10-20 16:47:04 +01001037HConstant* HUnaryOperation::TryStaticEvaluation() const {
1038 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001039 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001040 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001041 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001042 }
1043 return nullptr;
1044}
1045
1046HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001047 if (GetLeft()->IsIntConstant()) {
1048 if (GetRight()->IsIntConstant()) {
1049 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1050 } else if (GetRight()->IsLongConstant()) {
1051 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1052 }
1053 } else if (GetLeft()->IsLongConstant()) {
1054 if (GetRight()->IsIntConstant()) {
1055 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1056 } else if (GetRight()->IsLongConstant()) {
1057 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001058 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001059 }
1060 return nullptr;
1061}
Dave Allison20dfc792014-06-16 20:44:29 -07001062
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001063HConstant* HBinaryOperation::GetConstantRight() const {
1064 if (GetRight()->IsConstant()) {
1065 return GetRight()->AsConstant();
1066 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1067 return GetLeft()->AsConstant();
1068 } else {
1069 return nullptr;
1070 }
1071}
1072
1073// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001074// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001075HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1076 HInstruction* most_constant_right = GetConstantRight();
1077 if (most_constant_right == nullptr) {
1078 return nullptr;
1079 } else if (most_constant_right == GetLeft()) {
1080 return GetRight();
1081 } else {
1082 return GetLeft();
1083 }
1084}
1085
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001086bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1087 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001088}
1089
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001090bool HInstruction::Equals(HInstruction* other) const {
1091 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001092 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001093 if (!InstructionDataEquals(other)) return false;
1094 if (GetType() != other->GetType()) return false;
1095 if (InputCount() != other->InputCount()) return false;
1096
1097 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1098 if (InputAt(i) != other->InputAt(i)) return false;
1099 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001100 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001101 return true;
1102}
1103
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001104std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1105#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1106 switch (rhs) {
1107 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1108 default:
1109 os << "Unknown instruction kind " << static_cast<int>(rhs);
1110 break;
1111 }
1112#undef DECLARE_CASE
1113 return os;
1114}
1115
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001116void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001117 next_->previous_ = previous_;
1118 if (previous_ != nullptr) {
1119 previous_->next_ = next_;
1120 }
1121 if (block_->instructions_.first_instruction_ == this) {
1122 block_->instructions_.first_instruction_ = next_;
1123 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001124 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001125
1126 previous_ = cursor->previous_;
1127 if (previous_ != nullptr) {
1128 previous_->next_ = this;
1129 }
1130 next_ = cursor;
1131 cursor->previous_ = this;
1132 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001133
1134 if (block_->instructions_.first_instruction_ == cursor) {
1135 block_->instructions_.first_instruction_ = this;
1136 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001137}
1138
David Brazdilfc6a86a2015-06-26 10:33:45 +00001139HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1140 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1141 DCHECK_EQ(cursor->GetBlock(), this);
1142
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001143 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1144 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001145 new_block->instructions_.first_instruction_ = cursor;
1146 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1147 instructions_.last_instruction_ = cursor->previous_;
1148 if (cursor->previous_ == nullptr) {
1149 instructions_.first_instruction_ = nullptr;
1150 } else {
1151 cursor->previous_->next_ = nullptr;
1152 cursor->previous_ = nullptr;
1153 }
1154
1155 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001156 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001157
Vladimir Marko60584552015-09-03 13:35:12 +00001158 for (HBasicBlock* successor : GetSuccessors()) {
1159 new_block->successors_.push_back(successor);
1160 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001161 }
Vladimir Marko60584552015-09-03 13:35:12 +00001162 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001163 AddSuccessor(new_block);
1164
David Brazdil56e1acc2015-06-30 15:41:36 +01001165 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001166 return new_block;
1167}
1168
David Brazdild7558da2015-09-22 13:04:14 +01001169HBasicBlock* HBasicBlock::CreateImmediateDominator() {
1170 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1171 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1172
1173 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1174
1175 for (HBasicBlock* predecessor : GetPredecessors()) {
1176 new_block->predecessors_.push_back(predecessor);
1177 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1178 }
1179 predecessors_.clear();
1180 AddPredecessor(new_block);
1181
1182 GetGraph()->AddBlock(new_block);
1183 return new_block;
1184}
1185
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001186HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1187 DCHECK(!cursor->IsControlFlow());
1188 DCHECK_NE(instructions_.last_instruction_, cursor);
1189 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001190
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001191 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1192 new_block->instructions_.first_instruction_ = cursor->GetNext();
1193 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1194 cursor->next_->previous_ = nullptr;
1195 cursor->next_ = nullptr;
1196 instructions_.last_instruction_ = cursor;
1197
1198 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001199 for (HBasicBlock* successor : GetSuccessors()) {
1200 new_block->successors_.push_back(successor);
1201 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001202 }
Vladimir Marko60584552015-09-03 13:35:12 +00001203 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001204
Vladimir Marko60584552015-09-03 13:35:12 +00001205 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001206 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001207 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001208 }
Vladimir Marko60584552015-09-03 13:35:12 +00001209 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001210 return new_block;
1211}
1212
David Brazdilec16f792015-08-19 15:04:01 +01001213const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001214 if (EndsWithTryBoundary()) {
1215 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1216 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001217 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001218 return try_boundary;
1219 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001220 DCHECK(IsTryBlock());
1221 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001222 return nullptr;
1223 }
David Brazdilec16f792015-08-19 15:04:01 +01001224 } else if (IsTryBlock()) {
1225 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001226 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001227 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001228 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001229}
1230
David Brazdild7558da2015-09-22 13:04:14 +01001231bool HBasicBlock::HasThrowingInstructions() const {
1232 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1233 if (it.Current()->CanThrow()) {
1234 return true;
1235 }
1236 }
1237 return false;
1238}
1239
David Brazdilfc6a86a2015-06-26 10:33:45 +00001240static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1241 return block.GetPhis().IsEmpty()
1242 && !block.GetInstructions().IsEmpty()
1243 && block.GetFirstInstruction() == block.GetLastInstruction();
1244}
1245
David Brazdil46e2a392015-03-16 17:31:52 +00001246bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001247 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1248}
1249
1250bool HBasicBlock::IsSingleTryBoundary() const {
1251 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001252}
1253
David Brazdil8d5b8b22015-03-24 10:51:52 +00001254bool HBasicBlock::EndsWithControlFlowInstruction() const {
1255 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1256}
1257
David Brazdilb2bd1c52015-03-25 11:17:37 +00001258bool HBasicBlock::EndsWithIf() const {
1259 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1260}
1261
David Brazdilffee3d32015-07-06 11:48:53 +01001262bool HBasicBlock::EndsWithTryBoundary() const {
1263 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1264}
1265
David Brazdilb2bd1c52015-03-25 11:17:37 +00001266bool HBasicBlock::HasSinglePhi() const {
1267 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1268}
1269
David Brazdilffee3d32015-07-06 11:48:53 +01001270bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001271 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001272 return false;
1273 }
1274
David Brazdilb618ade2015-07-29 10:31:29 +01001275 // Exception handlers need to be stored in the same order.
1276 for (HExceptionHandlerIterator it1(*this), it2(other);
1277 !it1.Done();
1278 it1.Advance(), it2.Advance()) {
1279 DCHECK(!it2.Done());
1280 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001281 return false;
1282 }
1283 }
1284 return true;
1285}
1286
David Brazdil2d7352b2015-04-20 14:52:42 +01001287size_t HInstructionList::CountSize() const {
1288 size_t size = 0;
1289 HInstruction* current = first_instruction_;
1290 for (; current != nullptr; current = current->GetNext()) {
1291 size++;
1292 }
1293 return size;
1294}
1295
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001296void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1297 for (HInstruction* current = first_instruction_;
1298 current != nullptr;
1299 current = current->GetNext()) {
1300 current->SetBlock(block);
1301 }
1302}
1303
1304void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1305 DCHECK(Contains(cursor));
1306 if (!instruction_list.IsEmpty()) {
1307 if (cursor == last_instruction_) {
1308 last_instruction_ = instruction_list.last_instruction_;
1309 } else {
1310 cursor->next_->previous_ = instruction_list.last_instruction_;
1311 }
1312 instruction_list.last_instruction_->next_ = cursor->next_;
1313 cursor->next_ = instruction_list.first_instruction_;
1314 instruction_list.first_instruction_->previous_ = cursor;
1315 }
1316}
1317
1318void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001319 if (IsEmpty()) {
1320 first_instruction_ = instruction_list.first_instruction_;
1321 last_instruction_ = instruction_list.last_instruction_;
1322 } else {
1323 AddAfter(last_instruction_, instruction_list);
1324 }
1325}
1326
David Brazdil2d7352b2015-04-20 14:52:42 +01001327void HBasicBlock::DisconnectAndDelete() {
1328 // Dominators must be removed after all the blocks they dominate. This way
1329 // a loop header is removed last, a requirement for correct loop information
1330 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001331 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001332
David Brazdil2d7352b2015-04-20 14:52:42 +01001333 // Remove the block from all loops it is included in.
1334 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1335 HLoopInformation* loop_info = it.Current();
1336 loop_info->Remove(this);
1337 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001338 // If this was the last back edge of the loop, we deliberately leave the
1339 // loop in an inconsistent state and will fail SSAChecker unless the
1340 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001341 loop_info->RemoveBackEdge(this);
1342 }
1343 }
1344
1345 // Disconnect the block from its predecessors and update their control-flow
1346 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001347 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001348 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil2d7352b2015-04-20 14:52:42 +01001349 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001350 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1351 if (num_pred_successors == 1u) {
1352 // If we have one successor after removing one, then we must have
1353 // had an HIf or HPackedSwitch, as they have more than one successor.
1354 // Replace those with a HGoto.
1355 DCHECK(last_instruction->IsIf() || last_instruction->IsPackedSwitch());
1356 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001357 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001358 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001359 // The predecessor has no remaining successors and therefore must be dead.
1360 // We deliberately leave it without a control-flow instruction so that the
1361 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001362 predecessor->RemoveInstruction(last_instruction);
1363 } else {
1364 // There are multiple successors left. This must come from a HPackedSwitch
1365 // and we are in the middle of removing the HPackedSwitch. Like above, leave
1366 // this alone, and the SSAChecker will fail if it is not removed as well.
1367 DCHECK(last_instruction->IsPackedSwitch());
David Brazdil2d7352b2015-04-20 14:52:42 +01001368 }
David Brazdil46e2a392015-03-16 17:31:52 +00001369 }
Vladimir Marko60584552015-09-03 13:35:12 +00001370 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001371
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001372 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001373 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001374 // Delete this block from the list of predecessors.
1375 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001376 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001377
1378 // Check that `successor` has other predecessors, otherwise `this` is the
1379 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001380 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001381
David Brazdil2d7352b2015-04-20 14:52:42 +01001382 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001383 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001384 // The successor has just one predecessor left. Replace phis with the only
1385 // remaining input.
1386 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1387 HPhi* phi = phi_it.Current()->AsPhi();
1388 phi->ReplaceWith(phi->InputAt(1 - this_index));
1389 successor->RemovePhi(phi);
1390 }
1391 } else {
1392 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1393 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1394 }
1395 }
1396 }
Vladimir Marko60584552015-09-03 13:35:12 +00001397 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001398
1399 // Disconnect from the dominator.
1400 dominator_->RemoveDominatedBlock(this);
1401 SetDominator(nullptr);
1402
1403 // Delete from the graph. The function safely deletes remaining instructions
1404 // and updates the reverse post order.
1405 graph_->DeleteDeadBlock(this);
1406 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001407}
1408
1409void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001410 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001411 DCHECK(ContainsElement(dominated_blocks_, other));
1412 DCHECK_EQ(GetSingleSuccessor(), other);
1413 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001414 DCHECK(other->GetPhis().IsEmpty());
1415
David Brazdil2d7352b2015-04-20 14:52:42 +01001416 // Move instructions from `other` to `this`.
1417 DCHECK(EndsWithControlFlowInstruction());
1418 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001419 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001420 other->instructions_.SetBlockOfInstructions(this);
1421 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001422
David Brazdil2d7352b2015-04-20 14:52:42 +01001423 // Remove `other` from the loops it is included in.
1424 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1425 HLoopInformation* loop_info = it.Current();
1426 loop_info->Remove(other);
1427 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001428 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001429 }
1430 }
1431
1432 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001433 successors_.clear();
1434 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001435 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 successor->ReplacePredecessor(other, this);
1437 }
1438
David Brazdil2d7352b2015-04-20 14:52:42 +01001439 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001440 RemoveDominatedBlock(other);
1441 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1442 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001443 dominated->SetDominator(this);
1444 }
Vladimir Marko60584552015-09-03 13:35:12 +00001445 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001446 other->dominator_ = nullptr;
1447
1448 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001449 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001450
1451 // Delete `other` from the graph. The function updates reverse post order.
1452 graph_->DeleteDeadBlock(other);
1453 other->SetGraph(nullptr);
1454}
1455
1456void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1457 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001458 DCHECK(GetDominatedBlocks().empty());
1459 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001460 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001461 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001462 DCHECK(other->GetPhis().IsEmpty());
1463 DCHECK(!other->IsInLoop());
1464
1465 // Move instructions from `other` to `this`.
1466 instructions_.Add(other->GetInstructions());
1467 other->instructions_.SetBlockOfInstructions(this);
1468
1469 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001470 successors_.clear();
1471 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001472 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001473 successor->ReplacePredecessor(other, this);
1474 }
1475
1476 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001477 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1478 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001479 dominated->SetDominator(this);
1480 }
Vladimir Marko60584552015-09-03 13:35:12 +00001481 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001482 other->dominator_ = nullptr;
1483 other->graph_ = nullptr;
1484}
1485
1486void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001487 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001488 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001489 predecessor->ReplaceSuccessor(this, other);
1490 }
Vladimir Marko60584552015-09-03 13:35:12 +00001491 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001492 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001493 successor->ReplacePredecessor(this, other);
1494 }
Vladimir Marko60584552015-09-03 13:35:12 +00001495 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1496 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001497 }
1498 GetDominator()->ReplaceDominatedBlock(this, other);
1499 other->SetDominator(GetDominator());
1500 dominator_ = nullptr;
1501 graph_ = nullptr;
1502}
1503
1504// Create space in `blocks` for adding `number_of_new_blocks` entries
1505// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001506static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001507 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001508 size_t after) {
1509 DCHECK_LT(after, blocks->size());
1510 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001511 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001512 blocks->resize(new_size);
1513 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001514}
1515
David Brazdil2d7352b2015-04-20 14:52:42 +01001516void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1517 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001518 DCHECK(block->GetSuccessors().empty());
1519 DCHECK(block->GetPredecessors().empty());
1520 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001521 DCHECK(block->GetDominator() == nullptr);
1522
1523 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1524 block->RemoveInstruction(it.Current());
1525 }
1526 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1527 block->RemovePhi(it.Current()->AsPhi());
1528 }
1529
David Brazdilc7af85d2015-05-26 12:05:55 +01001530 if (block->IsExitBlock()) {
1531 exit_block_ = nullptr;
1532 }
1533
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001534 RemoveElement(reverse_post_order_, block);
1535 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001536}
1537
Calin Juravle2e768302015-07-28 14:41:11 +00001538HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001539 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001540 // Update the environments in this graph to have the invoke's environment
1541 // as parent.
1542 {
1543 HReversePostOrderIterator it(*this);
1544 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1545 for (; !it.Done(); it.Advance()) {
1546 HBasicBlock* block = it.Current();
1547 for (HInstructionIterator instr_it(block->GetInstructions());
1548 !instr_it.Done();
1549 instr_it.Advance()) {
1550 HInstruction* current = instr_it.Current();
1551 if (current->NeedsEnvironment()) {
1552 current->GetEnvironment()->SetAndCopyParentChain(
1553 outer_graph->GetArena(), invoke->GetEnvironment());
1554 }
1555 }
1556 }
1557 }
1558 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1559 if (HasBoundsChecks()) {
1560 outer_graph->SetHasBoundsChecks(true);
1561 }
1562
Calin Juravle2e768302015-07-28 14:41:11 +00001563 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001564 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001565 // Simple case of an entry block, a body block, and an exit block.
1566 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001567 HBasicBlock* body = GetBlocks()[1];
1568 DCHECK(GetBlocks()[0]->IsEntryBlock());
1569 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001570 DCHECK(!body->IsExitBlock());
1571 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001572
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001573 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1574 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001575
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001576 // Replace the invoke with the return value of the inlined graph.
1577 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001578 return_value = last->InputAt(0);
1579 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001580 } else {
1581 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001582 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001583
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001584 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001585 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001586 // Need to inline multiple blocks. We split `invoke`'s block
1587 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001588 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001589 // with the second half.
1590 ArenaAllocator* allocator = outer_graph->GetArena();
1591 HBasicBlock* at = invoke->GetBlock();
1592 HBasicBlock* to = at->SplitAfter(invoke);
1593
Vladimir Markoec7802a2015-10-01 20:57:57 +01001594 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001595 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001596 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001597 exit_block_->ReplaceWith(to);
1598
1599 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001600 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001601 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001602 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001603 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001604 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001605 if (!returns_void) {
1606 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001607 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001608 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001609 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001610 } else {
1611 if (!returns_void) {
1612 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001613 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001614 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001615 to->AddPhi(return_value->AsPhi());
1616 }
Vladimir Marko60584552015-09-03 13:35:12 +00001617 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001618 HInstruction* last = predecessor->GetLastInstruction();
1619 if (!returns_void) {
1620 return_value->AsPhi()->AddInput(last->InputAt(0));
1621 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001622 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001623 predecessor->RemoveInstruction(last);
1624 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001625 }
1626
1627 if (return_value != nullptr) {
1628 invoke->ReplaceWith(return_value);
1629 }
1630
1631 // Update the meta information surrounding blocks:
1632 // (1) the graph they are now in,
1633 // (2) the reverse post order of that graph,
1634 // (3) the potential loop information they are now in.
1635
1636 // We don't add the entry block, the exit block, and the first block, which
1637 // has been merged with `at`.
1638 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1639
1640 // We add the `to` block.
1641 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001642 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001643 + kNumberOfNewBlocksInCaller;
1644
1645 // Find the location of `at` in the outer graph's reverse post order. The new
1646 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001647 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001648 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1649
1650 // Do a reverse post order of the blocks in the callee and do (1), (2),
1651 // and (3) to the blocks that apply.
1652 HLoopInformation* info = at->GetLoopInformation();
1653 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1654 HBasicBlock* current = it.Current();
1655 if (current != exit_block_ && current != entry_block_ && current != first) {
1656 DCHECK(!current->IsInLoop());
1657 DCHECK(current->GetGraph() == this);
1658 current->SetGraph(outer_graph);
1659 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001660 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001661 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001662 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001663 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1664 loop_it.Current()->Add(current);
1665 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001666 }
1667 }
1668 }
1669
1670 // Do (1), (2), and (3) to `to`.
1671 to->SetGraph(outer_graph);
1672 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001673 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001674 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001675 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001676 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1677 loop_it.Current()->Add(to);
1678 }
David Brazdil46e2a392015-03-16 17:31:52 +00001679 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001680 // Only `to` can become a back edge, as the inlined blocks
1681 // are predecessors of `to`.
1682 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001683 }
1684 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001685 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001686
David Brazdil05144f42015-04-16 15:18:00 +01001687 // Update the next instruction id of the outer graph, so that instructions
1688 // added later get bigger ids than those in the inner graph.
1689 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1690
1691 // Walk over the entry block and:
1692 // - Move constants from the entry block to the outer_graph's entry block,
1693 // - Replace HParameterValue instructions with their real value.
1694 // - Remove suspend checks, that hold an environment.
1695 // We must do this after the other blocks have been inlined, otherwise ids of
1696 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001697 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001698 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1699 HInstruction* current = it.Current();
1700 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001701 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001702 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001703 current->ReplaceWith(outer_graph->GetIntConstant(
1704 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001705 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001706 current->ReplaceWith(outer_graph->GetLongConstant(
1707 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001708 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001709 current->ReplaceWith(outer_graph->GetFloatConstant(
1710 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001711 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001712 current->ReplaceWith(outer_graph->GetDoubleConstant(
1713 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001714 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001715 if (kIsDebugBuild
1716 && invoke->IsInvokeStaticOrDirect()
1717 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1718 // Ensure we do not use the last input of `invoke`, as it
1719 // contains a clinit check which is not an actual argument.
1720 size_t last_input_index = invoke->InputCount() - 1;
1721 DCHECK(parameter_index != last_input_index);
1722 }
David Brazdil05144f42015-04-16 15:18:00 +01001723 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001724 } else if (current->IsCurrentMethod()) {
1725 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001726 } else {
1727 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1728 entry_block_->RemoveInstruction(current);
1729 }
1730 }
1731
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001732 // Finally remove the invoke from the caller.
1733 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001734
1735 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001736}
1737
Mingyao Yang3584bce2015-05-19 16:01:59 -07001738/*
1739 * Loop will be transformed to:
1740 * old_pre_header
1741 * |
1742 * if_block
1743 * / \
1744 * dummy_block deopt_block
1745 * \ /
1746 * new_pre_header
1747 * |
1748 * header
1749 */
1750void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1751 DCHECK(header->IsLoopHeader());
1752 HBasicBlock* pre_header = header->GetDominator();
1753
1754 // Need this to avoid critical edge.
1755 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1756 // Need this to avoid critical edge.
1757 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1758 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1759 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1760 AddBlock(if_block);
1761 AddBlock(dummy_block);
1762 AddBlock(deopt_block);
1763 AddBlock(new_pre_header);
1764
1765 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001766 pre_header->successors_.clear();
1767 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001768
1769 pre_header->AddSuccessor(if_block);
1770 if_block->AddSuccessor(dummy_block); // True successor
1771 if_block->AddSuccessor(deopt_block); // False successor
1772 dummy_block->AddSuccessor(new_pre_header);
1773 deopt_block->AddSuccessor(new_pre_header);
1774
Vladimir Marko60584552015-09-03 13:35:12 +00001775 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001776 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001777 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001778 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001779 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001780 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001781 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001782 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001783 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001784 header->SetDominator(new_pre_header);
1785
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001786 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001787 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001788 reverse_post_order_[index_of_header++] = if_block;
1789 reverse_post_order_[index_of_header++] = dummy_block;
1790 reverse_post_order_[index_of_header++] = deopt_block;
1791 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001792
1793 HLoopInformation* info = pre_header->GetLoopInformation();
1794 if (info != nullptr) {
1795 if_block->SetLoopInformation(info);
1796 dummy_block->SetLoopInformation(info);
1797 deopt_block->SetLoopInformation(info);
1798 new_pre_header->SetLoopInformation(info);
1799 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1800 !loop_it.Done();
1801 loop_it.Advance()) {
1802 loop_it.Current()->Add(if_block);
1803 loop_it.Current()->Add(dummy_block);
1804 loop_it.Current()->Add(deopt_block);
1805 loop_it.Current()->Add(new_pre_header);
1806 }
1807 }
1808}
1809
Calin Juravle2e768302015-07-28 14:41:11 +00001810void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1811 if (kIsDebugBuild) {
1812 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1813 ScopedObjectAccess soa(Thread::Current());
1814 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1815 if (IsBoundType()) {
1816 // Having the test here spares us from making the method virtual just for
1817 // the sake of a DCHECK.
1818 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1819 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1820 << " upper_bound_rti: " << upper_bound_rti
1821 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001822 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001823 }
1824 }
1825 reference_type_info_ = rti;
1826}
1827
1828ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1829
1830ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1831 : type_handle_(type_handle), is_exact_(is_exact) {
1832 if (kIsDebugBuild) {
1833 ScopedObjectAccess soa(Thread::Current());
1834 DCHECK(IsValidHandle(type_handle));
1835 }
1836}
1837
Calin Juravleacf735c2015-02-12 15:25:22 +00001838std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1839 ScopedObjectAccess soa(Thread::Current());
1840 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001841 << " is_valid=" << rhs.IsValid()
1842 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001843 << " is_exact=" << rhs.IsExact()
1844 << " ]";
1845 return os;
1846}
1847
Mark Mendellc4701932015-04-10 13:18:51 -04001848bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1849 // For now, assume that instructions in different blocks may use the
1850 // environment.
1851 // TODO: Use the control flow to decide if this is true.
1852 if (GetBlock() != other->GetBlock()) {
1853 return true;
1854 }
1855
1856 // We know that we are in the same block. Walk from 'this' to 'other',
1857 // checking to see if there is any instruction with an environment.
1858 HInstruction* current = this;
1859 for (; current != other && current != nullptr; current = current->GetNext()) {
1860 // This is a conservative check, as the instruction result may not be in
1861 // the referenced environment.
1862 if (current->HasEnvironment()) {
1863 return true;
1864 }
1865 }
1866
1867 // We should have been called with 'this' before 'other' in the block.
1868 // Just confirm this.
1869 DCHECK(current != nullptr);
1870 return false;
1871}
1872
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001873void HInvoke::SetIntrinsic(Intrinsics intrinsic,
1874 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache) {
1875 intrinsic_ = intrinsic;
1876 IntrinsicOptimizations opt(this);
1877 if (needs_env_or_cache == kNoEnvironmentOrCache) {
1878 opt.SetDoesNotNeedDexCache();
1879 opt.SetDoesNotNeedEnvironment();
1880 }
1881}
1882
1883bool HInvoke::NeedsEnvironment() const {
1884 if (!IsIntrinsic()) {
1885 return true;
1886 }
1887 IntrinsicOptimizations opt(*this);
1888 return !opt.GetDoesNotNeedEnvironment();
1889}
1890
1891bool HInvokeStaticOrDirect::NeedsDexCache() const {
1892 if (IsRecursive() || IsStringInit()) {
1893 return false;
1894 }
1895 if (!IsIntrinsic()) {
1896 return true;
1897 }
1898 IntrinsicOptimizations opt(*this);
1899 return !opt.GetDoesNotNeedDexCache();
1900}
1901
Mark Mendellc4701932015-04-10 13:18:51 -04001902void HInstruction::RemoveEnvironmentUsers() {
1903 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1904 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1905 HEnvironment* user = user_node->GetUser();
1906 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1907 }
1908 env_uses_.Clear();
1909}
1910
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001911} // namespace art