blob: 81daa7f0b0958432d708a9e33a71c20b6f509b8f [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.
David Brazdil9bc43612015-11-05 21:25:24 +0000338 //
David Brazdilffee3d32015-07-06 11:48:53 +0100339 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000340 // a move-exception instruction, as guaranteed by the verifier. However,
341 // trivially dead predecessors are ignored by the verifier and such code
342 // has not been removed at this stage. We therefore ignore the assumption
343 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
344 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
345 if (normal_block == nullptr) {
346 // Catch block is either empty or only contains a move-exception. It must
347 // therefore be dead and will be removed during initial DCE. Do nothing.
348 DCHECK(!catch_block->EndsWithControlFlowInstruction());
349 } else {
350 // Catch block was split. Re-link normal-flow edges to the new block.
351 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
352 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
353 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
354 --j;
355 }
David Brazdilffee3d32015-07-06 11:48:53 +0100356 }
357 }
358 }
359 }
360}
361
362void HGraph::ComputeTryBlockInformation() {
363 // Iterate in reverse post order to propagate try membership information from
364 // predecessors to their successors.
365 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
366 HBasicBlock* block = it.Current();
367 if (block->IsEntryBlock() || block->IsCatchBlock()) {
368 // Catch blocks after simplification have only exceptional predecessors
369 // and hence are never in tries.
370 continue;
371 }
372
373 // Infer try membership from the first predecessor. Having simplified loops,
374 // the first predecessor can never be a back edge and therefore it must have
375 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100376 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100377 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100378 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000379 if (try_entry != nullptr &&
380 (block->GetTryCatchInformation() == nullptr ||
381 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
382 // We are either setting try block membership for the first time or it
383 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100384 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
385 }
David Brazdilffee3d32015-07-06 11:48:53 +0100386 }
387}
388
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100389void HGraph::SimplifyCFG() {
390 // Simplify the CFG for future analysis, and code generation:
391 // (1): Split critical edges.
392 // (2): Simplify loops by having only one back edge, and one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100393 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
394 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
395 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
396 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100397 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100398 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000399 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100400 HBasicBlock* successor = block->GetSuccessors()[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100401 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000402 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100403 SplitCriticalEdge(block, successor);
404 --j;
405 }
406 }
407 }
408 if (block->IsLoopHeader()) {
409 SimplifyLoop(block);
410 }
411 }
412}
413
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000414bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100415 // Order does not matter.
416 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
417 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100418 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100419 if (block->IsCatchBlock()) {
420 // TODO: Dealing with exceptional back edges could be tricky because
421 // they only approximate the real control flow. Bail out for now.
422 return false;
423 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100424 HLoopInformation* info = block->GetLoopInformation();
425 if (!info->Populate()) {
426 // Abort if the loop is non natural. We currently bailout in such cases.
427 return false;
428 }
429 }
430 }
431 return true;
432}
433
David Brazdil8d5b8b22015-03-24 10:51:52 +0000434void HGraph::InsertConstant(HConstant* constant) {
435 // New constants are inserted before the final control-flow instruction
436 // of the graph, or at its end if called from the graph builder.
437 if (entry_block_->EndsWithControlFlowInstruction()) {
438 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000439 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000440 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000441 }
442}
443
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600444HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100445 // For simplicity, don't bother reviving the cached null constant if it is
446 // not null and not in a block. Otherwise, we need to clear the instruction
447 // id and/or any invariants the graph is assuming when adding new instructions.
448 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600449 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000450 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000451 }
452 return cached_null_constant_;
453}
454
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100455HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100456 // For simplicity, don't bother reviving the cached current method if it is
457 // not null and not in a block. Otherwise, we need to clear the instruction
458 // id and/or any invariants the graph is assuming when adding new instructions.
459 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700460 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600461 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
462 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100463 if (entry_block_->GetFirstInstruction() == nullptr) {
464 entry_block_->AddInstruction(cached_current_method_);
465 } else {
466 entry_block_->InsertInstructionBefore(
467 cached_current_method_, entry_block_->GetFirstInstruction());
468 }
469 }
470 return cached_current_method_;
471}
472
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600473HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000474 switch (type) {
475 case Primitive::Type::kPrimBoolean:
476 DCHECK(IsUint<1>(value));
477 FALLTHROUGH_INTENDED;
478 case Primitive::Type::kPrimByte:
479 case Primitive::Type::kPrimChar:
480 case Primitive::Type::kPrimShort:
481 case Primitive::Type::kPrimInt:
482 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600483 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000484
485 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600486 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000487
488 default:
489 LOG(FATAL) << "Unsupported constant type";
490 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000491 }
David Brazdil46e2a392015-03-16 17:31:52 +0000492}
493
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000494void HGraph::CacheFloatConstant(HFloatConstant* constant) {
495 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
496 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
497 cached_float_constants_.Overwrite(value, constant);
498}
499
500void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
501 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
502 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
503 cached_double_constants_.Overwrite(value, constant);
504}
505
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000506void HLoopInformation::Add(HBasicBlock* block) {
507 blocks_.SetBit(block->GetBlockId());
508}
509
David Brazdil46e2a392015-03-16 17:31:52 +0000510void HLoopInformation::Remove(HBasicBlock* block) {
511 blocks_.ClearBit(block->GetBlockId());
512}
513
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100514void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
515 if (blocks_.IsBitSet(block->GetBlockId())) {
516 return;
517 }
518
519 blocks_.SetBit(block->GetBlockId());
520 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000521 for (HBasicBlock* predecessor : block->GetPredecessors()) {
522 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100523 }
524}
525
526bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100527 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100528 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100529 DCHECK(back_edge->GetDominator() != nullptr);
530 if (!header_->Dominates(back_edge)) {
531 // This loop is not natural. Do not bother going further.
532 return false;
533 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100534
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100535 // Populate this loop: starting with the back edge, recursively add predecessors
536 // that are not already part of that loop. Set the header as part of the loop
537 // to end the recursion.
538 // This is a recursive implementation of the algorithm described in
539 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
540 blocks_.SetBit(header_->GetBlockId());
541 PopulateRecursive(back_edge);
542 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100543 return true;
544}
545
David Brazdila4b8c212015-05-07 09:59:30 +0100546void HLoopInformation::Update() {
547 HGraph* graph = header_->GetGraph();
548 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100549 HBasicBlock* block = graph->GetBlocks()[id];
David Brazdila4b8c212015-05-07 09:59:30 +0100550 // Reset loop information of non-header blocks inside the loop, except
551 // members of inner nested loops because those should already have been
552 // updated by their own LoopInformation.
553 if (block->GetLoopInformation() == this && block != header_) {
554 block->SetLoopInformation(nullptr);
555 }
556 }
557 blocks_.ClearAllBits();
558
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100559 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100560 // The loop has been dismantled, delete its suspend check and remove info
561 // from the header.
562 DCHECK(HasSuspendCheck());
563 header_->RemoveInstruction(suspend_check_);
564 header_->SetLoopInformation(nullptr);
565 header_ = nullptr;
566 suspend_check_ = nullptr;
567 } else {
568 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100569 for (HBasicBlock* back_edge : back_edges_) {
570 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100571 }
572 }
573 // This loop still has reachable back edges. Repopulate the list of blocks.
574 bool populate_successful = Populate();
575 DCHECK(populate_successful);
576 }
577}
578
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100579HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100580 return header_->GetDominator();
581}
582
583bool HLoopInformation::Contains(const HBasicBlock& block) const {
584 return blocks_.IsBitSet(block.GetBlockId());
585}
586
587bool HLoopInformation::IsIn(const HLoopInformation& other) const {
588 return other.blocks_.IsBitSet(header_->GetBlockId());
589}
590
Aart Bik73f1f3b2015-10-28 15:28:08 -0700591bool HLoopInformation::IsLoopInvariant(HInstruction* instruction, bool must_dominate) const {
592 HLoopInformation* other_loop = instruction->GetBlock()->GetLoopInformation();
593 if (other_loop != this && (other_loop == nullptr || !other_loop->IsIn(*this))) {
594 if (must_dominate) {
595 return instruction->GetBlock()->Dominates(GetHeader());
596 }
597 return true;
598 }
599 return false;
600}
601
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100602size_t HLoopInformation::GetLifetimeEnd() const {
603 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100604 for (HBasicBlock* back_edge : GetBackEdges()) {
605 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100606 }
607 return last_position;
608}
609
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100610bool HBasicBlock::Dominates(HBasicBlock* other) const {
611 // Walk up the dominator tree from `other`, to find out if `this`
612 // is an ancestor.
613 HBasicBlock* current = other;
614 while (current != nullptr) {
615 if (current == this) {
616 return true;
617 }
618 current = current->GetDominator();
619 }
620 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100621}
622
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100623static void UpdateInputsUsers(HInstruction* instruction) {
624 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
625 instruction->InputAt(i)->AddUseAt(instruction, i);
626 }
627 // Environment should be created later.
628 DCHECK(!instruction->HasEnvironment());
629}
630
Roland Levillainccc07a92014-09-16 14:48:16 +0100631void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
632 HInstruction* replacement) {
633 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400634 if (initial->IsControlFlow()) {
635 // We can only replace a control flow instruction with another control flow instruction.
636 DCHECK(replacement->IsControlFlow());
637 DCHECK_EQ(replacement->GetId(), -1);
638 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
639 DCHECK_EQ(initial->GetBlock(), this);
640 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
641 DCHECK(initial->GetUses().IsEmpty());
642 DCHECK(initial->GetEnvUses().IsEmpty());
643 replacement->SetBlock(this);
644 replacement->SetId(GetGraph()->GetNextInstructionId());
645 instructions_.InsertInstructionBefore(replacement, initial);
646 UpdateInputsUsers(replacement);
647 } else {
648 InsertInstructionBefore(replacement, initial);
649 initial->ReplaceWith(replacement);
650 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100651 RemoveInstruction(initial);
652}
653
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100654static void Add(HInstructionList* instruction_list,
655 HBasicBlock* block,
656 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000657 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000658 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100659 instruction->SetBlock(block);
660 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100661 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100662 instruction_list->AddInstruction(instruction);
663}
664
665void HBasicBlock::AddInstruction(HInstruction* instruction) {
666 Add(&instructions_, this, instruction);
667}
668
669void HBasicBlock::AddPhi(HPhi* phi) {
670 Add(&phis_, this, phi);
671}
672
David Brazdilc3d743f2015-04-22 13:40:50 +0100673void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
674 DCHECK(!cursor->IsPhi());
675 DCHECK(!instruction->IsPhi());
676 DCHECK_EQ(instruction->GetId(), -1);
677 DCHECK_NE(cursor->GetId(), -1);
678 DCHECK_EQ(cursor->GetBlock(), this);
679 DCHECK(!instruction->IsControlFlow());
680 instruction->SetBlock(this);
681 instruction->SetId(GetGraph()->GetNextInstructionId());
682 UpdateInputsUsers(instruction);
683 instructions_.InsertInstructionBefore(instruction, cursor);
684}
685
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100686void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
687 DCHECK(!cursor->IsPhi());
688 DCHECK(!instruction->IsPhi());
689 DCHECK_EQ(instruction->GetId(), -1);
690 DCHECK_NE(cursor->GetId(), -1);
691 DCHECK_EQ(cursor->GetBlock(), this);
692 DCHECK(!instruction->IsControlFlow());
693 DCHECK(!cursor->IsControlFlow());
694 instruction->SetBlock(this);
695 instruction->SetId(GetGraph()->GetNextInstructionId());
696 UpdateInputsUsers(instruction);
697 instructions_.InsertInstructionAfter(instruction, cursor);
698}
699
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100700void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
701 DCHECK_EQ(phi->GetId(), -1);
702 DCHECK_NE(cursor->GetId(), -1);
703 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100704 phi->SetBlock(this);
705 phi->SetId(GetGraph()->GetNextInstructionId());
706 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100707 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100708}
709
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100710static void Remove(HInstructionList* instruction_list,
711 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000712 HInstruction* instruction,
713 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100714 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100715 instruction->SetBlock(nullptr);
716 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000717 if (ensure_safety) {
718 DCHECK(instruction->GetUses().IsEmpty());
719 DCHECK(instruction->GetEnvUses().IsEmpty());
720 RemoveAsUser(instruction);
721 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100722}
723
David Brazdil1abb4192015-02-17 18:33:36 +0000724void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100725 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000726 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100727}
728
David Brazdil1abb4192015-02-17 18:33:36 +0000729void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
730 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100731}
732
David Brazdilc7508e92015-04-27 13:28:57 +0100733void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
734 if (instruction->IsPhi()) {
735 RemovePhi(instruction->AsPhi(), ensure_safety);
736 } else {
737 RemoveInstruction(instruction, ensure_safety);
738 }
739}
740
Vladimir Marko71bf8092015-09-15 15:33:14 +0100741void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
742 for (size_t i = 0; i < locals.size(); i++) {
743 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100744 SetRawEnvAt(i, instruction);
745 if (instruction != nullptr) {
746 instruction->AddEnvUseAt(this, i);
747 }
748 }
749}
750
David Brazdiled596192015-01-23 10:39:45 +0000751void HEnvironment::CopyFrom(HEnvironment* env) {
752 for (size_t i = 0; i < env->Size(); i++) {
753 HInstruction* instruction = env->GetInstructionAt(i);
754 SetRawEnvAt(i, instruction);
755 if (instruction != nullptr) {
756 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100757 }
David Brazdiled596192015-01-23 10:39:45 +0000758 }
759}
760
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700761void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
762 HBasicBlock* loop_header) {
763 DCHECK(loop_header->IsLoopHeader());
764 for (size_t i = 0; i < env->Size(); i++) {
765 HInstruction* instruction = env->GetInstructionAt(i);
766 SetRawEnvAt(i, instruction);
767 if (instruction == nullptr) {
768 continue;
769 }
770 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
771 // At the end of the loop pre-header, the corresponding value for instruction
772 // is the first input of the phi.
773 HInstruction* initial = instruction->AsPhi()->InputAt(0);
774 DCHECK(initial->GetBlock()->Dominates(loop_header));
775 SetRawEnvAt(i, initial);
776 initial->AddEnvUseAt(this, i);
777 } else {
778 instruction->AddEnvUseAt(this, i);
779 }
780 }
781}
782
David Brazdil1abb4192015-02-17 18:33:36 +0000783void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100784 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000785 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100786}
787
Calin Juravle77520bc2015-01-12 18:45:46 +0000788HInstruction* HInstruction::GetNextDisregardingMoves() const {
789 HInstruction* next = GetNext();
790 while (next != nullptr && next->IsParallelMove()) {
791 next = next->GetNext();
792 }
793 return next;
794}
795
796HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
797 HInstruction* previous = GetPrevious();
798 while (previous != nullptr && previous->IsParallelMove()) {
799 previous = previous->GetPrevious();
800 }
801 return previous;
802}
803
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100804void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000805 if (first_instruction_ == nullptr) {
806 DCHECK(last_instruction_ == nullptr);
807 first_instruction_ = last_instruction_ = instruction;
808 } else {
809 last_instruction_->next_ = instruction;
810 instruction->previous_ = last_instruction_;
811 last_instruction_ = instruction;
812 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000813}
814
David Brazdilc3d743f2015-04-22 13:40:50 +0100815void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
816 DCHECK(Contains(cursor));
817 if (cursor == first_instruction_) {
818 cursor->previous_ = instruction;
819 instruction->next_ = cursor;
820 first_instruction_ = instruction;
821 } else {
822 instruction->previous_ = cursor->previous_;
823 instruction->next_ = cursor;
824 cursor->previous_ = instruction;
825 instruction->previous_->next_ = instruction;
826 }
827}
828
829void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
830 DCHECK(Contains(cursor));
831 if (cursor == last_instruction_) {
832 cursor->next_ = instruction;
833 instruction->previous_ = cursor;
834 last_instruction_ = instruction;
835 } else {
836 instruction->next_ = cursor->next_;
837 instruction->previous_ = cursor;
838 cursor->next_ = instruction;
839 instruction->next_->previous_ = instruction;
840 }
841}
842
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100843void HInstructionList::RemoveInstruction(HInstruction* instruction) {
844 if (instruction->previous_ != nullptr) {
845 instruction->previous_->next_ = instruction->next_;
846 }
847 if (instruction->next_ != nullptr) {
848 instruction->next_->previous_ = instruction->previous_;
849 }
850 if (instruction == first_instruction_) {
851 first_instruction_ = instruction->next_;
852 }
853 if (instruction == last_instruction_) {
854 last_instruction_ = instruction->previous_;
855 }
856}
857
Roland Levillain6b469232014-09-25 10:10:38 +0100858bool HInstructionList::Contains(HInstruction* instruction) const {
859 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
860 if (it.Current() == instruction) {
861 return true;
862 }
863 }
864 return false;
865}
866
Roland Levillainccc07a92014-09-16 14:48:16 +0100867bool HInstructionList::FoundBefore(const HInstruction* instruction1,
868 const HInstruction* instruction2) const {
869 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
870 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
871 if (it.Current() == instruction1) {
872 return true;
873 }
874 if (it.Current() == instruction2) {
875 return false;
876 }
877 }
878 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
879 return true;
880}
881
Roland Levillain6c82d402014-10-13 16:10:27 +0100882bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
883 if (other_instruction == this) {
884 // An instruction does not strictly dominate itself.
885 return false;
886 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100887 HBasicBlock* block = GetBlock();
888 HBasicBlock* other_block = other_instruction->GetBlock();
889 if (block != other_block) {
890 return GetBlock()->Dominates(other_instruction->GetBlock());
891 } else {
892 // If both instructions are in the same block, ensure this
893 // instruction comes before `other_instruction`.
894 if (IsPhi()) {
895 if (!other_instruction->IsPhi()) {
896 // Phis appear before non phi-instructions so this instruction
897 // dominates `other_instruction`.
898 return true;
899 } else {
900 // There is no order among phis.
901 LOG(FATAL) << "There is no dominance between phis of a same block.";
902 return false;
903 }
904 } else {
905 // `this` is not a phi.
906 if (other_instruction->IsPhi()) {
907 // Phis appear before non phi-instructions so this instruction
908 // does not dominate `other_instruction`.
909 return false;
910 } else {
911 // Check whether this instruction comes before
912 // `other_instruction` in the instruction list.
913 return block->GetInstructions().FoundBefore(this, other_instruction);
914 }
915 }
916 }
917}
918
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100919void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100920 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000921 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
922 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100923 HInstruction* user = current->GetUser();
924 size_t input_index = current->GetIndex();
925 user->SetRawInputAt(input_index, other);
926 other->AddUseAt(user, input_index);
927 }
928
David Brazdiled596192015-01-23 10:39:45 +0000929 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
930 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931 HEnvironment* user = current->GetUser();
932 size_t input_index = current->GetIndex();
933 user->SetRawEnvAt(input_index, other);
934 other->AddEnvUseAt(user, input_index);
935 }
936
David Brazdiled596192015-01-23 10:39:45 +0000937 uses_.Clear();
938 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100939}
940
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100941void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000942 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100943 SetRawInputAt(index, replacement);
944 replacement->AddUseAt(this, index);
945}
946
Nicolas Geoffray39468442014-09-02 15:17:15 +0100947size_t HInstruction::EnvironmentSize() const {
948 return HasEnvironment() ? environment_->Size() : 0;
949}
950
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100951void HPhi::AddInput(HInstruction* input) {
952 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100953 inputs_.push_back(HUserRecord<HInstruction*>(input));
954 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100955}
956
David Brazdil2d7352b2015-04-20 14:52:42 +0100957void HPhi::RemoveInputAt(size_t index) {
958 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100959 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100960 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100961 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100962 InputRecordAt(i).GetUseNode()->SetIndex(i);
963 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100964}
965
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100966#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000967void H##name::Accept(HGraphVisitor* visitor) { \
968 visitor->Visit##name(this); \
969}
970
971FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
972
973#undef DEFINE_ACCEPT
974
975void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100976 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
977 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000978 if (block != nullptr) {
979 VisitBasicBlock(block);
980 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000981 }
982}
983
Roland Levillain633021e2014-10-01 14:12:25 +0100984void HGraphVisitor::VisitReversePostOrder() {
985 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
986 VisitBasicBlock(it.Current());
987 }
988}
989
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000990void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100991 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100992 it.Current()->Accept(this);
993 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100994 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000995 it.Current()->Accept(this);
996 }
997}
998
Mark Mendelle82549b2015-05-06 10:55:34 -0400999HConstant* HTypeConversion::TryStaticEvaluation() const {
1000 HGraph* graph = GetBlock()->GetGraph();
1001 if (GetInput()->IsIntConstant()) {
1002 int32_t value = GetInput()->AsIntConstant()->GetValue();
1003 switch (GetResultType()) {
1004 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001005 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001006 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001007 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001008 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001009 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001010 default:
1011 return nullptr;
1012 }
1013 } else if (GetInput()->IsLongConstant()) {
1014 int64_t value = GetInput()->AsLongConstant()->GetValue();
1015 switch (GetResultType()) {
1016 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001017 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001018 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001019 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001020 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001021 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001022 default:
1023 return nullptr;
1024 }
1025 } else if (GetInput()->IsFloatConstant()) {
1026 float value = GetInput()->AsFloatConstant()->GetValue();
1027 switch (GetResultType()) {
1028 case Primitive::kPrimInt:
1029 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001030 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001031 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001032 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001033 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001034 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1035 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001036 case Primitive::kPrimLong:
1037 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001038 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001039 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001040 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001041 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001042 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1043 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001044 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001045 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001046 default:
1047 return nullptr;
1048 }
1049 } else if (GetInput()->IsDoubleConstant()) {
1050 double value = GetInput()->AsDoubleConstant()->GetValue();
1051 switch (GetResultType()) {
1052 case Primitive::kPrimInt:
1053 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001054 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001055 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001056 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001057 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001058 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1059 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001060 case Primitive::kPrimLong:
1061 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001062 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001063 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001064 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001065 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001066 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1067 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001068 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001069 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001070 default:
1071 return nullptr;
1072 }
1073 }
1074 return nullptr;
1075}
1076
Roland Levillain9240d6a2014-10-20 16:47:04 +01001077HConstant* HUnaryOperation::TryStaticEvaluation() const {
1078 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001079 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001080 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001081 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001082 }
1083 return nullptr;
1084}
1085
1086HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001087 if (GetLeft()->IsIntConstant()) {
1088 if (GetRight()->IsIntConstant()) {
1089 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1090 } else if (GetRight()->IsLongConstant()) {
1091 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1092 }
1093 } else if (GetLeft()->IsLongConstant()) {
1094 if (GetRight()->IsIntConstant()) {
1095 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1096 } else if (GetRight()->IsLongConstant()) {
1097 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001098 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001099 }
1100 return nullptr;
1101}
Dave Allison20dfc792014-06-16 20:44:29 -07001102
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001103HConstant* HBinaryOperation::GetConstantRight() const {
1104 if (GetRight()->IsConstant()) {
1105 return GetRight()->AsConstant();
1106 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1107 return GetLeft()->AsConstant();
1108 } else {
1109 return nullptr;
1110 }
1111}
1112
1113// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001114// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001115HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1116 HInstruction* most_constant_right = GetConstantRight();
1117 if (most_constant_right == nullptr) {
1118 return nullptr;
1119 } else if (most_constant_right == GetLeft()) {
1120 return GetRight();
1121 } else {
1122 return GetLeft();
1123 }
1124}
1125
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001126bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1127 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001128}
1129
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001130bool HInstruction::Equals(HInstruction* other) const {
1131 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001132 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001133 if (!InstructionDataEquals(other)) return false;
1134 if (GetType() != other->GetType()) return false;
1135 if (InputCount() != other->InputCount()) return false;
1136
1137 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1138 if (InputAt(i) != other->InputAt(i)) return false;
1139 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001140 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001141 return true;
1142}
1143
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001144std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1145#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1146 switch (rhs) {
1147 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1148 default:
1149 os << "Unknown instruction kind " << static_cast<int>(rhs);
1150 break;
1151 }
1152#undef DECLARE_CASE
1153 return os;
1154}
1155
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001156void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001157 next_->previous_ = previous_;
1158 if (previous_ != nullptr) {
1159 previous_->next_ = next_;
1160 }
1161 if (block_->instructions_.first_instruction_ == this) {
1162 block_->instructions_.first_instruction_ = next_;
1163 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001164 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001165
1166 previous_ = cursor->previous_;
1167 if (previous_ != nullptr) {
1168 previous_->next_ = this;
1169 }
1170 next_ = cursor;
1171 cursor->previous_ = this;
1172 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001173
1174 if (block_->instructions_.first_instruction_ == cursor) {
1175 block_->instructions_.first_instruction_ = this;
1176 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001177}
1178
David Brazdilfc6a86a2015-06-26 10:33:45 +00001179HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001180 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001181 DCHECK_EQ(cursor->GetBlock(), this);
1182
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001183 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1184 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001185 new_block->instructions_.first_instruction_ = cursor;
1186 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1187 instructions_.last_instruction_ = cursor->previous_;
1188 if (cursor->previous_ == nullptr) {
1189 instructions_.first_instruction_ = nullptr;
1190 } else {
1191 cursor->previous_->next_ = nullptr;
1192 cursor->previous_ = nullptr;
1193 }
1194
1195 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001196 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001197
Vladimir Marko60584552015-09-03 13:35:12 +00001198 for (HBasicBlock* successor : GetSuccessors()) {
1199 new_block->successors_.push_back(successor);
1200 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001201 }
Vladimir Marko60584552015-09-03 13:35:12 +00001202 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001203 AddSuccessor(new_block);
1204
David Brazdil56e1acc2015-06-30 15:41:36 +01001205 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001206 return new_block;
1207}
1208
David Brazdild7558da2015-09-22 13:04:14 +01001209HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001210 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001211 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1212
1213 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1214
1215 for (HBasicBlock* predecessor : GetPredecessors()) {
1216 new_block->predecessors_.push_back(predecessor);
1217 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1218 }
1219 predecessors_.clear();
1220 AddPredecessor(new_block);
1221
1222 GetGraph()->AddBlock(new_block);
1223 return new_block;
1224}
1225
David Brazdil9bc43612015-11-05 21:25:24 +00001226HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1227 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1228 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1229
1230 HInstruction* first_insn = GetFirstInstruction();
1231 HInstruction* split_before = nullptr;
1232
1233 if (first_insn != nullptr && first_insn->IsLoadException()) {
1234 // Catch block starts with a LoadException. Split the block after
1235 // the StoreLocal and ClearException which must come after the load.
1236 DCHECK(first_insn->GetNext()->IsStoreLocal());
1237 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1238 split_before = first_insn->GetNext()->GetNext()->GetNext();
1239 } else {
1240 // Catch block does not load the exception. Split at the beginning
1241 // to create an empty catch block.
1242 split_before = first_insn;
1243 }
1244
1245 if (split_before == nullptr) {
1246 // Catch block has no instructions after the split point (must be dead).
1247 // Do not split it but rather signal error by returning nullptr.
1248 return nullptr;
1249 } else {
1250 return SplitBefore(split_before);
1251 }
1252}
1253
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001254HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1255 DCHECK(!cursor->IsControlFlow());
1256 DCHECK_NE(instructions_.last_instruction_, cursor);
1257 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001258
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001259 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1260 new_block->instructions_.first_instruction_ = cursor->GetNext();
1261 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1262 cursor->next_->previous_ = nullptr;
1263 cursor->next_ = nullptr;
1264 instructions_.last_instruction_ = cursor;
1265
1266 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001267 for (HBasicBlock* successor : GetSuccessors()) {
1268 new_block->successors_.push_back(successor);
1269 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001270 }
Vladimir Marko60584552015-09-03 13:35:12 +00001271 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001272
Vladimir Marko60584552015-09-03 13:35:12 +00001273 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001274 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001275 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001276 }
Vladimir Marko60584552015-09-03 13:35:12 +00001277 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001278 return new_block;
1279}
1280
David Brazdilec16f792015-08-19 15:04:01 +01001281const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001282 if (EndsWithTryBoundary()) {
1283 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1284 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001285 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001286 return try_boundary;
1287 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001288 DCHECK(IsTryBlock());
1289 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001290 return nullptr;
1291 }
David Brazdilec16f792015-08-19 15:04:01 +01001292 } else if (IsTryBlock()) {
1293 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001294 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001295 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001296 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001297}
1298
David Brazdild7558da2015-09-22 13:04:14 +01001299bool HBasicBlock::HasThrowingInstructions() const {
1300 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1301 if (it.Current()->CanThrow()) {
1302 return true;
1303 }
1304 }
1305 return false;
1306}
1307
David Brazdilfc6a86a2015-06-26 10:33:45 +00001308static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1309 return block.GetPhis().IsEmpty()
1310 && !block.GetInstructions().IsEmpty()
1311 && block.GetFirstInstruction() == block.GetLastInstruction();
1312}
1313
David Brazdil46e2a392015-03-16 17:31:52 +00001314bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001315 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1316}
1317
1318bool HBasicBlock::IsSingleTryBoundary() const {
1319 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001320}
1321
David Brazdil8d5b8b22015-03-24 10:51:52 +00001322bool HBasicBlock::EndsWithControlFlowInstruction() const {
1323 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1324}
1325
David Brazdilb2bd1c52015-03-25 11:17:37 +00001326bool HBasicBlock::EndsWithIf() const {
1327 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1328}
1329
David Brazdilffee3d32015-07-06 11:48:53 +01001330bool HBasicBlock::EndsWithTryBoundary() const {
1331 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1332}
1333
David Brazdilb2bd1c52015-03-25 11:17:37 +00001334bool HBasicBlock::HasSinglePhi() const {
1335 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1336}
1337
David Brazdilffee3d32015-07-06 11:48:53 +01001338bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001339 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001340 return false;
1341 }
1342
David Brazdilb618ade2015-07-29 10:31:29 +01001343 // Exception handlers need to be stored in the same order.
1344 for (HExceptionHandlerIterator it1(*this), it2(other);
1345 !it1.Done();
1346 it1.Advance(), it2.Advance()) {
1347 DCHECK(!it2.Done());
1348 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001349 return false;
1350 }
1351 }
1352 return true;
1353}
1354
David Brazdil2d7352b2015-04-20 14:52:42 +01001355size_t HInstructionList::CountSize() const {
1356 size_t size = 0;
1357 HInstruction* current = first_instruction_;
1358 for (; current != nullptr; current = current->GetNext()) {
1359 size++;
1360 }
1361 return size;
1362}
1363
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001364void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1365 for (HInstruction* current = first_instruction_;
1366 current != nullptr;
1367 current = current->GetNext()) {
1368 current->SetBlock(block);
1369 }
1370}
1371
1372void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1373 DCHECK(Contains(cursor));
1374 if (!instruction_list.IsEmpty()) {
1375 if (cursor == last_instruction_) {
1376 last_instruction_ = instruction_list.last_instruction_;
1377 } else {
1378 cursor->next_->previous_ = instruction_list.last_instruction_;
1379 }
1380 instruction_list.last_instruction_->next_ = cursor->next_;
1381 cursor->next_ = instruction_list.first_instruction_;
1382 instruction_list.first_instruction_->previous_ = cursor;
1383 }
1384}
1385
1386void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001387 if (IsEmpty()) {
1388 first_instruction_ = instruction_list.first_instruction_;
1389 last_instruction_ = instruction_list.last_instruction_;
1390 } else {
1391 AddAfter(last_instruction_, instruction_list);
1392 }
1393}
1394
David Brazdil2d7352b2015-04-20 14:52:42 +01001395void HBasicBlock::DisconnectAndDelete() {
1396 // Dominators must be removed after all the blocks they dominate. This way
1397 // a loop header is removed last, a requirement for correct loop information
1398 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001399 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001400
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001401 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001402 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1403 HLoopInformation* loop_info = it.Current();
1404 loop_info->Remove(this);
1405 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001406 // If this was the last back edge of the loop, we deliberately leave the
1407 // loop in an inconsistent state and will fail SSAChecker unless the
1408 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001409 loop_info->RemoveBackEdge(this);
1410 }
1411 }
1412
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001413 // (2) Disconnect the block from its predecessors and update their
1414 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001415 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001416 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001417 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1418 // This block is the only normal-flow successor of the TryBoundary which
1419 // makes `predecessor` dead. Since DCE removes blocks in post order,
1420 // exception handlers of this TryBoundary were already visited and any
1421 // remaining handlers therefore must be live. We remove `predecessor` from
1422 // their list of predecessors.
1423 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1424 while (predecessor->GetSuccessors().size() > 1) {
1425 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1426 DCHECK(handler->IsCatchBlock());
1427 predecessor->RemoveSuccessor(handler);
1428 handler->RemovePredecessor(predecessor);
1429 }
1430 }
1431
David Brazdil2d7352b2015-04-20 14:52:42 +01001432 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001433 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1434 if (num_pred_successors == 1u) {
1435 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001436 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1437 // successor. Replace those with a HGoto.
1438 DCHECK(last_instruction->IsIf() ||
1439 last_instruction->IsPackedSwitch() ||
1440 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001441 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001442 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001443 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001444 // The predecessor has no remaining successors and therefore must be dead.
1445 // We deliberately leave it without a control-flow instruction so that the
1446 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001447 predecessor->RemoveInstruction(last_instruction);
1448 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001449 // There are multiple successors left. The removed block might be a successor
1450 // of a PackedSwitch which will be completely removed (perhaps replaced with
1451 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1452 // case, leave `last_instruction` as is for now.
1453 DCHECK(last_instruction->IsPackedSwitch() ||
1454 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001455 }
David Brazdil46e2a392015-03-16 17:31:52 +00001456 }
Vladimir Marko60584552015-09-03 13:35:12 +00001457 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001458
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001459 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001460 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001461 // Delete this block from the list of predecessors.
1462 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001463 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001464
1465 // Check that `successor` has other predecessors, otherwise `this` is the
1466 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001467 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001468
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001469 // Remove this block's entries in the successor's phis. Skip exceptional
1470 // successors because catch phi inputs do not correspond to predecessor
1471 // blocks but throwing instructions. Their inputs will be updated in step (4).
1472 if (!successor->IsCatchBlock()) {
1473 if (successor->predecessors_.size() == 1u) {
1474 // The successor has just one predecessor left. Replace phis with the only
1475 // remaining input.
1476 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1477 HPhi* phi = phi_it.Current()->AsPhi();
1478 phi->ReplaceWith(phi->InputAt(1 - this_index));
1479 successor->RemovePhi(phi);
1480 }
1481 } else {
1482 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1483 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1484 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001485 }
1486 }
1487 }
Vladimir Marko60584552015-09-03 13:35:12 +00001488 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001489
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001490 // (4) Remove instructions and phis. Instructions should have no remaining uses
1491 // except in catch phis. If an instruction is used by a catch phi at `index`,
1492 // remove `index`-th input of all phis in the catch block since they are
1493 // guaranteed dead. Note that we may miss dead inputs this way but the
1494 // graph will always remain consistent.
1495 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1496 HInstruction* insn = it.Current();
1497 while (insn->HasUses()) {
1498 DCHECK(IsTryBlock());
1499 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1500 size_t use_index = use->GetIndex();
1501 HBasicBlock* user_block = use->GetUser()->GetBlock();
1502 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1503 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1504 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1505 }
1506 }
1507
1508 RemoveInstruction(insn);
1509 }
1510 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1511 RemovePhi(it.Current()->AsPhi());
1512 }
1513
David Brazdil2d7352b2015-04-20 14:52:42 +01001514 // Disconnect from the dominator.
1515 dominator_->RemoveDominatedBlock(this);
1516 SetDominator(nullptr);
1517
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001518 // Delete from the graph, update reverse post order.
1519 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001520 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001521}
1522
1523void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001524 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001525 DCHECK(ContainsElement(dominated_blocks_, other));
1526 DCHECK_EQ(GetSingleSuccessor(), other);
1527 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001528 DCHECK(other->GetPhis().IsEmpty());
1529
David Brazdil2d7352b2015-04-20 14:52:42 +01001530 // Move instructions from `other` to `this`.
1531 DCHECK(EndsWithControlFlowInstruction());
1532 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001533 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001534 other->instructions_.SetBlockOfInstructions(this);
1535 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001536
David Brazdil2d7352b2015-04-20 14:52:42 +01001537 // Remove `other` from the loops it is included in.
1538 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1539 HLoopInformation* loop_info = it.Current();
1540 loop_info->Remove(other);
1541 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001542 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001543 }
1544 }
1545
1546 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001547 successors_.clear();
1548 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001549 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001550 successor->ReplacePredecessor(other, this);
1551 }
1552
David Brazdil2d7352b2015-04-20 14:52:42 +01001553 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001554 RemoveDominatedBlock(other);
1555 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1556 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001557 dominated->SetDominator(this);
1558 }
Vladimir Marko60584552015-09-03 13:35:12 +00001559 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001560 other->dominator_ = nullptr;
1561
1562 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001563 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001564
1565 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001566 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001567 other->SetGraph(nullptr);
1568}
1569
1570void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1571 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001572 DCHECK(GetDominatedBlocks().empty());
1573 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001574 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001575 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001576 DCHECK(other->GetPhis().IsEmpty());
1577 DCHECK(!other->IsInLoop());
1578
1579 // Move instructions from `other` to `this`.
1580 instructions_.Add(other->GetInstructions());
1581 other->instructions_.SetBlockOfInstructions(this);
1582
1583 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001584 successors_.clear();
1585 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001586 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001587 successor->ReplacePredecessor(other, this);
1588 }
1589
1590 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001591 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1592 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001593 dominated->SetDominator(this);
1594 }
Vladimir Marko60584552015-09-03 13:35:12 +00001595 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001596 other->dominator_ = nullptr;
1597 other->graph_ = nullptr;
1598}
1599
1600void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001601 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001602 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001603 predecessor->ReplaceSuccessor(this, other);
1604 }
Vladimir Marko60584552015-09-03 13:35:12 +00001605 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001606 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001607 successor->ReplacePredecessor(this, other);
1608 }
Vladimir Marko60584552015-09-03 13:35:12 +00001609 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1610 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001611 }
1612 GetDominator()->ReplaceDominatedBlock(this, other);
1613 other->SetDominator(GetDominator());
1614 dominator_ = nullptr;
1615 graph_ = nullptr;
1616}
1617
1618// Create space in `blocks` for adding `number_of_new_blocks` entries
1619// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001620static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001621 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001622 size_t after) {
1623 DCHECK_LT(after, blocks->size());
1624 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001625 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001626 blocks->resize(new_size);
1627 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001628}
1629
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001630void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001631 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001632 DCHECK(block->GetSuccessors().empty());
1633 DCHECK(block->GetPredecessors().empty());
1634 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001635 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001636 DCHECK(block->GetInstructions().IsEmpty());
1637 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001638
David Brazdilc7af85d2015-05-26 12:05:55 +01001639 if (block->IsExitBlock()) {
1640 exit_block_ = nullptr;
1641 }
1642
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001643 RemoveElement(reverse_post_order_, block);
1644 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001645}
1646
Calin Juravle2e768302015-07-28 14:41:11 +00001647HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001648 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001649 // Update the environments in this graph to have the invoke's environment
1650 // as parent.
1651 {
1652 HReversePostOrderIterator it(*this);
1653 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1654 for (; !it.Done(); it.Advance()) {
1655 HBasicBlock* block = it.Current();
1656 for (HInstructionIterator instr_it(block->GetInstructions());
1657 !instr_it.Done();
1658 instr_it.Advance()) {
1659 HInstruction* current = instr_it.Current();
1660 if (current->NeedsEnvironment()) {
1661 current->GetEnvironment()->SetAndCopyParentChain(
1662 outer_graph->GetArena(), invoke->GetEnvironment());
1663 }
1664 }
1665 }
1666 }
1667 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1668 if (HasBoundsChecks()) {
1669 outer_graph->SetHasBoundsChecks(true);
1670 }
1671
Calin Juravle2e768302015-07-28 14:41:11 +00001672 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001673 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001674 // Simple case of an entry block, a body block, and an exit block.
1675 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001676 HBasicBlock* body = GetBlocks()[1];
1677 DCHECK(GetBlocks()[0]->IsEntryBlock());
1678 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001679 DCHECK(!body->IsExitBlock());
1680 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001681
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001682 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1683 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001684
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001685 // Replace the invoke with the return value of the inlined graph.
1686 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001687 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001688 } else {
1689 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001690 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001691
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001692 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001693 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001694 // Need to inline multiple blocks. We split `invoke`'s block
1695 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001696 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001697 // with the second half.
1698 ArenaAllocator* allocator = outer_graph->GetArena();
1699 HBasicBlock* at = invoke->GetBlock();
1700 HBasicBlock* to = at->SplitAfter(invoke);
1701
Vladimir Markoec7802a2015-10-01 20:57:57 +01001702 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001703 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001704 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001705 exit_block_->ReplaceWith(to);
1706
1707 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001708 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001709 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001710 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001711 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001712 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001713 if (!returns_void) {
1714 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001715 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001716 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001717 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001718 } else {
1719 if (!returns_void) {
1720 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001721 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001722 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001723 to->AddPhi(return_value->AsPhi());
1724 }
Vladimir Marko60584552015-09-03 13:35:12 +00001725 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001726 HInstruction* last = predecessor->GetLastInstruction();
1727 if (!returns_void) {
1728 return_value->AsPhi()->AddInput(last->InputAt(0));
1729 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001730 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001731 predecessor->RemoveInstruction(last);
1732 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001733 }
1734
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001735 // Update the meta information surrounding blocks:
1736 // (1) the graph they are now in,
1737 // (2) the reverse post order of that graph,
David Brazdil95177982015-10-30 12:56:58 -05001738 // (3) the potential loop information they are now in,
1739 // (4) try block membership.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001740
1741 // We don't add the entry block, the exit block, and the first block, which
1742 // has been merged with `at`.
1743 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1744
1745 // We add the `to` block.
1746 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001747 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001748 + kNumberOfNewBlocksInCaller;
1749
1750 // Find the location of `at` in the outer graph's reverse post order. The new
1751 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001752 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001753 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1754
David Brazdil95177982015-10-30 12:56:58 -05001755 HLoopInformation* loop_info = at->GetLoopInformation();
1756 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1757 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1758
1759 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1760 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001761 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1762 HBasicBlock* current = it.Current();
1763 if (current != exit_block_ && current != entry_block_ && current != first) {
1764 DCHECK(!current->IsInLoop());
David Brazdil95177982015-10-30 12:56:58 -05001765 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001766 DCHECK(current->GetGraph() == this);
1767 current->SetGraph(outer_graph);
1768 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001769 outer_graph->reverse_post_order_[++index_of_at] = current;
David Brazdil95177982015-10-30 12:56:58 -05001770 if (loop_info != nullptr) {
1771 current->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001772 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1773 loop_it.Current()->Add(current);
1774 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001775 }
David Brazdil95177982015-10-30 12:56:58 -05001776 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001777 }
1778 }
1779
David Brazdil95177982015-10-30 12:56:58 -05001780 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001781 to->SetGraph(outer_graph);
1782 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001783 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001784 if (loop_info != nullptr) {
1785 to->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001786 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1787 loop_it.Current()->Add(to);
1788 }
David Brazdil95177982015-10-30 12:56:58 -05001789 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001790 // Only `to` can become a back edge, as the inlined blocks
1791 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001792 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001793 }
1794 }
David Brazdil95177982015-10-30 12:56:58 -05001795 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001796 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001797
David Brazdil05144f42015-04-16 15:18:00 +01001798 // Update the next instruction id of the outer graph, so that instructions
1799 // added later get bigger ids than those in the inner graph.
1800 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1801
1802 // Walk over the entry block and:
1803 // - Move constants from the entry block to the outer_graph's entry block,
1804 // - Replace HParameterValue instructions with their real value.
1805 // - Remove suspend checks, that hold an environment.
1806 // We must do this after the other blocks have been inlined, otherwise ids of
1807 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001808 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001809 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1810 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001811 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001812 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001813 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001814 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001815 replacement = outer_graph->GetIntConstant(
1816 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001817 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001818 replacement = outer_graph->GetLongConstant(
1819 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001820 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001821 replacement = outer_graph->GetFloatConstant(
1822 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001823 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001824 replacement = outer_graph->GetDoubleConstant(
1825 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001826 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001827 if (kIsDebugBuild
1828 && invoke->IsInvokeStaticOrDirect()
1829 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1830 // Ensure we do not use the last input of `invoke`, as it
1831 // contains a clinit check which is not an actual argument.
1832 size_t last_input_index = invoke->InputCount() - 1;
1833 DCHECK(parameter_index != last_input_index);
1834 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001835 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001836 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001837 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01001838 } else {
1839 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1840 entry_block_->RemoveInstruction(current);
1841 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001842 if (replacement != nullptr) {
1843 current->ReplaceWith(replacement);
1844 // If the current is the return value then we need to update the latter.
1845 if (current == return_value) {
1846 DCHECK_EQ(entry_block_, return_value->GetBlock());
1847 return_value = replacement;
1848 }
1849 }
1850 }
1851
1852 if (return_value != nullptr) {
1853 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01001854 }
1855
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001856 // Finally remove the invoke from the caller.
1857 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001858
1859 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001860}
1861
Mingyao Yang3584bce2015-05-19 16:01:59 -07001862/*
1863 * Loop will be transformed to:
1864 * old_pre_header
1865 * |
1866 * if_block
1867 * / \
1868 * dummy_block deopt_block
1869 * \ /
1870 * new_pre_header
1871 * |
1872 * header
1873 */
1874void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1875 DCHECK(header->IsLoopHeader());
1876 HBasicBlock* pre_header = header->GetDominator();
1877
1878 // Need this to avoid critical edge.
1879 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1880 // Need this to avoid critical edge.
1881 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1882 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1883 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1884 AddBlock(if_block);
1885 AddBlock(dummy_block);
1886 AddBlock(deopt_block);
1887 AddBlock(new_pre_header);
1888
1889 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001890 pre_header->successors_.clear();
1891 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001892
1893 pre_header->AddSuccessor(if_block);
1894 if_block->AddSuccessor(dummy_block); // True successor
1895 if_block->AddSuccessor(deopt_block); // False successor
1896 dummy_block->AddSuccessor(new_pre_header);
1897 deopt_block->AddSuccessor(new_pre_header);
1898
Vladimir Marko60584552015-09-03 13:35:12 +00001899 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001900 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001901 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001902 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001903 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001904 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001905 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001906 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001907 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001908 header->SetDominator(new_pre_header);
1909
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001910 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001911 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001912 reverse_post_order_[index_of_header++] = if_block;
1913 reverse_post_order_[index_of_header++] = dummy_block;
1914 reverse_post_order_[index_of_header++] = deopt_block;
1915 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001916
1917 HLoopInformation* info = pre_header->GetLoopInformation();
1918 if (info != nullptr) {
1919 if_block->SetLoopInformation(info);
1920 dummy_block->SetLoopInformation(info);
1921 deopt_block->SetLoopInformation(info);
1922 new_pre_header->SetLoopInformation(info);
1923 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1924 !loop_it.Done();
1925 loop_it.Advance()) {
1926 loop_it.Current()->Add(if_block);
1927 loop_it.Current()->Add(dummy_block);
1928 loop_it.Current()->Add(deopt_block);
1929 loop_it.Current()->Add(new_pre_header);
1930 }
1931 }
1932}
1933
Calin Juravle2e768302015-07-28 14:41:11 +00001934void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1935 if (kIsDebugBuild) {
1936 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1937 ScopedObjectAccess soa(Thread::Current());
1938 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1939 if (IsBoundType()) {
1940 // Having the test here spares us from making the method virtual just for
1941 // the sake of a DCHECK.
1942 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1943 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1944 << " upper_bound_rti: " << upper_bound_rti
1945 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001946 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001947 }
1948 }
1949 reference_type_info_ = rti;
1950}
1951
1952ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1953
1954ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1955 : type_handle_(type_handle), is_exact_(is_exact) {
1956 if (kIsDebugBuild) {
1957 ScopedObjectAccess soa(Thread::Current());
1958 DCHECK(IsValidHandle(type_handle));
1959 }
1960}
1961
Calin Juravleacf735c2015-02-12 15:25:22 +00001962std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1963 ScopedObjectAccess soa(Thread::Current());
1964 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001965 << " is_valid=" << rhs.IsValid()
1966 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001967 << " is_exact=" << rhs.IsExact()
1968 << " ]";
1969 return os;
1970}
1971
Mark Mendellc4701932015-04-10 13:18:51 -04001972bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1973 // For now, assume that instructions in different blocks may use the
1974 // environment.
1975 // TODO: Use the control flow to decide if this is true.
1976 if (GetBlock() != other->GetBlock()) {
1977 return true;
1978 }
1979
1980 // We know that we are in the same block. Walk from 'this' to 'other',
1981 // checking to see if there is any instruction with an environment.
1982 HInstruction* current = this;
1983 for (; current != other && current != nullptr; current = current->GetNext()) {
1984 // This is a conservative check, as the instruction result may not be in
1985 // the referenced environment.
1986 if (current->HasEnvironment()) {
1987 return true;
1988 }
1989 }
1990
1991 // We should have been called with 'this' before 'other' in the block.
1992 // Just confirm this.
1993 DCHECK(current != nullptr);
1994 return false;
1995}
1996
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001997void HInvoke::SetIntrinsic(Intrinsics intrinsic,
1998 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache) {
1999 intrinsic_ = intrinsic;
2000 IntrinsicOptimizations opt(this);
2001 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2002 opt.SetDoesNotNeedDexCache();
2003 opt.SetDoesNotNeedEnvironment();
2004 }
2005}
2006
2007bool HInvoke::NeedsEnvironment() const {
2008 if (!IsIntrinsic()) {
2009 return true;
2010 }
2011 IntrinsicOptimizations opt(*this);
2012 return !opt.GetDoesNotNeedEnvironment();
2013}
2014
Vladimir Markodc151b22015-10-15 18:02:30 +01002015bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2016 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002017 return false;
2018 }
2019 if (!IsIntrinsic()) {
2020 return true;
2021 }
2022 IntrinsicOptimizations opt(*this);
2023 return !opt.GetDoesNotNeedDexCache();
2024}
2025
Vladimir Markob554b5a2015-11-06 12:57:55 +00002026void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2027 RemoveAsUserOfInput(index);
2028 inputs_.erase(inputs_.begin() + index);
2029 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2030 for (size_t i = index, e = InputCount(); i < e; ++i) {
2031 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2032 InputRecordAt(i).GetUseNode()->SetIndex(i);
2033 }
2034}
2035
Mark Mendellc4701932015-04-10 13:18:51 -04002036void HInstruction::RemoveEnvironmentUsers() {
2037 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2038 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2039 HEnvironment* user = user_node->GetUser();
2040 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2041 }
2042 env_uses_.Clear();
2043}
2044
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002045} // namespace art