blob: 1e6bf07e42abb7f22a1fcdb1a6a0c7a5679a9b2e [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 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010059 ArenaVector<size_t> successors_visited(blocks_.size(),
60 0u,
61 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010062 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010063 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 constexpr size_t kDefaultWorklistSize = 8;
65 worklist.reserve(kDefaultWorklistSize);
66 visited->SetBit(entry_block_->GetBlockId());
67 visiting.SetBit(entry_block_->GetBlockId());
68 worklist.push_back(entry_block_);
69
70 while (!worklist.empty()) {
71 HBasicBlock* current = worklist.back();
72 uint32_t current_id = current->GetBlockId();
73 if (successors_visited[current_id] == current->GetSuccessors().size()) {
74 visiting.ClearBit(current_id);
75 worklist.pop_back();
76 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010077 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
78 uint32_t successor_id = successor->GetBlockId();
79 if (visiting.IsBitSet(successor_id)) {
80 DCHECK(ContainsElement(worklist, successor));
81 successor->AddBackEdge(current);
82 } else if (!visited->IsBitSet(successor_id)) {
83 visited->SetBit(successor_id);
84 visiting.SetBit(successor_id);
85 worklist.push_back(successor);
86 }
87 }
88 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000089}
90
Vladimir Markocac5a7e2016-02-22 10:39:50 +000091static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010092 for (HEnvironment* environment = instruction->GetEnvironment();
93 environment != nullptr;
94 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000095 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000096 if (environment->GetInstructionAt(i) != nullptr) {
97 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 }
99 }
100 }
101}
102
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000103static void RemoveAsUser(HInstruction* instruction) {
104 for (size_t i = 0; i < instruction->InputCount(); i++) {
105 instruction->RemoveAsUserOfInput(i);
106 }
107
108 RemoveEnvironmentUses(instruction);
109}
110
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100112 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000113 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100114 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000115 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100116 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
118 RemoveAsUser(it.Current());
119 }
120 }
121 }
122}
123
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100124void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100125 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000126 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100127 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000128 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100129 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000130 for (HBasicBlock* successor : block->GetSuccessors()) {
131 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000132 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100133 // Remove the block from the list of blocks, so that further analyses
134 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100135 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600136 if (block->IsExitBlock()) {
137 SetExitBlock(nullptr);
138 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000139 // Mark the block as removed. This is used by the HGraphBuilder to discard
140 // the block as a branch target.
141 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000142 }
143 }
144}
145
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000146GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000147 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148
David Brazdil86ea7ee2016-02-16 09:26:07 +0000149 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 FindBackEdges(&visited);
151
David Brazdil86ea7ee2016-02-16 09:26:07 +0000152 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000153 // the initial DFS as users from other instructions, so that
154 // users can be safely removed before uses later.
155 RemoveInstructionsAsUsersFromDeadBlocks(visited);
156
David Brazdil86ea7ee2016-02-16 09:26:07 +0000157 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000158 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // predecessors list of live blocks.
160 RemoveDeadBlocks(visited);
161
David Brazdil86ea7ee2016-02-16 09:26:07 +0000162 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100163 // dominators and the reverse post order.
164 SimplifyCFG();
165
David Brazdil86ea7ee2016-02-16 09:26:07 +0000166 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100167 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168
David Brazdil86ea7ee2016-02-16 09:26:07 +0000169 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000170 // set the loop information on each block.
171 GraphAnalysisResult result = AnalyzeLoops();
172 if (result != kAnalysisSuccess) {
173 return result;
174 }
175
David Brazdil86ea7ee2016-02-16 09:26:07 +0000176 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000177 // which needs the information to build catch block phis from values of
178 // locals at throwing instructions inside try blocks.
179 ComputeTryBlockInformation();
180
181 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100182}
183
184void HGraph::ClearDominanceInformation() {
185 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
186 it.Current()->ClearDominanceInformation();
187 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100189}
190
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000191void HGraph::ClearLoopInformation() {
192 SetHasIrreducibleLoops(false);
193 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000194 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 }
196}
197
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000199 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100200 dominator_ = nullptr;
201}
202
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000203HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
204 HInstruction* instruction = GetFirstInstruction();
205 while (instruction->IsParallelMove()) {
206 instruction = instruction->GetNext();
207 }
208 return instruction;
209}
210
David Brazdil3f4a5222016-05-06 12:46:21 +0100211static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
212 DCHECK(ContainsElement(block->GetSuccessors(), successor));
213
214 HBasicBlock* old_dominator = successor->GetDominator();
215 HBasicBlock* new_dominator =
216 (old_dominator == nullptr) ? block
217 : CommonDominator::ForPair(old_dominator, block);
218
219 if (old_dominator == new_dominator) {
220 return false;
221 } else {
222 successor->SetDominator(new_dominator);
223 return true;
224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100228 DCHECK(reverse_post_order_.empty());
229 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100230 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100231
232 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100233 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100234 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100235 ArenaVector<size_t> successors_visited(blocks_.size(),
236 0u,
237 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100238 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100239 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100240 constexpr size_t kDefaultWorklistSize = 8;
241 worklist.reserve(kDefaultWorklistSize);
242 worklist.push_back(entry_block_);
243
244 while (!worklist.empty()) {
245 HBasicBlock* current = worklist.back();
246 uint32_t current_id = current->GetBlockId();
247 if (successors_visited[current_id] == current->GetSuccessors().size()) {
248 worklist.pop_back();
249 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100250 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100251 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100252
253 // Once all the forward edges have been visited, we know the immediate
254 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100255 if (++visits[successor->GetBlockId()] ==
256 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100257 reverse_post_order_.push_back(successor);
258 worklist.push_back(successor);
259 }
260 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000261 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000262
David Brazdil3f4a5222016-05-06 12:46:21 +0100263 // Check if the graph has back edges not dominated by their respective headers.
264 // If so, we need to update the dominators of those headers and recursively of
265 // their successors. We do that with a fix-point iteration over all blocks.
266 // The algorithm is guaranteed to terminate because it loops only if the sum
267 // of all dominator chains has decreased in the current iteration.
268 bool must_run_fix_point = false;
269 for (HBasicBlock* block : blocks_) {
270 if (block != nullptr &&
271 block->IsLoopHeader() &&
272 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
273 must_run_fix_point = true;
274 break;
275 }
276 }
277 if (must_run_fix_point) {
278 bool update_occurred = true;
279 while (update_occurred) {
280 update_occurred = false;
281 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
282 HBasicBlock* block = it.Current();
283 for (HBasicBlock* successor : block->GetSuccessors()) {
284 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
285 }
286 }
287 }
288 }
289
290 // Make sure that there are no remaining blocks whose dominator information
291 // needs to be updated.
292 if (kIsDebugBuild) {
293 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
294 HBasicBlock* block = it.Current();
295 for (HBasicBlock* successor : block->GetSuccessors()) {
296 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
297 }
298 }
299 }
300
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000302 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000303 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
304 HBasicBlock* block = it.Current();
305 if (!block->IsEntryBlock()) {
306 block->GetDominator()->AddDominatedBlock(block);
307 }
308 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000309}
310
David Brazdilfc6a86a2015-06-26 10:33:45 +0000311HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000312 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
313 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000314 // Use `InsertBetween` to ensure the predecessor index and successor index of
315 // `block` and `successor` are preserved.
316 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000317 return new_block;
318}
319
320void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
321 // Insert a new node between `block` and `successor` to split the
322 // critical edge.
323 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600324 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 if (successor->IsLoopHeader()) {
326 // If we split at a back edge boundary, make the new block the back edge.
327 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000328 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100329 info->RemoveBackEdge(block);
330 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100331 }
332 }
333}
334
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100335void HGraph::SimplifyLoop(HBasicBlock* header) {
336 HLoopInformation* info = header->GetLoopInformation();
337
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100338 // Make sure the loop has only one pre header. This simplifies SSA building by having
339 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000340 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
341 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000342 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000343 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100344 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100345 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600346 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100347
Vladimir Marko60584552015-09-03 13:35:12 +0000348 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100349 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100350 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100351 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100352 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100353 }
354 }
355 pre_header->AddSuccessor(header);
356 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100357
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100358 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100359 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
360 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000361 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100362 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100363 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000364 header->predecessors_[pred] = to_swap;
365 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100366 break;
367 }
368 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100369 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100370
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100371 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000372 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
373 // Called from DeadBlockElimination. Update SuspendCheck pointer.
374 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100375 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100376}
377
David Brazdilffee3d32015-07-06 11:48:53 +0100378void HGraph::ComputeTryBlockInformation() {
379 // Iterate in reverse post order to propagate try membership information from
380 // predecessors to their successors.
381 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
382 HBasicBlock* block = it.Current();
383 if (block->IsEntryBlock() || block->IsCatchBlock()) {
384 // Catch blocks after simplification have only exceptional predecessors
385 // and hence are never in tries.
386 continue;
387 }
388
389 // Infer try membership from the first predecessor. Having simplified loops,
390 // the first predecessor can never be a back edge and therefore it must have
391 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100392 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100393 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100394 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000395 if (try_entry != nullptr &&
396 (block->GetTryCatchInformation() == nullptr ||
397 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
398 // We are either setting try block membership for the first time or it
399 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100400 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
401 }
David Brazdilffee3d32015-07-06 11:48:53 +0100402 }
403}
404
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100405void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000406// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100407 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000408 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100409 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
410 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
411 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
412 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100413 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000414 if (block->GetSuccessors().size() > 1) {
415 // Only split normal-flow edges. We cannot split exceptional edges as they
416 // are synthesized (approximate real control flow), and we do not need to
417 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000418 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
419 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
420 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100421 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000422 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000423 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
424 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000425 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000426 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000428 // SplitCriticalEdge could have invalidated the `normal_successors`
429 // ArrayRef. We must re-acquire it.
430 normal_successors = block->GetNormalSuccessors();
431 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
432 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100433 }
434 }
435 }
436 if (block->IsLoopHeader()) {
437 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000438 } else if (!block->IsEntryBlock() &&
439 block->GetFirstInstruction() != nullptr &&
440 block->GetFirstInstruction()->IsSuspendCheck()) {
441 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000442 // a loop got dismantled. Just remove the suspend check.
443 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100444 }
445 }
446}
447
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000448GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100449 // Order does not matter.
450 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
451 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100452 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100453 if (block->IsCatchBlock()) {
454 // TODO: Dealing with exceptional back edges could be tricky because
455 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000456 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100457 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000458 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100459 }
460 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000461 return kAnalysisSuccess;
462}
463
464void HLoopInformation::Dump(std::ostream& os) {
465 os << "header: " << header_->GetBlockId() << std::endl;
466 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
467 for (HBasicBlock* block : back_edges_) {
468 os << "back edge: " << block->GetBlockId() << std::endl;
469 }
470 for (HBasicBlock* block : header_->GetPredecessors()) {
471 os << "predecessor: " << block->GetBlockId() << std::endl;
472 }
473 for (uint32_t idx : blocks_.Indexes()) {
474 os << " in loop: " << idx << std::endl;
475 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100476}
477
David Brazdil8d5b8b22015-03-24 10:51:52 +0000478void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000479 // New constants are inserted before the SuspendCheck at the bottom of the
480 // entry block. Note that this method can be called from the graph builder and
481 // the entry block therefore may not end with SuspendCheck->Goto yet.
482 HInstruction* insert_before = nullptr;
483
484 HInstruction* gota = entry_block_->GetLastInstruction();
485 if (gota != nullptr && gota->IsGoto()) {
486 HInstruction* suspend_check = gota->GetPrevious();
487 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
488 insert_before = suspend_check;
489 } else {
490 insert_before = gota;
491 }
492 }
493
494 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000495 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000496 } else {
497 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000498 }
499}
500
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600501HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100502 // For simplicity, don't bother reviving the cached null constant if it is
503 // not null and not in a block. Otherwise, we need to clear the instruction
504 // id and/or any invariants the graph is assuming when adding new instructions.
505 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600506 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000507 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000508 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000509 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000510 if (kIsDebugBuild) {
511 ScopedObjectAccess soa(Thread::Current());
512 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
513 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000514 return cached_null_constant_;
515}
516
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100517HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100518 // For simplicity, don't bother reviving the cached current method if it is
519 // not null and not in a block. Otherwise, we need to clear the instruction
520 // id and/or any invariants the graph is assuming when adding new instructions.
521 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700522 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600523 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
524 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100525 if (entry_block_->GetFirstInstruction() == nullptr) {
526 entry_block_->AddInstruction(cached_current_method_);
527 } else {
528 entry_block_->InsertInstructionBefore(
529 cached_current_method_, entry_block_->GetFirstInstruction());
530 }
531 }
532 return cached_current_method_;
533}
534
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600535HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000536 switch (type) {
537 case Primitive::Type::kPrimBoolean:
538 DCHECK(IsUint<1>(value));
539 FALLTHROUGH_INTENDED;
540 case Primitive::Type::kPrimByte:
541 case Primitive::Type::kPrimChar:
542 case Primitive::Type::kPrimShort:
543 case Primitive::Type::kPrimInt:
544 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600545 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000546
547 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600548 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000549
550 default:
551 LOG(FATAL) << "Unsupported constant type";
552 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000553 }
David Brazdil46e2a392015-03-16 17:31:52 +0000554}
555
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000556void HGraph::CacheFloatConstant(HFloatConstant* constant) {
557 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
558 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
559 cached_float_constants_.Overwrite(value, constant);
560}
561
562void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
563 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
564 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
565 cached_double_constants_.Overwrite(value, constant);
566}
567
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000568void HLoopInformation::Add(HBasicBlock* block) {
569 blocks_.SetBit(block->GetBlockId());
570}
571
David Brazdil46e2a392015-03-16 17:31:52 +0000572void HLoopInformation::Remove(HBasicBlock* block) {
573 blocks_.ClearBit(block->GetBlockId());
574}
575
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100576void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
577 if (blocks_.IsBitSet(block->GetBlockId())) {
578 return;
579 }
580
581 blocks_.SetBit(block->GetBlockId());
582 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000583 for (HBasicBlock* predecessor : block->GetPredecessors()) {
584 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100585 }
586}
587
David Brazdilc2e8af92016-04-05 17:15:19 +0100588void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
589 size_t block_id = block->GetBlockId();
590
591 // If `block` is in `finalized`, we know its membership in the loop has been
592 // decided and it does not need to be revisited.
593 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594 return;
595 }
596
David Brazdilc2e8af92016-04-05 17:15:19 +0100597 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000598 if (block->IsLoopHeader()) {
599 // If we hit a loop header in an irreducible loop, we first check if the
600 // pre header of that loop belongs to the currently analyzed loop. If it does,
601 // then we visit the back edges.
602 // Note that we cannot use GetPreHeader, as the loop may have not been populated
603 // yet.
604 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100605 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000606 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000607 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100608 blocks_.SetBit(block_id);
609 finalized->SetBit(block_id);
610 is_finalized = true;
611
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000612 HLoopInformation* info = block->GetLoopInformation();
613 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100614 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000615 }
616 }
617 } else {
618 // Visit all predecessors. If one predecessor is part of the loop, this
619 // block is also part of this loop.
620 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100621 PopulateIrreducibleRecursive(predecessor, finalized);
622 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000623 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100624 blocks_.SetBit(block_id);
625 finalized->SetBit(block_id);
626 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000627 }
628 }
629 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100630
631 // All predecessors have been recursively visited. Mark finalized if not marked yet.
632 if (!is_finalized) {
633 finalized->SetBit(block_id);
634 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000635}
636
637void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100638 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000639 // Populate this loop: starting with the back edge, recursively add predecessors
640 // that are not already part of that loop. Set the header as part of the loop
641 // to end the recursion.
642 // This is a recursive implementation of the algorithm described in
643 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100644 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000645 blocks_.SetBit(header_->GetBlockId());
646 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100647
David Brazdil3f4a5222016-05-06 12:46:21 +0100648 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100649
650 if (is_irreducible_loop) {
651 ArenaBitVector visited(graph->GetArena(),
652 graph->GetBlocks().size(),
653 /* expandable */ false,
654 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100655 // Stop marking blocks at the loop header.
656 visited.SetBit(header_->GetBlockId());
657
David Brazdilc2e8af92016-04-05 17:15:19 +0100658 for (HBasicBlock* back_edge : GetBackEdges()) {
659 PopulateIrreducibleRecursive(back_edge, &visited);
660 }
661 } else {
662 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000663 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100664 }
David Brazdila4b8c212015-05-07 09:59:30 +0100665 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100666
Vladimir Markofd66c502016-04-18 15:37:01 +0100667 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
668 // When compiling in OSR mode, all loops in the compiled method may be entered
669 // from the interpreter. We treat this OSR entry point just like an extra entry
670 // to an irreducible loop, so we need to mark the method's loops as irreducible.
671 // This does not apply to inlined loops which do not act as OSR entry points.
672 if (suspend_check_ == nullptr) {
673 // Just building the graph in OSR mode, this loop is not inlined. We never build an
674 // inner graph in OSR mode as we can do OSR transition only from the outer method.
675 is_irreducible_loop = true;
676 } else {
677 // Look at the suspend check's environment to determine if the loop was inlined.
678 DCHECK(suspend_check_->HasEnvironment());
679 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
680 is_irreducible_loop = true;
681 }
682 }
683 }
684 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100685 irreducible_ = true;
686 graph->SetHasIrreducibleLoops(true);
687 }
David Brazdila4b8c212015-05-07 09:59:30 +0100688}
689
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100690HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000691 HBasicBlock* block = header_->GetPredecessors()[0];
692 DCHECK(irreducible_ || (block == header_->GetDominator()));
693 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100694}
695
696bool HLoopInformation::Contains(const HBasicBlock& block) const {
697 return blocks_.IsBitSet(block.GetBlockId());
698}
699
700bool HLoopInformation::IsIn(const HLoopInformation& other) const {
701 return other.blocks_.IsBitSet(header_->GetBlockId());
702}
703
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800704bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
705 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700706}
707
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100708size_t HLoopInformation::GetLifetimeEnd() const {
709 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100710 for (HBasicBlock* back_edge : GetBackEdges()) {
711 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100712 }
713 return last_position;
714}
715
David Brazdil3f4a5222016-05-06 12:46:21 +0100716bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
717 for (HBasicBlock* back_edge : GetBackEdges()) {
718 DCHECK(back_edge->GetDominator() != nullptr);
719 if (!header_->Dominates(back_edge)) {
720 return true;
721 }
722 }
723 return false;
724}
725
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100726bool HBasicBlock::Dominates(HBasicBlock* other) const {
727 // Walk up the dominator tree from `other`, to find out if `this`
728 // is an ancestor.
729 HBasicBlock* current = other;
730 while (current != nullptr) {
731 if (current == this) {
732 return true;
733 }
734 current = current->GetDominator();
735 }
736 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100737}
738
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100739static void UpdateInputsUsers(HInstruction* instruction) {
740 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
741 instruction->InputAt(i)->AddUseAt(instruction, i);
742 }
743 // Environment should be created later.
744 DCHECK(!instruction->HasEnvironment());
745}
746
Roland Levillainccc07a92014-09-16 14:48:16 +0100747void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
748 HInstruction* replacement) {
749 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400750 if (initial->IsControlFlow()) {
751 // We can only replace a control flow instruction with another control flow instruction.
752 DCHECK(replacement->IsControlFlow());
753 DCHECK_EQ(replacement->GetId(), -1);
754 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
755 DCHECK_EQ(initial->GetBlock(), this);
756 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100757 DCHECK(initial->GetUses().empty());
758 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400759 replacement->SetBlock(this);
760 replacement->SetId(GetGraph()->GetNextInstructionId());
761 instructions_.InsertInstructionBefore(replacement, initial);
762 UpdateInputsUsers(replacement);
763 } else {
764 InsertInstructionBefore(replacement, initial);
765 initial->ReplaceWith(replacement);
766 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100767 RemoveInstruction(initial);
768}
769
David Brazdil74eb1b22015-12-14 11:44:01 +0000770void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
771 DCHECK(!cursor->IsPhi());
772 DCHECK(!insn->IsPhi());
773 DCHECK(!insn->IsControlFlow());
774 DCHECK(insn->CanBeMoved());
775 DCHECK(!insn->HasSideEffects());
776
777 HBasicBlock* from_block = insn->GetBlock();
778 HBasicBlock* to_block = cursor->GetBlock();
779 DCHECK(from_block != to_block);
780
781 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
782 insn->SetBlock(to_block);
783 to_block->instructions_.InsertInstructionBefore(insn, cursor);
784}
785
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100786static void Add(HInstructionList* instruction_list,
787 HBasicBlock* block,
788 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000789 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000790 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100791 instruction->SetBlock(block);
792 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100793 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100794 instruction_list->AddInstruction(instruction);
795}
796
797void HBasicBlock::AddInstruction(HInstruction* instruction) {
798 Add(&instructions_, this, instruction);
799}
800
801void HBasicBlock::AddPhi(HPhi* phi) {
802 Add(&phis_, this, phi);
803}
804
David Brazdilc3d743f2015-04-22 13:40:50 +0100805void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
806 DCHECK(!cursor->IsPhi());
807 DCHECK(!instruction->IsPhi());
808 DCHECK_EQ(instruction->GetId(), -1);
809 DCHECK_NE(cursor->GetId(), -1);
810 DCHECK_EQ(cursor->GetBlock(), this);
811 DCHECK(!instruction->IsControlFlow());
812 instruction->SetBlock(this);
813 instruction->SetId(GetGraph()->GetNextInstructionId());
814 UpdateInputsUsers(instruction);
815 instructions_.InsertInstructionBefore(instruction, cursor);
816}
817
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100818void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
819 DCHECK(!cursor->IsPhi());
820 DCHECK(!instruction->IsPhi());
821 DCHECK_EQ(instruction->GetId(), -1);
822 DCHECK_NE(cursor->GetId(), -1);
823 DCHECK_EQ(cursor->GetBlock(), this);
824 DCHECK(!instruction->IsControlFlow());
825 DCHECK(!cursor->IsControlFlow());
826 instruction->SetBlock(this);
827 instruction->SetId(GetGraph()->GetNextInstructionId());
828 UpdateInputsUsers(instruction);
829 instructions_.InsertInstructionAfter(instruction, cursor);
830}
831
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100832void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
833 DCHECK_EQ(phi->GetId(), -1);
834 DCHECK_NE(cursor->GetId(), -1);
835 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100836 phi->SetBlock(this);
837 phi->SetId(GetGraph()->GetNextInstructionId());
838 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100839 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100840}
841
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100842static void Remove(HInstructionList* instruction_list,
843 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000844 HInstruction* instruction,
845 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100846 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100847 instruction->SetBlock(nullptr);
848 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000849 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100850 DCHECK(instruction->GetUses().empty());
851 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000852 RemoveAsUser(instruction);
853 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100854}
855
David Brazdil1abb4192015-02-17 18:33:36 +0000856void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100857 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000858 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100859}
860
David Brazdil1abb4192015-02-17 18:33:36 +0000861void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
862 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100863}
864
David Brazdilc7508e92015-04-27 13:28:57 +0100865void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
866 if (instruction->IsPhi()) {
867 RemovePhi(instruction->AsPhi(), ensure_safety);
868 } else {
869 RemoveInstruction(instruction, ensure_safety);
870 }
871}
872
Vladimir Marko71bf8092015-09-15 15:33:14 +0100873void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
874 for (size_t i = 0; i < locals.size(); i++) {
875 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100876 SetRawEnvAt(i, instruction);
877 if (instruction != nullptr) {
878 instruction->AddEnvUseAt(this, i);
879 }
880 }
881}
882
David Brazdiled596192015-01-23 10:39:45 +0000883void HEnvironment::CopyFrom(HEnvironment* env) {
884 for (size_t i = 0; i < env->Size(); i++) {
885 HInstruction* instruction = env->GetInstructionAt(i);
886 SetRawEnvAt(i, instruction);
887 if (instruction != nullptr) {
888 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100889 }
David Brazdiled596192015-01-23 10:39:45 +0000890 }
891}
892
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700893void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
894 HBasicBlock* loop_header) {
895 DCHECK(loop_header->IsLoopHeader());
896 for (size_t i = 0; i < env->Size(); i++) {
897 HInstruction* instruction = env->GetInstructionAt(i);
898 SetRawEnvAt(i, instruction);
899 if (instruction == nullptr) {
900 continue;
901 }
902 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
903 // At the end of the loop pre-header, the corresponding value for instruction
904 // is the first input of the phi.
905 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700906 SetRawEnvAt(i, initial);
907 initial->AddEnvUseAt(this, i);
908 } else {
909 instruction->AddEnvUseAt(this, i);
910 }
911 }
912}
913
David Brazdil1abb4192015-02-17 18:33:36 +0000914void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100915 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
916 HInstruction* user = env_use.GetInstruction();
917 auto before_env_use_node = env_use.GetBeforeUseNode();
918 user->env_uses_.erase_after(before_env_use_node);
919 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100920}
921
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000922HInstruction::InstructionKind HInstruction::GetKind() const {
923 return GetKindInternal();
924}
925
Calin Juravle77520bc2015-01-12 18:45:46 +0000926HInstruction* HInstruction::GetNextDisregardingMoves() const {
927 HInstruction* next = GetNext();
928 while (next != nullptr && next->IsParallelMove()) {
929 next = next->GetNext();
930 }
931 return next;
932}
933
934HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
935 HInstruction* previous = GetPrevious();
936 while (previous != nullptr && previous->IsParallelMove()) {
937 previous = previous->GetPrevious();
938 }
939 return previous;
940}
941
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100942void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000943 if (first_instruction_ == nullptr) {
944 DCHECK(last_instruction_ == nullptr);
945 first_instruction_ = last_instruction_ = instruction;
946 } else {
947 last_instruction_->next_ = instruction;
948 instruction->previous_ = last_instruction_;
949 last_instruction_ = instruction;
950 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000951}
952
David Brazdilc3d743f2015-04-22 13:40:50 +0100953void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
954 DCHECK(Contains(cursor));
955 if (cursor == first_instruction_) {
956 cursor->previous_ = instruction;
957 instruction->next_ = cursor;
958 first_instruction_ = instruction;
959 } else {
960 instruction->previous_ = cursor->previous_;
961 instruction->next_ = cursor;
962 cursor->previous_ = instruction;
963 instruction->previous_->next_ = instruction;
964 }
965}
966
967void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
968 DCHECK(Contains(cursor));
969 if (cursor == last_instruction_) {
970 cursor->next_ = instruction;
971 instruction->previous_ = cursor;
972 last_instruction_ = instruction;
973 } else {
974 instruction->next_ = cursor->next_;
975 instruction->previous_ = cursor;
976 cursor->next_ = instruction;
977 instruction->next_->previous_ = instruction;
978 }
979}
980
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100981void HInstructionList::RemoveInstruction(HInstruction* instruction) {
982 if (instruction->previous_ != nullptr) {
983 instruction->previous_->next_ = instruction->next_;
984 }
985 if (instruction->next_ != nullptr) {
986 instruction->next_->previous_ = instruction->previous_;
987 }
988 if (instruction == first_instruction_) {
989 first_instruction_ = instruction->next_;
990 }
991 if (instruction == last_instruction_) {
992 last_instruction_ = instruction->previous_;
993 }
994}
995
Roland Levillain6b469232014-09-25 10:10:38 +0100996bool HInstructionList::Contains(HInstruction* instruction) const {
997 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
998 if (it.Current() == instruction) {
999 return true;
1000 }
1001 }
1002 return false;
1003}
1004
Roland Levillainccc07a92014-09-16 14:48:16 +01001005bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1006 const HInstruction* instruction2) const {
1007 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1008 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1009 if (it.Current() == instruction1) {
1010 return true;
1011 }
1012 if (it.Current() == instruction2) {
1013 return false;
1014 }
1015 }
1016 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1017 return true;
1018}
1019
Roland Levillain6c82d402014-10-13 16:10:27 +01001020bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1021 if (other_instruction == this) {
1022 // An instruction does not strictly dominate itself.
1023 return false;
1024 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001025 HBasicBlock* block = GetBlock();
1026 HBasicBlock* other_block = other_instruction->GetBlock();
1027 if (block != other_block) {
1028 return GetBlock()->Dominates(other_instruction->GetBlock());
1029 } else {
1030 // If both instructions are in the same block, ensure this
1031 // instruction comes before `other_instruction`.
1032 if (IsPhi()) {
1033 if (!other_instruction->IsPhi()) {
1034 // Phis appear before non phi-instructions so this instruction
1035 // dominates `other_instruction`.
1036 return true;
1037 } else {
1038 // There is no order among phis.
1039 LOG(FATAL) << "There is no dominance between phis of a same block.";
1040 return false;
1041 }
1042 } else {
1043 // `this` is not a phi.
1044 if (other_instruction->IsPhi()) {
1045 // Phis appear before non phi-instructions so this instruction
1046 // does not dominate `other_instruction`.
1047 return false;
1048 } else {
1049 // Check whether this instruction comes before
1050 // `other_instruction` in the instruction list.
1051 return block->GetInstructions().FoundBefore(this, other_instruction);
1052 }
1053 }
1054 }
1055}
1056
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001057void HInstruction::RemoveEnvironment() {
1058 RemoveEnvironmentUses(this);
1059 environment_ = nullptr;
1060}
1061
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001062void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001063 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001064 // Note: fixup_end remains valid across splice_after().
1065 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1066 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1067 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001068
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001069 // Note: env_fixup_end remains valid across splice_after().
1070 auto env_fixup_end =
1071 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1072 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1073 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001074
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001075 DCHECK(uses_.empty());
1076 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001077}
1078
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001079void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001080 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001081 if (input_use.GetInstruction() == replacement) {
1082 // Nothing to do.
1083 return;
1084 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001085 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001086 // Note: fixup_end remains valid across splice_after().
1087 auto fixup_end =
1088 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1089 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1090 input_use.GetInstruction()->uses_,
1091 before_use_node);
1092 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1093 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001094}
1095
Nicolas Geoffray39468442014-09-02 15:17:15 +01001096size_t HInstruction::EnvironmentSize() const {
1097 return HasEnvironment() ? environment_->Size() : 0;
1098}
1099
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001100void HPhi::AddInput(HInstruction* input) {
1101 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001102 inputs_.push_back(HUserRecord<HInstruction*>(input));
1103 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001104}
1105
David Brazdil2d7352b2015-04-20 14:52:42 +01001106void HPhi::RemoveInputAt(size_t index) {
1107 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001108 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001109 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001110 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001111 InputRecordAt(i).GetUseNode()->SetIndex(i);
1112 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001113}
1114
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001115#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001116void H##name::Accept(HGraphVisitor* visitor) { \
1117 visitor->Visit##name(this); \
1118}
1119
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001120FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001121
1122#undef DEFINE_ACCEPT
1123
1124void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001125 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1126 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001127 if (block != nullptr) {
1128 VisitBasicBlock(block);
1129 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001130 }
1131}
1132
Roland Levillain633021e2014-10-01 14:12:25 +01001133void HGraphVisitor::VisitReversePostOrder() {
1134 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1135 VisitBasicBlock(it.Current());
1136 }
1137}
1138
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001139void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001140 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001141 it.Current()->Accept(this);
1142 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001143 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001144 it.Current()->Accept(this);
1145 }
1146}
1147
Mark Mendelle82549b2015-05-06 10:55:34 -04001148HConstant* HTypeConversion::TryStaticEvaluation() const {
1149 HGraph* graph = GetBlock()->GetGraph();
1150 if (GetInput()->IsIntConstant()) {
1151 int32_t value = GetInput()->AsIntConstant()->GetValue();
1152 switch (GetResultType()) {
1153 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001155 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001156 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001157 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001158 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001159 default:
1160 return nullptr;
1161 }
1162 } else if (GetInput()->IsLongConstant()) {
1163 int64_t value = GetInput()->AsLongConstant()->GetValue();
1164 switch (GetResultType()) {
1165 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001166 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001167 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001168 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001169 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001170 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001171 default:
1172 return nullptr;
1173 }
1174 } else if (GetInput()->IsFloatConstant()) {
1175 float value = GetInput()->AsFloatConstant()->GetValue();
1176 switch (GetResultType()) {
1177 case Primitive::kPrimInt:
1178 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001179 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001180 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001181 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001182 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001183 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1184 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001185 case Primitive::kPrimLong:
1186 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001187 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001188 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001189 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001190 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001191 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1192 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001193 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001194 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001195 default:
1196 return nullptr;
1197 }
1198 } else if (GetInput()->IsDoubleConstant()) {
1199 double value = GetInput()->AsDoubleConstant()->GetValue();
1200 switch (GetResultType()) {
1201 case Primitive::kPrimInt:
1202 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001203 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001204 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001205 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001206 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001207 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1208 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001209 case Primitive::kPrimLong:
1210 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001211 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001212 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001213 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001214 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001215 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1216 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001217 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001218 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001219 default:
1220 return nullptr;
1221 }
1222 }
1223 return nullptr;
1224}
1225
Roland Levillain9240d6a2014-10-20 16:47:04 +01001226HConstant* HUnaryOperation::TryStaticEvaluation() const {
1227 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001228 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001229 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001230 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001231 } else if (kEnableFloatingPointStaticEvaluation) {
1232 if (GetInput()->IsFloatConstant()) {
1233 return Evaluate(GetInput()->AsFloatConstant());
1234 } else if (GetInput()->IsDoubleConstant()) {
1235 return Evaluate(GetInput()->AsDoubleConstant());
1236 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001237 }
1238 return nullptr;
1239}
1240
1241HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001242 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1243 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001244 } else if (GetLeft()->IsLongConstant()) {
1245 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001246 // The binop(long, int) case is only valid for shifts and rotations.
1247 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001248 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1249 } else if (GetRight()->IsLongConstant()) {
1250 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001251 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001252 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001253 // The binop(null, null) case is only valid for equal and not-equal conditions.
1254 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001255 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001256 } else if (kEnableFloatingPointStaticEvaluation) {
1257 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1258 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1259 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1260 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1261 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001262 }
1263 return nullptr;
1264}
Dave Allison20dfc792014-06-16 20:44:29 -07001265
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001266HConstant* HBinaryOperation::GetConstantRight() const {
1267 if (GetRight()->IsConstant()) {
1268 return GetRight()->AsConstant();
1269 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1270 return GetLeft()->AsConstant();
1271 } else {
1272 return nullptr;
1273 }
1274}
1275
1276// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001277// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001278HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1279 HInstruction* most_constant_right = GetConstantRight();
1280 if (most_constant_right == nullptr) {
1281 return nullptr;
1282 } else if (most_constant_right == GetLeft()) {
1283 return GetRight();
1284 } else {
1285 return GetLeft();
1286 }
1287}
1288
Roland Levillain31dd3d62016-02-16 12:21:02 +00001289std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1290 switch (rhs) {
1291 case ComparisonBias::kNoBias:
1292 return os << "no_bias";
1293 case ComparisonBias::kGtBias:
1294 return os << "gt_bias";
1295 case ComparisonBias::kLtBias:
1296 return os << "lt_bias";
1297 default:
1298 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1299 UNREACHABLE();
1300 }
1301}
1302
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001303bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1304 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001305}
1306
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001307bool HInstruction::Equals(HInstruction* other) const {
1308 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001309 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001310 if (!InstructionDataEquals(other)) return false;
1311 if (GetType() != other->GetType()) return false;
1312 if (InputCount() != other->InputCount()) return false;
1313
1314 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1315 if (InputAt(i) != other->InputAt(i)) return false;
1316 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001317 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001318 return true;
1319}
1320
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001321std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1322#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1323 switch (rhs) {
1324 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1325 default:
1326 os << "Unknown instruction kind " << static_cast<int>(rhs);
1327 break;
1328 }
1329#undef DECLARE_CASE
1330 return os;
1331}
1332
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001333void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001334 next_->previous_ = previous_;
1335 if (previous_ != nullptr) {
1336 previous_->next_ = next_;
1337 }
1338 if (block_->instructions_.first_instruction_ == this) {
1339 block_->instructions_.first_instruction_ = next_;
1340 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001341 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001342
1343 previous_ = cursor->previous_;
1344 if (previous_ != nullptr) {
1345 previous_->next_ = this;
1346 }
1347 next_ = cursor;
1348 cursor->previous_ = this;
1349 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001350
1351 if (block_->instructions_.first_instruction_ == cursor) {
1352 block_->instructions_.first_instruction_ = this;
1353 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001354}
1355
Vladimir Markofb337ea2015-11-25 15:25:10 +00001356void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1357 DCHECK(!CanThrow());
1358 DCHECK(!HasSideEffects());
1359 DCHECK(!HasEnvironmentUses());
1360 DCHECK(HasNonEnvironmentUses());
1361 DCHECK(!IsPhi()); // Makes no sense for Phi.
1362 DCHECK_EQ(InputCount(), 0u);
1363
1364 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001365 auto uses_it = GetUses().begin();
1366 auto uses_end = GetUses().end();
1367 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1368 ++uses_it;
1369 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1370 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001371 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001372 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001373 // This instruction has uses in two or more blocks. Find the common dominator.
1374 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001375 for (; uses_it != uses_end; ++uses_it) {
1376 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001377 }
1378 target_block = finder.Get();
1379 DCHECK(target_block != nullptr);
1380 }
1381 // Move to the first dominator not in a loop.
1382 while (target_block->IsInLoop()) {
1383 target_block = target_block->GetDominator();
1384 DCHECK(target_block != nullptr);
1385 }
1386
1387 // Find insertion position.
1388 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001389 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1390 if (use.GetUser()->GetBlock() == target_block &&
1391 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1392 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001393 }
1394 }
1395 if (insert_pos == nullptr) {
1396 // No user in `target_block`, insert before the control flow instruction.
1397 insert_pos = target_block->GetLastInstruction();
1398 DCHECK(insert_pos->IsControlFlow());
1399 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1400 if (insert_pos->IsIf()) {
1401 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1402 if (if_input == insert_pos->GetPrevious()) {
1403 insert_pos = if_input;
1404 }
1405 }
1406 }
1407 MoveBefore(insert_pos);
1408}
1409
David Brazdilfc6a86a2015-06-26 10:33:45 +00001410HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001411 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001412 DCHECK_EQ(cursor->GetBlock(), this);
1413
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001414 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1415 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001416 new_block->instructions_.first_instruction_ = cursor;
1417 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1418 instructions_.last_instruction_ = cursor->previous_;
1419 if (cursor->previous_ == nullptr) {
1420 instructions_.first_instruction_ = nullptr;
1421 } else {
1422 cursor->previous_->next_ = nullptr;
1423 cursor->previous_ = nullptr;
1424 }
1425
1426 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001427 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001428
Vladimir Marko60584552015-09-03 13:35:12 +00001429 for (HBasicBlock* successor : GetSuccessors()) {
1430 new_block->successors_.push_back(successor);
1431 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001432 }
Vladimir Marko60584552015-09-03 13:35:12 +00001433 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001434 AddSuccessor(new_block);
1435
David Brazdil56e1acc2015-06-30 15:41:36 +01001436 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001437 return new_block;
1438}
1439
David Brazdild7558da2015-09-22 13:04:14 +01001440HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001441 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001442 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1443
1444 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1445
1446 for (HBasicBlock* predecessor : GetPredecessors()) {
1447 new_block->predecessors_.push_back(predecessor);
1448 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1449 }
1450 predecessors_.clear();
1451 AddPredecessor(new_block);
1452
1453 GetGraph()->AddBlock(new_block);
1454 return new_block;
1455}
1456
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001457HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1458 DCHECK_EQ(cursor->GetBlock(), this);
1459
1460 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1461 cursor->GetDexPc());
1462 new_block->instructions_.first_instruction_ = cursor;
1463 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1464 instructions_.last_instruction_ = cursor->previous_;
1465 if (cursor->previous_ == nullptr) {
1466 instructions_.first_instruction_ = nullptr;
1467 } else {
1468 cursor->previous_->next_ = nullptr;
1469 cursor->previous_ = nullptr;
1470 }
1471
1472 new_block->instructions_.SetBlockOfInstructions(new_block);
1473
1474 for (HBasicBlock* successor : GetSuccessors()) {
1475 new_block->successors_.push_back(successor);
1476 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1477 }
1478 successors_.clear();
1479
1480 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1481 dominated->dominator_ = new_block;
1482 new_block->dominated_blocks_.push_back(dominated);
1483 }
1484 dominated_blocks_.clear();
1485 return new_block;
1486}
1487
1488HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001489 DCHECK(!cursor->IsControlFlow());
1490 DCHECK_NE(instructions_.last_instruction_, cursor);
1491 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001492
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001493 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1494 new_block->instructions_.first_instruction_ = cursor->GetNext();
1495 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1496 cursor->next_->previous_ = nullptr;
1497 cursor->next_ = nullptr;
1498 instructions_.last_instruction_ = cursor;
1499
1500 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001501 for (HBasicBlock* successor : GetSuccessors()) {
1502 new_block->successors_.push_back(successor);
1503 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001504 }
Vladimir Marko60584552015-09-03 13:35:12 +00001505 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001506
Vladimir Marko60584552015-09-03 13:35:12 +00001507 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001508 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001509 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001510 }
Vladimir Marko60584552015-09-03 13:35:12 +00001511 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001512 return new_block;
1513}
1514
David Brazdilec16f792015-08-19 15:04:01 +01001515const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001516 if (EndsWithTryBoundary()) {
1517 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1518 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001519 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001520 return try_boundary;
1521 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001522 DCHECK(IsTryBlock());
1523 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001524 return nullptr;
1525 }
David Brazdilec16f792015-08-19 15:04:01 +01001526 } else if (IsTryBlock()) {
1527 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001528 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001529 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001530 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001531}
1532
David Brazdild7558da2015-09-22 13:04:14 +01001533bool HBasicBlock::HasThrowingInstructions() const {
1534 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1535 if (it.Current()->CanThrow()) {
1536 return true;
1537 }
1538 }
1539 return false;
1540}
1541
David Brazdilfc6a86a2015-06-26 10:33:45 +00001542static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1543 return block.GetPhis().IsEmpty()
1544 && !block.GetInstructions().IsEmpty()
1545 && block.GetFirstInstruction() == block.GetLastInstruction();
1546}
1547
David Brazdil46e2a392015-03-16 17:31:52 +00001548bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001549 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1550}
1551
1552bool HBasicBlock::IsSingleTryBoundary() const {
1553 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001554}
1555
David Brazdil8d5b8b22015-03-24 10:51:52 +00001556bool HBasicBlock::EndsWithControlFlowInstruction() const {
1557 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1558}
1559
David Brazdilb2bd1c52015-03-25 11:17:37 +00001560bool HBasicBlock::EndsWithIf() const {
1561 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1562}
1563
David Brazdilffee3d32015-07-06 11:48:53 +01001564bool HBasicBlock::EndsWithTryBoundary() const {
1565 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1566}
1567
David Brazdilb2bd1c52015-03-25 11:17:37 +00001568bool HBasicBlock::HasSinglePhi() const {
1569 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1570}
1571
David Brazdild26a4112015-11-10 11:07:31 +00001572ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1573 if (EndsWithTryBoundary()) {
1574 // The normal-flow successor of HTryBoundary is always stored at index zero.
1575 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1576 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1577 } else {
1578 // All successors of blocks not ending with TryBoundary are normal.
1579 return ArrayRef<HBasicBlock* const>(successors_);
1580 }
1581}
1582
1583ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1584 if (EndsWithTryBoundary()) {
1585 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1586 } else {
1587 // Blocks not ending with TryBoundary do not have exceptional successors.
1588 return ArrayRef<HBasicBlock* const>();
1589 }
1590}
1591
David Brazdilffee3d32015-07-06 11:48:53 +01001592bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001593 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1594 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1595
1596 size_t length = handlers1.size();
1597 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001598 return false;
1599 }
1600
David Brazdilb618ade2015-07-29 10:31:29 +01001601 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001602 for (size_t i = 0; i < length; ++i) {
1603 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001604 return false;
1605 }
1606 }
1607 return true;
1608}
1609
David Brazdil2d7352b2015-04-20 14:52:42 +01001610size_t HInstructionList::CountSize() const {
1611 size_t size = 0;
1612 HInstruction* current = first_instruction_;
1613 for (; current != nullptr; current = current->GetNext()) {
1614 size++;
1615 }
1616 return size;
1617}
1618
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001619void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1620 for (HInstruction* current = first_instruction_;
1621 current != nullptr;
1622 current = current->GetNext()) {
1623 current->SetBlock(block);
1624 }
1625}
1626
1627void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1628 DCHECK(Contains(cursor));
1629 if (!instruction_list.IsEmpty()) {
1630 if (cursor == last_instruction_) {
1631 last_instruction_ = instruction_list.last_instruction_;
1632 } else {
1633 cursor->next_->previous_ = instruction_list.last_instruction_;
1634 }
1635 instruction_list.last_instruction_->next_ = cursor->next_;
1636 cursor->next_ = instruction_list.first_instruction_;
1637 instruction_list.first_instruction_->previous_ = cursor;
1638 }
1639}
1640
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001641void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1642 DCHECK(Contains(cursor));
1643 if (!instruction_list.IsEmpty()) {
1644 if (cursor == first_instruction_) {
1645 first_instruction_ = instruction_list.first_instruction_;
1646 } else {
1647 cursor->previous_->next_ = instruction_list.first_instruction_;
1648 }
1649 instruction_list.last_instruction_->next_ = cursor;
1650 instruction_list.first_instruction_->previous_ = cursor->previous_;
1651 cursor->previous_ = instruction_list.last_instruction_;
1652 }
1653}
1654
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001655void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001656 if (IsEmpty()) {
1657 first_instruction_ = instruction_list.first_instruction_;
1658 last_instruction_ = instruction_list.last_instruction_;
1659 } else {
1660 AddAfter(last_instruction_, instruction_list);
1661 }
1662}
1663
David Brazdil04ff4e82015-12-10 13:54:52 +00001664// Should be called on instructions in a dead block in post order. This method
1665// assumes `insn` has been removed from all users with the exception of catch
1666// phis because of missing exceptional edges in the graph. It removes the
1667// instruction from catch phi uses, together with inputs of other catch phis in
1668// the catch block at the same index, as these must be dead too.
1669static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1670 DCHECK(!insn->HasEnvironmentUses());
1671 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001672 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1673 size_t use_index = use.GetIndex();
1674 HBasicBlock* user_block = use.GetUser()->GetBlock();
1675 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001676 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1677 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1678 }
1679 }
1680}
1681
David Brazdil2d7352b2015-04-20 14:52:42 +01001682void HBasicBlock::DisconnectAndDelete() {
1683 // Dominators must be removed after all the blocks they dominate. This way
1684 // a loop header is removed last, a requirement for correct loop information
1685 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001686 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001687
David Brazdil9eeebf62016-03-24 11:18:15 +00001688 // The following steps gradually remove the block from all its dependants in
1689 // post order (b/27683071).
1690
1691 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1692 // We need to do this before step (4) which destroys the predecessor list.
1693 HBasicBlock* loop_update_start = this;
1694 if (IsLoopHeader()) {
1695 HLoopInformation* loop_info = GetLoopInformation();
1696 // All other blocks in this loop should have been removed because the header
1697 // was their dominator.
1698 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1699 DCHECK(!loop_info->IsIrreducible());
1700 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1701 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1702 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001703 }
1704
David Brazdil9eeebf62016-03-24 11:18:15 +00001705 // (2) Disconnect the block from its successors and update their phis.
1706 for (HBasicBlock* successor : successors_) {
1707 // Delete this block from the list of predecessors.
1708 size_t this_index = successor->GetPredecessorIndexOf(this);
1709 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1710
1711 // Check that `successor` has other predecessors, otherwise `this` is the
1712 // dominator of `successor` which violates the order DCHECKed at the top.
1713 DCHECK(!successor->predecessors_.empty());
1714
1715 // Remove this block's entries in the successor's phis. Skip exceptional
1716 // successors because catch phi inputs do not correspond to predecessor
1717 // blocks but throwing instructions. The inputs of the catch phis will be
1718 // updated in step (3).
1719 if (!successor->IsCatchBlock()) {
1720 if (successor->predecessors_.size() == 1u) {
1721 // The successor has just one predecessor left. Replace phis with the only
1722 // remaining input.
1723 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1724 HPhi* phi = phi_it.Current()->AsPhi();
1725 phi->ReplaceWith(phi->InputAt(1 - this_index));
1726 successor->RemovePhi(phi);
1727 }
1728 } else {
1729 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1730 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1731 }
1732 }
1733 }
1734 }
1735 successors_.clear();
1736
1737 // (3) Remove instructions and phis. Instructions should have no remaining uses
1738 // except in catch phis. If an instruction is used by a catch phi at `index`,
1739 // remove `index`-th input of all phis in the catch block since they are
1740 // guaranteed dead. Note that we may miss dead inputs this way but the
1741 // graph will always remain consistent.
1742 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1743 HInstruction* insn = it.Current();
1744 RemoveUsesOfDeadInstruction(insn);
1745 RemoveInstruction(insn);
1746 }
1747 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1748 HPhi* insn = it.Current()->AsPhi();
1749 RemoveUsesOfDeadInstruction(insn);
1750 RemovePhi(insn);
1751 }
1752
1753 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001754 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001755 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001756 // We should not see any back edges as they would have been removed by step (3).
1757 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1758
David Brazdil2d7352b2015-04-20 14:52:42 +01001759 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001760 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1761 // This block is the only normal-flow successor of the TryBoundary which
1762 // makes `predecessor` dead. Since DCE removes blocks in post order,
1763 // exception handlers of this TryBoundary were already visited and any
1764 // remaining handlers therefore must be live. We remove `predecessor` from
1765 // their list of predecessors.
1766 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1767 while (predecessor->GetSuccessors().size() > 1) {
1768 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1769 DCHECK(handler->IsCatchBlock());
1770 predecessor->RemoveSuccessor(handler);
1771 handler->RemovePredecessor(predecessor);
1772 }
1773 }
1774
David Brazdil2d7352b2015-04-20 14:52:42 +01001775 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001776 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1777 if (num_pred_successors == 1u) {
1778 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001779 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1780 // successor. Replace those with a HGoto.
1781 DCHECK(last_instruction->IsIf() ||
1782 last_instruction->IsPackedSwitch() ||
1783 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001784 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001785 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001786 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001787 // The predecessor has no remaining successors and therefore must be dead.
1788 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001789 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001790 predecessor->RemoveInstruction(last_instruction);
1791 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001792 // There are multiple successors left. The removed block might be a successor
1793 // of a PackedSwitch which will be completely removed (perhaps replaced with
1794 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1795 // case, leave `last_instruction` as is for now.
1796 DCHECK(last_instruction->IsPackedSwitch() ||
1797 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001798 }
David Brazdil46e2a392015-03-16 17:31:52 +00001799 }
Vladimir Marko60584552015-09-03 13:35:12 +00001800 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001801
David Brazdil9eeebf62016-03-24 11:18:15 +00001802 // (5) Remove the block from all loops it is included in. Skip the inner-most
1803 // loop if this is the loop header (see definition of `loop_update_start`)
1804 // because the loop header's predecessor list has been destroyed in step (4).
1805 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1806 HLoopInformation* loop_info = it.Current();
1807 loop_info->Remove(this);
1808 if (loop_info->IsBackEdge(*this)) {
1809 // If this was the last back edge of the loop, we deliberately leave the
1810 // loop in an inconsistent state and will fail GraphChecker unless the
1811 // entire loop is removed during the pass.
1812 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001813 }
1814 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001815
David Brazdil9eeebf62016-03-24 11:18:15 +00001816 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001817 dominator_->RemoveDominatedBlock(this);
1818 SetDominator(nullptr);
1819
David Brazdil9eeebf62016-03-24 11:18:15 +00001820 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001821 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001822 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001823}
1824
1825void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001826 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001827 DCHECK(ContainsElement(dominated_blocks_, other));
1828 DCHECK_EQ(GetSingleSuccessor(), other);
1829 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001830 DCHECK(other->GetPhis().IsEmpty());
1831
David Brazdil2d7352b2015-04-20 14:52:42 +01001832 // Move instructions from `other` to `this`.
1833 DCHECK(EndsWithControlFlowInstruction());
1834 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001835 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001836 other->instructions_.SetBlockOfInstructions(this);
1837 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001838
David Brazdil2d7352b2015-04-20 14:52:42 +01001839 // Remove `other` from the loops it is included in.
1840 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1841 HLoopInformation* loop_info = it.Current();
1842 loop_info->Remove(other);
1843 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001844 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001845 }
1846 }
1847
1848 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001849 successors_.clear();
1850 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001851 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001852 successor->ReplacePredecessor(other, this);
1853 }
1854
David Brazdil2d7352b2015-04-20 14:52:42 +01001855 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001856 RemoveDominatedBlock(other);
1857 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1858 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001859 dominated->SetDominator(this);
1860 }
Vladimir Marko60584552015-09-03 13:35:12 +00001861 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001862 other->dominator_ = nullptr;
1863
1864 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001865 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001866
1867 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001868 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001869 other->SetGraph(nullptr);
1870}
1871
1872void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1873 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001874 DCHECK(GetDominatedBlocks().empty());
1875 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001876 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001877 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001878 DCHECK(other->GetPhis().IsEmpty());
1879 DCHECK(!other->IsInLoop());
1880
1881 // Move instructions from `other` to `this`.
1882 instructions_.Add(other->GetInstructions());
1883 other->instructions_.SetBlockOfInstructions(this);
1884
1885 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001886 successors_.clear();
1887 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001888 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001889 successor->ReplacePredecessor(other, this);
1890 }
1891
1892 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001893 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1894 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 dominated->SetDominator(this);
1896 }
Vladimir Marko60584552015-09-03 13:35:12 +00001897 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 other->dominator_ = nullptr;
1899 other->graph_ = nullptr;
1900}
1901
1902void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001903 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001904 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001905 predecessor->ReplaceSuccessor(this, other);
1906 }
Vladimir Marko60584552015-09-03 13:35:12 +00001907 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001908 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001909 successor->ReplacePredecessor(this, other);
1910 }
Vladimir Marko60584552015-09-03 13:35:12 +00001911 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1912 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001913 }
1914 GetDominator()->ReplaceDominatedBlock(this, other);
1915 other->SetDominator(GetDominator());
1916 dominator_ = nullptr;
1917 graph_ = nullptr;
1918}
1919
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001920void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001921 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001922 DCHECK(block->GetSuccessors().empty());
1923 DCHECK(block->GetPredecessors().empty());
1924 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001925 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001926 DCHECK(block->GetInstructions().IsEmpty());
1927 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001928
David Brazdilc7af85d2015-05-26 12:05:55 +01001929 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001930 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001931 }
1932
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001933 RemoveElement(reverse_post_order_, block);
1934 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001935 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001936}
1937
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001938void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1939 HBasicBlock* reference,
1940 bool replace_if_back_edge) {
1941 if (block->IsLoopHeader()) {
1942 // Clear the information of which blocks are contained in that loop. Since the
1943 // information is stored as a bit vector based on block ids, we have to update
1944 // it, as those block ids were specific to the callee graph and we are now adding
1945 // these blocks to the caller graph.
1946 block->GetLoopInformation()->ClearAllBlocks();
1947 }
1948
1949 // If not already in a loop, update the loop information.
1950 if (!block->IsInLoop()) {
1951 block->SetLoopInformation(reference->GetLoopInformation());
1952 }
1953
1954 // If the block is in a loop, update all its outward loops.
1955 HLoopInformation* loop_info = block->GetLoopInformation();
1956 if (loop_info != nullptr) {
1957 for (HLoopInformationOutwardIterator loop_it(*block);
1958 !loop_it.Done();
1959 loop_it.Advance()) {
1960 loop_it.Current()->Add(block);
1961 }
1962 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1963 loop_info->ReplaceBackEdge(reference, block);
1964 }
1965 }
1966
1967 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1968 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1969 ? reference->GetTryCatchInformation()
1970 : nullptr;
1971 block->SetTryCatchInformation(try_catch_info);
1972}
1973
Calin Juravle2e768302015-07-28 14:41:11 +00001974HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001975 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001976 // Update the environments in this graph to have the invoke's environment
1977 // as parent.
1978 {
1979 HReversePostOrderIterator it(*this);
1980 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1981 for (; !it.Done(); it.Advance()) {
1982 HBasicBlock* block = it.Current();
1983 for (HInstructionIterator instr_it(block->GetInstructions());
1984 !instr_it.Done();
1985 instr_it.Advance()) {
1986 HInstruction* current = instr_it.Current();
1987 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001988 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001989 current->GetEnvironment()->SetAndCopyParentChain(
1990 outer_graph->GetArena(), invoke->GetEnvironment());
1991 }
1992 }
1993 }
1994 }
1995 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1996 if (HasBoundsChecks()) {
1997 outer_graph->SetHasBoundsChecks(true);
1998 }
1999
Calin Juravle2e768302015-07-28 14:41:11 +00002000 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002001 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002002 // Simple case of an entry block, a body block, and an exit block.
2003 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002004 HBasicBlock* body = GetBlocks()[1];
2005 DCHECK(GetBlocks()[0]->IsEntryBlock());
2006 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002007 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002008 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002009 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002010
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002011 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2012 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002013 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002014
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002015 // Replace the invoke with the return value of the inlined graph.
2016 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002017 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002018 } else {
2019 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002020 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002021
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002022 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002023 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002024 // Need to inline multiple blocks. We split `invoke`'s block
2025 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002026 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002027 // with the second half.
2028 ArenaAllocator* allocator = outer_graph->GetArena();
2029 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002030 // Note that we split before the invoke only to simplify polymorphic inlining.
2031 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002032
Vladimir Markoec7802a2015-10-01 20:57:57 +01002033 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002034 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002035 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002036 exit_block_->ReplaceWith(to);
2037
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002038 // Update the meta information surrounding blocks:
2039 // (1) the graph they are now in,
2040 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002041 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002042 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002043 // Note that we do not need to update catch phi inputs because they
2044 // correspond to the register file of the outer method which the inlinee
2045 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002046
2047 // We don't add the entry block, the exit block, and the first block, which
2048 // has been merged with `at`.
2049 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2050
2051 // We add the `to` block.
2052 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002053 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002054 + kNumberOfNewBlocksInCaller;
2055
2056 // Find the location of `at` in the outer graph's reverse post order. The new
2057 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002058 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002059 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2060
David Brazdil95177982015-10-30 12:56:58 -05002061 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2062 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002063 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2064 HBasicBlock* current = it.Current();
2065 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002066 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002067 DCHECK(current->GetGraph() == this);
2068 current->SetGraph(outer_graph);
2069 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002070 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002071 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002072 }
2073 }
2074
David Brazdil95177982015-10-30 12:56:58 -05002075 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002076 to->SetGraph(outer_graph);
2077 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002078 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002079 // Only `to` can become a back edge, as the inlined blocks
2080 // are predecessors of `to`.
2081 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002082
David Brazdil3f523062016-02-29 16:53:33 +00002083 // Update all predecessors of the exit block (now the `to` block)
2084 // to not `HReturn` but `HGoto` instead.
2085 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2086 if (to->GetPredecessors().size() == 1) {
2087 HBasicBlock* predecessor = to->GetPredecessors()[0];
2088 HInstruction* last = predecessor->GetLastInstruction();
2089 if (!returns_void) {
2090 return_value = last->InputAt(0);
2091 }
2092 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2093 predecessor->RemoveInstruction(last);
2094 } else {
2095 if (!returns_void) {
2096 // There will be multiple returns.
2097 return_value = new (allocator) HPhi(
2098 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2099 to->AddPhi(return_value->AsPhi());
2100 }
2101 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2102 HInstruction* last = predecessor->GetLastInstruction();
2103 if (!returns_void) {
2104 DCHECK(last->IsReturn());
2105 return_value->AsPhi()->AddInput(last->InputAt(0));
2106 }
2107 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2108 predecessor->RemoveInstruction(last);
2109 }
2110 }
2111 }
David Brazdil05144f42015-04-16 15:18:00 +01002112
2113 // Walk over the entry block and:
2114 // - Move constants from the entry block to the outer_graph's entry block,
2115 // - Replace HParameterValue instructions with their real value.
2116 // - Remove suspend checks, that hold an environment.
2117 // We must do this after the other blocks have been inlined, otherwise ids of
2118 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002119 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002120 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2121 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002122 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002123 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002124 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002125 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002126 replacement = outer_graph->GetIntConstant(
2127 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002128 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002129 replacement = outer_graph->GetLongConstant(
2130 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002131 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002132 replacement = outer_graph->GetFloatConstant(
2133 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002134 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002135 replacement = outer_graph->GetDoubleConstant(
2136 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002137 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002138 if (kIsDebugBuild
2139 && invoke->IsInvokeStaticOrDirect()
2140 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2141 // Ensure we do not use the last input of `invoke`, as it
2142 // contains a clinit check which is not an actual argument.
2143 size_t last_input_index = invoke->InputCount() - 1;
2144 DCHECK(parameter_index != last_input_index);
2145 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002146 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002147 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002148 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002149 } else {
2150 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2151 entry_block_->RemoveInstruction(current);
2152 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002153 if (replacement != nullptr) {
2154 current->ReplaceWith(replacement);
2155 // If the current is the return value then we need to update the latter.
2156 if (current == return_value) {
2157 DCHECK_EQ(entry_block_, return_value->GetBlock());
2158 return_value = replacement;
2159 }
2160 }
2161 }
2162
Calin Juravle2e768302015-07-28 14:41:11 +00002163 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002164}
2165
Mingyao Yang3584bce2015-05-19 16:01:59 -07002166/*
2167 * Loop will be transformed to:
2168 * old_pre_header
2169 * |
2170 * if_block
2171 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002172 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002173 * \ /
2174 * new_pre_header
2175 * |
2176 * header
2177 */
2178void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2179 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002180 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002181
Aart Bik3fc7f352015-11-20 22:03:03 -08002182 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002183 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002184 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2185 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002186 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2187 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002188 AddBlock(true_block);
2189 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002190 AddBlock(new_pre_header);
2191
Aart Bik3fc7f352015-11-20 22:03:03 -08002192 header->ReplacePredecessor(old_pre_header, new_pre_header);
2193 old_pre_header->successors_.clear();
2194 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002195
Aart Bik3fc7f352015-11-20 22:03:03 -08002196 old_pre_header->AddSuccessor(if_block);
2197 if_block->AddSuccessor(true_block); // True successor
2198 if_block->AddSuccessor(false_block); // False successor
2199 true_block->AddSuccessor(new_pre_header);
2200 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002201
Aart Bik3fc7f352015-11-20 22:03:03 -08002202 old_pre_header->dominated_blocks_.push_back(if_block);
2203 if_block->SetDominator(old_pre_header);
2204 if_block->dominated_blocks_.push_back(true_block);
2205 true_block->SetDominator(if_block);
2206 if_block->dominated_blocks_.push_back(false_block);
2207 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002208 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002209 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002210 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002211 header->SetDominator(new_pre_header);
2212
Aart Bik3fc7f352015-11-20 22:03:03 -08002213 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002214 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002215 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002216 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002217 reverse_post_order_[index_of_header++] = true_block;
2218 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002219 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002220
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002221 // The pre_header can never be a back edge of a loop.
2222 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2223 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2224 UpdateLoopAndTryInformationOfNewBlock(
2225 if_block, old_pre_header, /* replace_if_back_edge */ false);
2226 UpdateLoopAndTryInformationOfNewBlock(
2227 true_block, old_pre_header, /* replace_if_back_edge */ false);
2228 UpdateLoopAndTryInformationOfNewBlock(
2229 false_block, old_pre_header, /* replace_if_back_edge */ false);
2230 UpdateLoopAndTryInformationOfNewBlock(
2231 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002232}
2233
David Brazdilf5552582015-12-27 13:36:12 +00002234static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2235 SHARED_REQUIRES(Locks::mutator_lock_) {
2236 if (rti.IsValid()) {
2237 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2238 << " upper_bound_rti: " << upper_bound_rti
2239 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002240 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2241 << " upper_bound_rti: " << upper_bound_rti
2242 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002243 }
2244}
2245
Calin Juravle2e768302015-07-28 14:41:11 +00002246void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2247 if (kIsDebugBuild) {
2248 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2249 ScopedObjectAccess soa(Thread::Current());
2250 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2251 if (IsBoundType()) {
2252 // Having the test here spares us from making the method virtual just for
2253 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002254 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002255 }
2256 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002257 reference_type_handle_ = rti.GetTypeHandle();
2258 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002259}
2260
David Brazdilf5552582015-12-27 13:36:12 +00002261void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2262 if (kIsDebugBuild) {
2263 ScopedObjectAccess soa(Thread::Current());
2264 DCHECK(upper_bound.IsValid());
2265 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2266 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2267 }
2268 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002269 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002270}
2271
Vladimir Markoa1de9182016-02-25 11:37:38 +00002272ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002273 if (kIsDebugBuild) {
2274 ScopedObjectAccess soa(Thread::Current());
2275 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002276 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002277 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002278 if (!is_exact) {
2279 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2280 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2281 }
Calin Juravle2e768302015-07-28 14:41:11 +00002282 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002283 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002284}
2285
Calin Juravleacf735c2015-02-12 15:25:22 +00002286std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2287 ScopedObjectAccess soa(Thread::Current());
2288 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002289 << " is_valid=" << rhs.IsValid()
2290 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002291 << " is_exact=" << rhs.IsExact()
2292 << " ]";
2293 return os;
2294}
2295
Mark Mendellc4701932015-04-10 13:18:51 -04002296bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2297 // For now, assume that instructions in different blocks may use the
2298 // environment.
2299 // TODO: Use the control flow to decide if this is true.
2300 if (GetBlock() != other->GetBlock()) {
2301 return true;
2302 }
2303
2304 // We know that we are in the same block. Walk from 'this' to 'other',
2305 // checking to see if there is any instruction with an environment.
2306 HInstruction* current = this;
2307 for (; current != other && current != nullptr; current = current->GetNext()) {
2308 // This is a conservative check, as the instruction result may not be in
2309 // the referenced environment.
2310 if (current->HasEnvironment()) {
2311 return true;
2312 }
2313 }
2314
2315 // We should have been called with 'this' before 'other' in the block.
2316 // Just confirm this.
2317 DCHECK(current != nullptr);
2318 return false;
2319}
2320
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002321void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002322 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2323 IntrinsicSideEffects side_effects,
2324 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002325 intrinsic_ = intrinsic;
2326 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002327
Aart Bik5d75afe2015-12-14 11:57:01 -08002328 // Adjust method's side effects from intrinsic table.
2329 switch (side_effects) {
2330 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2331 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2332 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2333 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2334 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002335
2336 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2337 opt.SetDoesNotNeedDexCache();
2338 opt.SetDoesNotNeedEnvironment();
2339 } else {
2340 // If we need an environment, that means there will be a call, which can trigger GC.
2341 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2342 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002343 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002344 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002345}
2346
David Brazdil6de19382016-01-08 17:37:10 +00002347bool HNewInstance::IsStringAlloc() const {
2348 ScopedObjectAccess soa(Thread::Current());
2349 return GetReferenceTypeInfo().IsStringClass();
2350}
2351
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002352bool HInvoke::NeedsEnvironment() const {
2353 if (!IsIntrinsic()) {
2354 return true;
2355 }
2356 IntrinsicOptimizations opt(*this);
2357 return !opt.GetDoesNotNeedEnvironment();
2358}
2359
Vladimir Markodc151b22015-10-15 18:02:30 +01002360bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2361 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002362 return false;
2363 }
2364 if (!IsIntrinsic()) {
2365 return true;
2366 }
2367 IntrinsicOptimizations opt(*this);
2368 return !opt.GetDoesNotNeedDexCache();
2369}
2370
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002371void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2372 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2373 input->AddUseAt(this, index);
2374 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2375 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2376 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2377 InputRecordAt(i).GetUseNode()->SetIndex(i);
2378 }
2379}
2380
Vladimir Markob554b5a2015-11-06 12:57:55 +00002381void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2382 RemoveAsUserOfInput(index);
2383 inputs_.erase(inputs_.begin() + index);
2384 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2385 for (size_t i = index, e = InputCount(); i < e; ++i) {
2386 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2387 InputRecordAt(i).GetUseNode()->SetIndex(i);
2388 }
2389}
2390
Vladimir Markof64242a2015-12-01 14:58:23 +00002391std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2392 switch (rhs) {
2393 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2394 return os << "string_init";
2395 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2396 return os << "recursive";
2397 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2398 return os << "direct";
2399 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2400 return os << "direct_fixup";
2401 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2402 return os << "dex_cache_pc_relative";
2403 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2404 return os << "dex_cache_via_method";
2405 default:
2406 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2407 UNREACHABLE();
2408 }
2409}
2410
Vladimir Markofbb184a2015-11-13 14:47:00 +00002411std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2412 switch (rhs) {
2413 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2414 return os << "explicit";
2415 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2416 return os << "implicit";
2417 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2418 return os << "none";
2419 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002420 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2421 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002422 }
2423}
2424
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002425bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2426 HLoadString* other_load_string = other->AsLoadString();
2427 if (string_index_ != other_load_string->string_index_ ||
2428 GetPackedFields() != other_load_string->GetPackedFields()) {
2429 return false;
2430 }
2431 LoadKind load_kind = GetLoadKind();
2432 if (HasAddress(load_kind)) {
2433 return GetAddress() == other_load_string->GetAddress();
2434 } else if (HasStringReference(load_kind)) {
2435 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2436 } else {
2437 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2438 // If the string indexes and dex files are the same, dex cache element offsets
2439 // must also be the same, so we don't need to compare them.
2440 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2441 }
2442}
2443
2444void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2445 // Once sharpened, the load kind should not be changed again.
2446 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2447 SetPackedField<LoadKindField>(load_kind);
2448
2449 if (load_kind != LoadKind::kDexCacheViaMethod) {
2450 RemoveAsUserOfInput(0u);
2451 SetRawInputAt(0u, nullptr);
2452 }
2453 if (!NeedsEnvironment()) {
2454 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002455 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002456 }
2457}
2458
2459std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2460 switch (rhs) {
2461 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2462 return os << "BootImageLinkTimeAddress";
2463 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2464 return os << "BootImageLinkTimePcRelative";
2465 case HLoadString::LoadKind::kBootImageAddress:
2466 return os << "BootImageAddress";
2467 case HLoadString::LoadKind::kDexCacheAddress:
2468 return os << "DexCacheAddress";
2469 case HLoadString::LoadKind::kDexCachePcRelative:
2470 return os << "DexCachePcRelative";
2471 case HLoadString::LoadKind::kDexCacheViaMethod:
2472 return os << "DexCacheViaMethod";
2473 default:
2474 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2475 UNREACHABLE();
2476 }
2477}
2478
Mark Mendellc4701932015-04-10 13:18:51 -04002479void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002480 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2481 HEnvironment* user = use.GetUser();
2482 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002483 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002484 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002485}
2486
Roland Levillainc9b21f82016-03-23 16:36:59 +00002487// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002488HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2489 ArenaAllocator* allocator = GetArena();
2490
2491 if (cond->IsCondition() &&
2492 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2493 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2494 HInstruction* lhs = cond->InputAt(0);
2495 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002496 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002497 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2498 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2499 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2500 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2501 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2502 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2503 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2504 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2505 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2506 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2507 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002508 default:
2509 LOG(FATAL) << "Unexpected condition";
2510 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002511 }
2512 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2513 return replacement;
2514 } else if (cond->IsIntConstant()) {
2515 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002516 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002517 return GetIntConstant(1);
2518 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002519 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002520 return GetIntConstant(0);
2521 }
2522 } else {
2523 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2524 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2525 return replacement;
2526 }
2527}
2528
Roland Levillainc9285912015-12-18 10:38:42 +00002529std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2530 os << "["
2531 << " source=" << rhs.GetSource()
2532 << " destination=" << rhs.GetDestination()
2533 << " type=" << rhs.GetType()
2534 << " instruction=";
2535 if (rhs.GetInstruction() != nullptr) {
2536 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2537 } else {
2538 os << "null";
2539 }
2540 os << " ]";
2541 return os;
2542}
2543
Roland Levillain86503782016-02-11 19:07:30 +00002544std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2545 switch (rhs) {
2546 case TypeCheckKind::kUnresolvedCheck:
2547 return os << "unresolved_check";
2548 case TypeCheckKind::kExactCheck:
2549 return os << "exact_check";
2550 case TypeCheckKind::kClassHierarchyCheck:
2551 return os << "class_hierarchy_check";
2552 case TypeCheckKind::kAbstractClassCheck:
2553 return os << "abstract_class_check";
2554 case TypeCheckKind::kInterfaceCheck:
2555 return os << "interface_check";
2556 case TypeCheckKind::kArrayObjectCheck:
2557 return os << "array_object_check";
2558 case TypeCheckKind::kArrayCheck:
2559 return os << "array_check";
2560 default:
2561 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2562 UNREACHABLE();
2563 }
2564}
2565
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002566} // namespace art