blob: 60329ccff20258087d6c73a3936bfec4f30db7e7 [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 Geoffrayd7c2fdc2016-05-10 14:35:34 +0100449 // We iterate post order to ensure we visit inner loops before outer loops.
450 // `PopulateRecursive` needs this guarantee to know whether a natural loop
451 // contains an irreducible loop.
452 for (HPostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100453 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100455 if (block->IsCatchBlock()) {
456 // TODO: Dealing with exceptional back edges could be tricky because
457 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000458 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100459 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000460 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100461 }
462 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000463 return kAnalysisSuccess;
464}
465
466void HLoopInformation::Dump(std::ostream& os) {
467 os << "header: " << header_->GetBlockId() << std::endl;
468 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
469 for (HBasicBlock* block : back_edges_) {
470 os << "back edge: " << block->GetBlockId() << std::endl;
471 }
472 for (HBasicBlock* block : header_->GetPredecessors()) {
473 os << "predecessor: " << block->GetBlockId() << std::endl;
474 }
475 for (uint32_t idx : blocks_.Indexes()) {
476 os << " in loop: " << idx << std::endl;
477 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478}
479
David Brazdil8d5b8b22015-03-24 10:51:52 +0000480void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000481 // New constants are inserted before the SuspendCheck at the bottom of the
482 // entry block. Note that this method can be called from the graph builder and
483 // the entry block therefore may not end with SuspendCheck->Goto yet.
484 HInstruction* insert_before = nullptr;
485
486 HInstruction* gota = entry_block_->GetLastInstruction();
487 if (gota != nullptr && gota->IsGoto()) {
488 HInstruction* suspend_check = gota->GetPrevious();
489 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
490 insert_before = suspend_check;
491 } else {
492 insert_before = gota;
493 }
494 }
495
496 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000497 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000498 } else {
499 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000500 }
501}
502
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600503HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100504 // For simplicity, don't bother reviving the cached null constant if it is
505 // not null and not in a block. Otherwise, we need to clear the instruction
506 // id and/or any invariants the graph is assuming when adding new instructions.
507 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600508 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000509 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000510 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000511 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000512 if (kIsDebugBuild) {
513 ScopedObjectAccess soa(Thread::Current());
514 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
515 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000516 return cached_null_constant_;
517}
518
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100519HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100520 // For simplicity, don't bother reviving the cached current method if it is
521 // not null and not in a block. Otherwise, we need to clear the instruction
522 // id and/or any invariants the graph is assuming when adding new instructions.
523 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700524 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600525 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
526 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100527 if (entry_block_->GetFirstInstruction() == nullptr) {
528 entry_block_->AddInstruction(cached_current_method_);
529 } else {
530 entry_block_->InsertInstructionBefore(
531 cached_current_method_, entry_block_->GetFirstInstruction());
532 }
533 }
534 return cached_current_method_;
535}
536
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600537HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000538 switch (type) {
539 case Primitive::Type::kPrimBoolean:
540 DCHECK(IsUint<1>(value));
541 FALLTHROUGH_INTENDED;
542 case Primitive::Type::kPrimByte:
543 case Primitive::Type::kPrimChar:
544 case Primitive::Type::kPrimShort:
545 case Primitive::Type::kPrimInt:
546 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548
549 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600550 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000551
552 default:
553 LOG(FATAL) << "Unsupported constant type";
554 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000555 }
David Brazdil46e2a392015-03-16 17:31:52 +0000556}
557
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000558void HGraph::CacheFloatConstant(HFloatConstant* constant) {
559 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
560 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
561 cached_float_constants_.Overwrite(value, constant);
562}
563
564void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
565 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
566 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
567 cached_double_constants_.Overwrite(value, constant);
568}
569
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000570void HLoopInformation::Add(HBasicBlock* block) {
571 blocks_.SetBit(block->GetBlockId());
572}
573
David Brazdil46e2a392015-03-16 17:31:52 +0000574void HLoopInformation::Remove(HBasicBlock* block) {
575 blocks_.ClearBit(block->GetBlockId());
576}
577
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100578void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
579 if (blocks_.IsBitSet(block->GetBlockId())) {
580 return;
581 }
582
583 blocks_.SetBit(block->GetBlockId());
584 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100585 if (block->IsLoopHeader()) {
586 // We're visiting loops in post-order, so inner loops must have been
587 // populated already.
588 DCHECK(block->GetLoopInformation()->IsPopulated());
589 if (block->GetLoopInformation()->IsIrreducible()) {
590 contains_irreducible_loop_ = true;
591 }
592 }
Vladimir Marko60584552015-09-03 13:35:12 +0000593 for (HBasicBlock* predecessor : block->GetPredecessors()) {
594 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100595 }
596}
597
David Brazdilc2e8af92016-04-05 17:15:19 +0100598void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
599 size_t block_id = block->GetBlockId();
600
601 // If `block` is in `finalized`, we know its membership in the loop has been
602 // decided and it does not need to be revisited.
603 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000604 return;
605 }
606
David Brazdilc2e8af92016-04-05 17:15:19 +0100607 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 if (block->IsLoopHeader()) {
609 // If we hit a loop header in an irreducible loop, we first check if the
610 // pre header of that loop belongs to the currently analyzed loop. If it does,
611 // then we visit the back edges.
612 // Note that we cannot use GetPreHeader, as the loop may have not been populated
613 // yet.
614 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100615 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000616 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000617 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100618 blocks_.SetBit(block_id);
619 finalized->SetBit(block_id);
620 is_finalized = true;
621
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000622 HLoopInformation* info = block->GetLoopInformation();
623 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100624 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000625 }
626 }
627 } else {
628 // Visit all predecessors. If one predecessor is part of the loop, this
629 // block is also part of this loop.
630 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100631 PopulateIrreducibleRecursive(predecessor, finalized);
632 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000633 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100634 blocks_.SetBit(block_id);
635 finalized->SetBit(block_id);
636 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 }
638 }
639 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100640
641 // All predecessors have been recursively visited. Mark finalized if not marked yet.
642 if (!is_finalized) {
643 finalized->SetBit(block_id);
644 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000645}
646
647void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100648 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000649 // Populate this loop: starting with the back edge, recursively add predecessors
650 // that are not already part of that loop. Set the header as part of the loop
651 // to end the recursion.
652 // This is a recursive implementation of the algorithm described in
653 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100654 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 blocks_.SetBit(header_->GetBlockId());
656 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100657
David Brazdil3f4a5222016-05-06 12:46:21 +0100658 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100659
660 if (is_irreducible_loop) {
661 ArenaBitVector visited(graph->GetArena(),
662 graph->GetBlocks().size(),
663 /* expandable */ false,
664 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100665 // Stop marking blocks at the loop header.
666 visited.SetBit(header_->GetBlockId());
667
David Brazdilc2e8af92016-04-05 17:15:19 +0100668 for (HBasicBlock* back_edge : GetBackEdges()) {
669 PopulateIrreducibleRecursive(back_edge, &visited);
670 }
671 } else {
672 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000673 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100674 }
David Brazdila4b8c212015-05-07 09:59:30 +0100675 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100676
Vladimir Markofd66c502016-04-18 15:37:01 +0100677 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
678 // When compiling in OSR mode, all loops in the compiled method may be entered
679 // from the interpreter. We treat this OSR entry point just like an extra entry
680 // to an irreducible loop, so we need to mark the method's loops as irreducible.
681 // This does not apply to inlined loops which do not act as OSR entry points.
682 if (suspend_check_ == nullptr) {
683 // Just building the graph in OSR mode, this loop is not inlined. We never build an
684 // inner graph in OSR mode as we can do OSR transition only from the outer method.
685 is_irreducible_loop = true;
686 } else {
687 // Look at the suspend check's environment to determine if the loop was inlined.
688 DCHECK(suspend_check_->HasEnvironment());
689 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
690 is_irreducible_loop = true;
691 }
692 }
693 }
694 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100695 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100696 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100697 graph->SetHasIrreducibleLoops(true);
698 }
David Brazdila4b8c212015-05-07 09:59:30 +0100699}
700
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100701HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000702 HBasicBlock* block = header_->GetPredecessors()[0];
703 DCHECK(irreducible_ || (block == header_->GetDominator()));
704 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100705}
706
707bool HLoopInformation::Contains(const HBasicBlock& block) const {
708 return blocks_.IsBitSet(block.GetBlockId());
709}
710
711bool HLoopInformation::IsIn(const HLoopInformation& other) const {
712 return other.blocks_.IsBitSet(header_->GetBlockId());
713}
714
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800715bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
716 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700717}
718
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100719size_t HLoopInformation::GetLifetimeEnd() const {
720 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100721 for (HBasicBlock* back_edge : GetBackEdges()) {
722 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100723 }
724 return last_position;
725}
726
David Brazdil3f4a5222016-05-06 12:46:21 +0100727bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
728 for (HBasicBlock* back_edge : GetBackEdges()) {
729 DCHECK(back_edge->GetDominator() != nullptr);
730 if (!header_->Dominates(back_edge)) {
731 return true;
732 }
733 }
734 return false;
735}
736
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100737bool HBasicBlock::Dominates(HBasicBlock* other) const {
738 // Walk up the dominator tree from `other`, to find out if `this`
739 // is an ancestor.
740 HBasicBlock* current = other;
741 while (current != nullptr) {
742 if (current == this) {
743 return true;
744 }
745 current = current->GetDominator();
746 }
747 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100748}
749
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100750static void UpdateInputsUsers(HInstruction* instruction) {
751 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
752 instruction->InputAt(i)->AddUseAt(instruction, i);
753 }
754 // Environment should be created later.
755 DCHECK(!instruction->HasEnvironment());
756}
757
Roland Levillainccc07a92014-09-16 14:48:16 +0100758void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
759 HInstruction* replacement) {
760 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400761 if (initial->IsControlFlow()) {
762 // We can only replace a control flow instruction with another control flow instruction.
763 DCHECK(replacement->IsControlFlow());
764 DCHECK_EQ(replacement->GetId(), -1);
765 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
766 DCHECK_EQ(initial->GetBlock(), this);
767 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100768 DCHECK(initial->GetUses().empty());
769 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400770 replacement->SetBlock(this);
771 replacement->SetId(GetGraph()->GetNextInstructionId());
772 instructions_.InsertInstructionBefore(replacement, initial);
773 UpdateInputsUsers(replacement);
774 } else {
775 InsertInstructionBefore(replacement, initial);
776 initial->ReplaceWith(replacement);
777 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100778 RemoveInstruction(initial);
779}
780
David Brazdil74eb1b22015-12-14 11:44:01 +0000781void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
782 DCHECK(!cursor->IsPhi());
783 DCHECK(!insn->IsPhi());
784 DCHECK(!insn->IsControlFlow());
785 DCHECK(insn->CanBeMoved());
786 DCHECK(!insn->HasSideEffects());
787
788 HBasicBlock* from_block = insn->GetBlock();
789 HBasicBlock* to_block = cursor->GetBlock();
790 DCHECK(from_block != to_block);
791
792 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
793 insn->SetBlock(to_block);
794 to_block->instructions_.InsertInstructionBefore(insn, cursor);
795}
796
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100797static void Add(HInstructionList* instruction_list,
798 HBasicBlock* block,
799 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000800 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000801 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802 instruction->SetBlock(block);
803 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100804 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100805 instruction_list->AddInstruction(instruction);
806}
807
808void HBasicBlock::AddInstruction(HInstruction* instruction) {
809 Add(&instructions_, this, instruction);
810}
811
812void HBasicBlock::AddPhi(HPhi* phi) {
813 Add(&phis_, this, phi);
814}
815
David Brazdilc3d743f2015-04-22 13:40:50 +0100816void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
817 DCHECK(!cursor->IsPhi());
818 DCHECK(!instruction->IsPhi());
819 DCHECK_EQ(instruction->GetId(), -1);
820 DCHECK_NE(cursor->GetId(), -1);
821 DCHECK_EQ(cursor->GetBlock(), this);
822 DCHECK(!instruction->IsControlFlow());
823 instruction->SetBlock(this);
824 instruction->SetId(GetGraph()->GetNextInstructionId());
825 UpdateInputsUsers(instruction);
826 instructions_.InsertInstructionBefore(instruction, cursor);
827}
828
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100829void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
830 DCHECK(!cursor->IsPhi());
831 DCHECK(!instruction->IsPhi());
832 DCHECK_EQ(instruction->GetId(), -1);
833 DCHECK_NE(cursor->GetId(), -1);
834 DCHECK_EQ(cursor->GetBlock(), this);
835 DCHECK(!instruction->IsControlFlow());
836 DCHECK(!cursor->IsControlFlow());
837 instruction->SetBlock(this);
838 instruction->SetId(GetGraph()->GetNextInstructionId());
839 UpdateInputsUsers(instruction);
840 instructions_.InsertInstructionAfter(instruction, cursor);
841}
842
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100843void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
844 DCHECK_EQ(phi->GetId(), -1);
845 DCHECK_NE(cursor->GetId(), -1);
846 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100847 phi->SetBlock(this);
848 phi->SetId(GetGraph()->GetNextInstructionId());
849 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100850 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100851}
852
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100853static void Remove(HInstructionList* instruction_list,
854 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000855 HInstruction* instruction,
856 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100857 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100858 instruction->SetBlock(nullptr);
859 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000860 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100861 DCHECK(instruction->GetUses().empty());
862 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000863 RemoveAsUser(instruction);
864 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865}
866
David Brazdil1abb4192015-02-17 18:33:36 +0000867void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100868 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000869 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870}
871
David Brazdil1abb4192015-02-17 18:33:36 +0000872void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
873 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100874}
875
David Brazdilc7508e92015-04-27 13:28:57 +0100876void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
877 if (instruction->IsPhi()) {
878 RemovePhi(instruction->AsPhi(), ensure_safety);
879 } else {
880 RemoveInstruction(instruction, ensure_safety);
881 }
882}
883
Vladimir Marko71bf8092015-09-15 15:33:14 +0100884void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
885 for (size_t i = 0; i < locals.size(); i++) {
886 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100887 SetRawEnvAt(i, instruction);
888 if (instruction != nullptr) {
889 instruction->AddEnvUseAt(this, i);
890 }
891 }
892}
893
David Brazdiled596192015-01-23 10:39:45 +0000894void HEnvironment::CopyFrom(HEnvironment* env) {
895 for (size_t i = 0; i < env->Size(); i++) {
896 HInstruction* instruction = env->GetInstructionAt(i);
897 SetRawEnvAt(i, instruction);
898 if (instruction != nullptr) {
899 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100900 }
David Brazdiled596192015-01-23 10:39:45 +0000901 }
902}
903
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700904void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
905 HBasicBlock* loop_header) {
906 DCHECK(loop_header->IsLoopHeader());
907 for (size_t i = 0; i < env->Size(); i++) {
908 HInstruction* instruction = env->GetInstructionAt(i);
909 SetRawEnvAt(i, instruction);
910 if (instruction == nullptr) {
911 continue;
912 }
913 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
914 // At the end of the loop pre-header, the corresponding value for instruction
915 // is the first input of the phi.
916 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700917 SetRawEnvAt(i, initial);
918 initial->AddEnvUseAt(this, i);
919 } else {
920 instruction->AddEnvUseAt(this, i);
921 }
922 }
923}
924
David Brazdil1abb4192015-02-17 18:33:36 +0000925void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100926 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
927 HInstruction* user = env_use.GetInstruction();
928 auto before_env_use_node = env_use.GetBeforeUseNode();
929 user->env_uses_.erase_after(before_env_use_node);
930 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931}
932
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000933HInstruction::InstructionKind HInstruction::GetKind() const {
934 return GetKindInternal();
935}
936
Calin Juravle77520bc2015-01-12 18:45:46 +0000937HInstruction* HInstruction::GetNextDisregardingMoves() const {
938 HInstruction* next = GetNext();
939 while (next != nullptr && next->IsParallelMove()) {
940 next = next->GetNext();
941 }
942 return next;
943}
944
945HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
946 HInstruction* previous = GetPrevious();
947 while (previous != nullptr && previous->IsParallelMove()) {
948 previous = previous->GetPrevious();
949 }
950 return previous;
951}
952
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100953void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000954 if (first_instruction_ == nullptr) {
955 DCHECK(last_instruction_ == nullptr);
956 first_instruction_ = last_instruction_ = instruction;
957 } else {
958 last_instruction_->next_ = instruction;
959 instruction->previous_ = last_instruction_;
960 last_instruction_ = instruction;
961 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000962}
963
David Brazdilc3d743f2015-04-22 13:40:50 +0100964void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
965 DCHECK(Contains(cursor));
966 if (cursor == first_instruction_) {
967 cursor->previous_ = instruction;
968 instruction->next_ = cursor;
969 first_instruction_ = instruction;
970 } else {
971 instruction->previous_ = cursor->previous_;
972 instruction->next_ = cursor;
973 cursor->previous_ = instruction;
974 instruction->previous_->next_ = instruction;
975 }
976}
977
978void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
979 DCHECK(Contains(cursor));
980 if (cursor == last_instruction_) {
981 cursor->next_ = instruction;
982 instruction->previous_ = cursor;
983 last_instruction_ = instruction;
984 } else {
985 instruction->next_ = cursor->next_;
986 instruction->previous_ = cursor;
987 cursor->next_ = instruction;
988 instruction->next_->previous_ = instruction;
989 }
990}
991
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100992void HInstructionList::RemoveInstruction(HInstruction* instruction) {
993 if (instruction->previous_ != nullptr) {
994 instruction->previous_->next_ = instruction->next_;
995 }
996 if (instruction->next_ != nullptr) {
997 instruction->next_->previous_ = instruction->previous_;
998 }
999 if (instruction == first_instruction_) {
1000 first_instruction_ = instruction->next_;
1001 }
1002 if (instruction == last_instruction_) {
1003 last_instruction_ = instruction->previous_;
1004 }
1005}
1006
Roland Levillain6b469232014-09-25 10:10:38 +01001007bool HInstructionList::Contains(HInstruction* instruction) const {
1008 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1009 if (it.Current() == instruction) {
1010 return true;
1011 }
1012 }
1013 return false;
1014}
1015
Roland Levillainccc07a92014-09-16 14:48:16 +01001016bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1017 const HInstruction* instruction2) const {
1018 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1019 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1020 if (it.Current() == instruction1) {
1021 return true;
1022 }
1023 if (it.Current() == instruction2) {
1024 return false;
1025 }
1026 }
1027 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1028 return true;
1029}
1030
Roland Levillain6c82d402014-10-13 16:10:27 +01001031bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1032 if (other_instruction == this) {
1033 // An instruction does not strictly dominate itself.
1034 return false;
1035 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001036 HBasicBlock* block = GetBlock();
1037 HBasicBlock* other_block = other_instruction->GetBlock();
1038 if (block != other_block) {
1039 return GetBlock()->Dominates(other_instruction->GetBlock());
1040 } else {
1041 // If both instructions are in the same block, ensure this
1042 // instruction comes before `other_instruction`.
1043 if (IsPhi()) {
1044 if (!other_instruction->IsPhi()) {
1045 // Phis appear before non phi-instructions so this instruction
1046 // dominates `other_instruction`.
1047 return true;
1048 } else {
1049 // There is no order among phis.
1050 LOG(FATAL) << "There is no dominance between phis of a same block.";
1051 return false;
1052 }
1053 } else {
1054 // `this` is not a phi.
1055 if (other_instruction->IsPhi()) {
1056 // Phis appear before non phi-instructions so this instruction
1057 // does not dominate `other_instruction`.
1058 return false;
1059 } else {
1060 // Check whether this instruction comes before
1061 // `other_instruction` in the instruction list.
1062 return block->GetInstructions().FoundBefore(this, other_instruction);
1063 }
1064 }
1065 }
1066}
1067
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001068void HInstruction::RemoveEnvironment() {
1069 RemoveEnvironmentUses(this);
1070 environment_ = nullptr;
1071}
1072
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001073void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001074 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001075 // Note: fixup_end remains valid across splice_after().
1076 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1077 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1078 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001079
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001080 // Note: env_fixup_end remains valid across splice_after().
1081 auto env_fixup_end =
1082 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1083 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1084 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001085
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001086 DCHECK(uses_.empty());
1087 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001088}
1089
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001090void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001091 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001092 if (input_use.GetInstruction() == replacement) {
1093 // Nothing to do.
1094 return;
1095 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001096 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001097 // Note: fixup_end remains valid across splice_after().
1098 auto fixup_end =
1099 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1100 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1101 input_use.GetInstruction()->uses_,
1102 before_use_node);
1103 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1104 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001105}
1106
Nicolas Geoffray39468442014-09-02 15:17:15 +01001107size_t HInstruction::EnvironmentSize() const {
1108 return HasEnvironment() ? environment_->Size() : 0;
1109}
1110
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001111void HPhi::AddInput(HInstruction* input) {
1112 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001113 inputs_.push_back(HUserRecord<HInstruction*>(input));
1114 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001115}
1116
David Brazdil2d7352b2015-04-20 14:52:42 +01001117void HPhi::RemoveInputAt(size_t index) {
1118 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001119 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001120 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001121 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001122 InputRecordAt(i).GetUseNode()->SetIndex(i);
1123 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001124}
1125
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001126#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001127void H##name::Accept(HGraphVisitor* visitor) { \
1128 visitor->Visit##name(this); \
1129}
1130
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001131FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001132
1133#undef DEFINE_ACCEPT
1134
1135void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001136 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1137 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001138 if (block != nullptr) {
1139 VisitBasicBlock(block);
1140 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001141 }
1142}
1143
Roland Levillain633021e2014-10-01 14:12:25 +01001144void HGraphVisitor::VisitReversePostOrder() {
1145 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1146 VisitBasicBlock(it.Current());
1147 }
1148}
1149
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001150void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001151 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001152 it.Current()->Accept(this);
1153 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001154 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001155 it.Current()->Accept(this);
1156 }
1157}
1158
Mark Mendelle82549b2015-05-06 10:55:34 -04001159HConstant* HTypeConversion::TryStaticEvaluation() const {
1160 HGraph* graph = GetBlock()->GetGraph();
1161 if (GetInput()->IsIntConstant()) {
1162 int32_t value = GetInput()->AsIntConstant()->GetValue();
1163 switch (GetResultType()) {
1164 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001165 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001166 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001167 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001168 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001169 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001170 default:
1171 return nullptr;
1172 }
1173 } else if (GetInput()->IsLongConstant()) {
1174 int64_t value = GetInput()->AsLongConstant()->GetValue();
1175 switch (GetResultType()) {
1176 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001177 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001178 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001179 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001180 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001181 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001182 default:
1183 return nullptr;
1184 }
1185 } else if (GetInput()->IsFloatConstant()) {
1186 float value = GetInput()->AsFloatConstant()->GetValue();
1187 switch (GetResultType()) {
1188 case Primitive::kPrimInt:
1189 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001190 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001191 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001192 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001193 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001194 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1195 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001196 case Primitive::kPrimLong:
1197 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001198 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001199 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001200 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001201 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001202 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1203 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001204 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001205 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001206 default:
1207 return nullptr;
1208 }
1209 } else if (GetInput()->IsDoubleConstant()) {
1210 double value = GetInput()->AsDoubleConstant()->GetValue();
1211 switch (GetResultType()) {
1212 case Primitive::kPrimInt:
1213 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001214 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001215 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001216 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001217 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001218 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1219 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001220 case Primitive::kPrimLong:
1221 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001222 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001223 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001224 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001225 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001226 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1227 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001228 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001229 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001230 default:
1231 return nullptr;
1232 }
1233 }
1234 return nullptr;
1235}
1236
Roland Levillain9240d6a2014-10-20 16:47:04 +01001237HConstant* HUnaryOperation::TryStaticEvaluation() const {
1238 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001239 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001240 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001241 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001242 } else if (kEnableFloatingPointStaticEvaluation) {
1243 if (GetInput()->IsFloatConstant()) {
1244 return Evaluate(GetInput()->AsFloatConstant());
1245 } else if (GetInput()->IsDoubleConstant()) {
1246 return Evaluate(GetInput()->AsDoubleConstant());
1247 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001248 }
1249 return nullptr;
1250}
1251
1252HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001253 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1254 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001255 } else if (GetLeft()->IsLongConstant()) {
1256 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001257 // The binop(long, int) case is only valid for shifts and rotations.
1258 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001259 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1260 } else if (GetRight()->IsLongConstant()) {
1261 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001262 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001263 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001264 // The binop(null, null) case is only valid for equal and not-equal conditions.
1265 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001266 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001267 } else if (kEnableFloatingPointStaticEvaluation) {
1268 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1269 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1270 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1271 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1272 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001273 }
1274 return nullptr;
1275}
Dave Allison20dfc792014-06-16 20:44:29 -07001276
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001277HConstant* HBinaryOperation::GetConstantRight() const {
1278 if (GetRight()->IsConstant()) {
1279 return GetRight()->AsConstant();
1280 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1281 return GetLeft()->AsConstant();
1282 } else {
1283 return nullptr;
1284 }
1285}
1286
1287// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001288// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001289HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1290 HInstruction* most_constant_right = GetConstantRight();
1291 if (most_constant_right == nullptr) {
1292 return nullptr;
1293 } else if (most_constant_right == GetLeft()) {
1294 return GetRight();
1295 } else {
1296 return GetLeft();
1297 }
1298}
1299
Roland Levillain31dd3d62016-02-16 12:21:02 +00001300std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1301 switch (rhs) {
1302 case ComparisonBias::kNoBias:
1303 return os << "no_bias";
1304 case ComparisonBias::kGtBias:
1305 return os << "gt_bias";
1306 case ComparisonBias::kLtBias:
1307 return os << "lt_bias";
1308 default:
1309 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1310 UNREACHABLE();
1311 }
1312}
1313
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001314bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1315 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001316}
1317
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001318bool HInstruction::Equals(HInstruction* other) const {
1319 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001320 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001321 if (!InstructionDataEquals(other)) return false;
1322 if (GetType() != other->GetType()) return false;
1323 if (InputCount() != other->InputCount()) return false;
1324
1325 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1326 if (InputAt(i) != other->InputAt(i)) return false;
1327 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001328 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001329 return true;
1330}
1331
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001332std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1333#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1334 switch (rhs) {
1335 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1336 default:
1337 os << "Unknown instruction kind " << static_cast<int>(rhs);
1338 break;
1339 }
1340#undef DECLARE_CASE
1341 return os;
1342}
1343
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001344void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001345 next_->previous_ = previous_;
1346 if (previous_ != nullptr) {
1347 previous_->next_ = next_;
1348 }
1349 if (block_->instructions_.first_instruction_ == this) {
1350 block_->instructions_.first_instruction_ = next_;
1351 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001352 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001353
1354 previous_ = cursor->previous_;
1355 if (previous_ != nullptr) {
1356 previous_->next_ = this;
1357 }
1358 next_ = cursor;
1359 cursor->previous_ = this;
1360 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001361
1362 if (block_->instructions_.first_instruction_ == cursor) {
1363 block_->instructions_.first_instruction_ = this;
1364 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001365}
1366
Vladimir Markofb337ea2015-11-25 15:25:10 +00001367void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1368 DCHECK(!CanThrow());
1369 DCHECK(!HasSideEffects());
1370 DCHECK(!HasEnvironmentUses());
1371 DCHECK(HasNonEnvironmentUses());
1372 DCHECK(!IsPhi()); // Makes no sense for Phi.
1373 DCHECK_EQ(InputCount(), 0u);
1374
1375 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001376 auto uses_it = GetUses().begin();
1377 auto uses_end = GetUses().end();
1378 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1379 ++uses_it;
1380 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1381 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001382 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001383 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001384 // This instruction has uses in two or more blocks. Find the common dominator.
1385 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001386 for (; uses_it != uses_end; ++uses_it) {
1387 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001388 }
1389 target_block = finder.Get();
1390 DCHECK(target_block != nullptr);
1391 }
1392 // Move to the first dominator not in a loop.
1393 while (target_block->IsInLoop()) {
1394 target_block = target_block->GetDominator();
1395 DCHECK(target_block != nullptr);
1396 }
1397
1398 // Find insertion position.
1399 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001400 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1401 if (use.GetUser()->GetBlock() == target_block &&
1402 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1403 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001404 }
1405 }
1406 if (insert_pos == nullptr) {
1407 // No user in `target_block`, insert before the control flow instruction.
1408 insert_pos = target_block->GetLastInstruction();
1409 DCHECK(insert_pos->IsControlFlow());
1410 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1411 if (insert_pos->IsIf()) {
1412 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1413 if (if_input == insert_pos->GetPrevious()) {
1414 insert_pos = if_input;
1415 }
1416 }
1417 }
1418 MoveBefore(insert_pos);
1419}
1420
David Brazdilfc6a86a2015-06-26 10:33:45 +00001421HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001422 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001423 DCHECK_EQ(cursor->GetBlock(), this);
1424
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001425 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1426 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001427 new_block->instructions_.first_instruction_ = cursor;
1428 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1429 instructions_.last_instruction_ = cursor->previous_;
1430 if (cursor->previous_ == nullptr) {
1431 instructions_.first_instruction_ = nullptr;
1432 } else {
1433 cursor->previous_->next_ = nullptr;
1434 cursor->previous_ = nullptr;
1435 }
1436
1437 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001438 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001439
Vladimir Marko60584552015-09-03 13:35:12 +00001440 for (HBasicBlock* successor : GetSuccessors()) {
1441 new_block->successors_.push_back(successor);
1442 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001443 }
Vladimir Marko60584552015-09-03 13:35:12 +00001444 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001445 AddSuccessor(new_block);
1446
David Brazdil56e1acc2015-06-30 15:41:36 +01001447 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001448 return new_block;
1449}
1450
David Brazdild7558da2015-09-22 13:04:14 +01001451HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001452 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001453 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1454
1455 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1456
1457 for (HBasicBlock* predecessor : GetPredecessors()) {
1458 new_block->predecessors_.push_back(predecessor);
1459 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1460 }
1461 predecessors_.clear();
1462 AddPredecessor(new_block);
1463
1464 GetGraph()->AddBlock(new_block);
1465 return new_block;
1466}
1467
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001468HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1469 DCHECK_EQ(cursor->GetBlock(), this);
1470
1471 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1472 cursor->GetDexPc());
1473 new_block->instructions_.first_instruction_ = cursor;
1474 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1475 instructions_.last_instruction_ = cursor->previous_;
1476 if (cursor->previous_ == nullptr) {
1477 instructions_.first_instruction_ = nullptr;
1478 } else {
1479 cursor->previous_->next_ = nullptr;
1480 cursor->previous_ = nullptr;
1481 }
1482
1483 new_block->instructions_.SetBlockOfInstructions(new_block);
1484
1485 for (HBasicBlock* successor : GetSuccessors()) {
1486 new_block->successors_.push_back(successor);
1487 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1488 }
1489 successors_.clear();
1490
1491 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1492 dominated->dominator_ = new_block;
1493 new_block->dominated_blocks_.push_back(dominated);
1494 }
1495 dominated_blocks_.clear();
1496 return new_block;
1497}
1498
1499HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001500 DCHECK(!cursor->IsControlFlow());
1501 DCHECK_NE(instructions_.last_instruction_, cursor);
1502 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001503
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001504 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1505 new_block->instructions_.first_instruction_ = cursor->GetNext();
1506 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1507 cursor->next_->previous_ = nullptr;
1508 cursor->next_ = nullptr;
1509 instructions_.last_instruction_ = cursor;
1510
1511 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001512 for (HBasicBlock* successor : GetSuccessors()) {
1513 new_block->successors_.push_back(successor);
1514 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001515 }
Vladimir Marko60584552015-09-03 13:35:12 +00001516 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001517
Vladimir Marko60584552015-09-03 13:35:12 +00001518 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001519 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001520 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001521 }
Vladimir Marko60584552015-09-03 13:35:12 +00001522 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001523 return new_block;
1524}
1525
David Brazdilec16f792015-08-19 15:04:01 +01001526const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001527 if (EndsWithTryBoundary()) {
1528 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1529 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001530 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001531 return try_boundary;
1532 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001533 DCHECK(IsTryBlock());
1534 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001535 return nullptr;
1536 }
David Brazdilec16f792015-08-19 15:04:01 +01001537 } else if (IsTryBlock()) {
1538 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001539 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001540 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001541 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001542}
1543
David Brazdild7558da2015-09-22 13:04:14 +01001544bool HBasicBlock::HasThrowingInstructions() const {
1545 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1546 if (it.Current()->CanThrow()) {
1547 return true;
1548 }
1549 }
1550 return false;
1551}
1552
David Brazdilfc6a86a2015-06-26 10:33:45 +00001553static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1554 return block.GetPhis().IsEmpty()
1555 && !block.GetInstructions().IsEmpty()
1556 && block.GetFirstInstruction() == block.GetLastInstruction();
1557}
1558
David Brazdil46e2a392015-03-16 17:31:52 +00001559bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001560 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1561}
1562
1563bool HBasicBlock::IsSingleTryBoundary() const {
1564 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001565}
1566
David Brazdil8d5b8b22015-03-24 10:51:52 +00001567bool HBasicBlock::EndsWithControlFlowInstruction() const {
1568 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1569}
1570
David Brazdilb2bd1c52015-03-25 11:17:37 +00001571bool HBasicBlock::EndsWithIf() const {
1572 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1573}
1574
David Brazdilffee3d32015-07-06 11:48:53 +01001575bool HBasicBlock::EndsWithTryBoundary() const {
1576 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1577}
1578
David Brazdilb2bd1c52015-03-25 11:17:37 +00001579bool HBasicBlock::HasSinglePhi() const {
1580 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1581}
1582
David Brazdild26a4112015-11-10 11:07:31 +00001583ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1584 if (EndsWithTryBoundary()) {
1585 // The normal-flow successor of HTryBoundary is always stored at index zero.
1586 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1587 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1588 } else {
1589 // All successors of blocks not ending with TryBoundary are normal.
1590 return ArrayRef<HBasicBlock* const>(successors_);
1591 }
1592}
1593
1594ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1595 if (EndsWithTryBoundary()) {
1596 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1597 } else {
1598 // Blocks not ending with TryBoundary do not have exceptional successors.
1599 return ArrayRef<HBasicBlock* const>();
1600 }
1601}
1602
David Brazdilffee3d32015-07-06 11:48:53 +01001603bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001604 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1605 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1606
1607 size_t length = handlers1.size();
1608 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001609 return false;
1610 }
1611
David Brazdilb618ade2015-07-29 10:31:29 +01001612 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001613 for (size_t i = 0; i < length; ++i) {
1614 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001615 return false;
1616 }
1617 }
1618 return true;
1619}
1620
David Brazdil2d7352b2015-04-20 14:52:42 +01001621size_t HInstructionList::CountSize() const {
1622 size_t size = 0;
1623 HInstruction* current = first_instruction_;
1624 for (; current != nullptr; current = current->GetNext()) {
1625 size++;
1626 }
1627 return size;
1628}
1629
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001630void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1631 for (HInstruction* current = first_instruction_;
1632 current != nullptr;
1633 current = current->GetNext()) {
1634 current->SetBlock(block);
1635 }
1636}
1637
1638void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1639 DCHECK(Contains(cursor));
1640 if (!instruction_list.IsEmpty()) {
1641 if (cursor == last_instruction_) {
1642 last_instruction_ = instruction_list.last_instruction_;
1643 } else {
1644 cursor->next_->previous_ = instruction_list.last_instruction_;
1645 }
1646 instruction_list.last_instruction_->next_ = cursor->next_;
1647 cursor->next_ = instruction_list.first_instruction_;
1648 instruction_list.first_instruction_->previous_ = cursor;
1649 }
1650}
1651
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001652void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1653 DCHECK(Contains(cursor));
1654 if (!instruction_list.IsEmpty()) {
1655 if (cursor == first_instruction_) {
1656 first_instruction_ = instruction_list.first_instruction_;
1657 } else {
1658 cursor->previous_->next_ = instruction_list.first_instruction_;
1659 }
1660 instruction_list.last_instruction_->next_ = cursor;
1661 instruction_list.first_instruction_->previous_ = cursor->previous_;
1662 cursor->previous_ = instruction_list.last_instruction_;
1663 }
1664}
1665
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001666void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001667 if (IsEmpty()) {
1668 first_instruction_ = instruction_list.first_instruction_;
1669 last_instruction_ = instruction_list.last_instruction_;
1670 } else {
1671 AddAfter(last_instruction_, instruction_list);
1672 }
1673}
1674
David Brazdil04ff4e82015-12-10 13:54:52 +00001675// Should be called on instructions in a dead block in post order. This method
1676// assumes `insn` has been removed from all users with the exception of catch
1677// phis because of missing exceptional edges in the graph. It removes the
1678// instruction from catch phi uses, together with inputs of other catch phis in
1679// the catch block at the same index, as these must be dead too.
1680static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1681 DCHECK(!insn->HasEnvironmentUses());
1682 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001683 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1684 size_t use_index = use.GetIndex();
1685 HBasicBlock* user_block = use.GetUser()->GetBlock();
1686 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001687 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1688 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1689 }
1690 }
1691}
1692
David Brazdil2d7352b2015-04-20 14:52:42 +01001693void HBasicBlock::DisconnectAndDelete() {
1694 // Dominators must be removed after all the blocks they dominate. This way
1695 // a loop header is removed last, a requirement for correct loop information
1696 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001697 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001698
David Brazdil9eeebf62016-03-24 11:18:15 +00001699 // The following steps gradually remove the block from all its dependants in
1700 // post order (b/27683071).
1701
1702 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1703 // We need to do this before step (4) which destroys the predecessor list.
1704 HBasicBlock* loop_update_start = this;
1705 if (IsLoopHeader()) {
1706 HLoopInformation* loop_info = GetLoopInformation();
1707 // All other blocks in this loop should have been removed because the header
1708 // was their dominator.
1709 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1710 DCHECK(!loop_info->IsIrreducible());
1711 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1712 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1713 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 }
1715
David Brazdil9eeebf62016-03-24 11:18:15 +00001716 // (2) Disconnect the block from its successors and update their phis.
1717 for (HBasicBlock* successor : successors_) {
1718 // Delete this block from the list of predecessors.
1719 size_t this_index = successor->GetPredecessorIndexOf(this);
1720 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1721
1722 // Check that `successor` has other predecessors, otherwise `this` is the
1723 // dominator of `successor` which violates the order DCHECKed at the top.
1724 DCHECK(!successor->predecessors_.empty());
1725
1726 // Remove this block's entries in the successor's phis. Skip exceptional
1727 // successors because catch phi inputs do not correspond to predecessor
1728 // blocks but throwing instructions. The inputs of the catch phis will be
1729 // updated in step (3).
1730 if (!successor->IsCatchBlock()) {
1731 if (successor->predecessors_.size() == 1u) {
1732 // The successor has just one predecessor left. Replace phis with the only
1733 // remaining input.
1734 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1735 HPhi* phi = phi_it.Current()->AsPhi();
1736 phi->ReplaceWith(phi->InputAt(1 - this_index));
1737 successor->RemovePhi(phi);
1738 }
1739 } else {
1740 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1741 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1742 }
1743 }
1744 }
1745 }
1746 successors_.clear();
1747
1748 // (3) Remove instructions and phis. Instructions should have no remaining uses
1749 // except in catch phis. If an instruction is used by a catch phi at `index`,
1750 // remove `index`-th input of all phis in the catch block since they are
1751 // guaranteed dead. Note that we may miss dead inputs this way but the
1752 // graph will always remain consistent.
1753 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1754 HInstruction* insn = it.Current();
1755 RemoveUsesOfDeadInstruction(insn);
1756 RemoveInstruction(insn);
1757 }
1758 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1759 HPhi* insn = it.Current()->AsPhi();
1760 RemoveUsesOfDeadInstruction(insn);
1761 RemovePhi(insn);
1762 }
1763
1764 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001765 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001766 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001767 // We should not see any back edges as they would have been removed by step (3).
1768 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1769
David Brazdil2d7352b2015-04-20 14:52:42 +01001770 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001771 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1772 // This block is the only normal-flow successor of the TryBoundary which
1773 // makes `predecessor` dead. Since DCE removes blocks in post order,
1774 // exception handlers of this TryBoundary were already visited and any
1775 // remaining handlers therefore must be live. We remove `predecessor` from
1776 // their list of predecessors.
1777 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1778 while (predecessor->GetSuccessors().size() > 1) {
1779 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1780 DCHECK(handler->IsCatchBlock());
1781 predecessor->RemoveSuccessor(handler);
1782 handler->RemovePredecessor(predecessor);
1783 }
1784 }
1785
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001787 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1788 if (num_pred_successors == 1u) {
1789 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001790 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1791 // successor. Replace those with a HGoto.
1792 DCHECK(last_instruction->IsIf() ||
1793 last_instruction->IsPackedSwitch() ||
1794 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001795 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001796 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001797 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001798 // The predecessor has no remaining successors and therefore must be dead.
1799 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001800 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001801 predecessor->RemoveInstruction(last_instruction);
1802 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001803 // There are multiple successors left. The removed block might be a successor
1804 // of a PackedSwitch which will be completely removed (perhaps replaced with
1805 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1806 // case, leave `last_instruction` as is for now.
1807 DCHECK(last_instruction->IsPackedSwitch() ||
1808 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001809 }
David Brazdil46e2a392015-03-16 17:31:52 +00001810 }
Vladimir Marko60584552015-09-03 13:35:12 +00001811 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001812
David Brazdil9eeebf62016-03-24 11:18:15 +00001813 // (5) Remove the block from all loops it is included in. Skip the inner-most
1814 // loop if this is the loop header (see definition of `loop_update_start`)
1815 // because the loop header's predecessor list has been destroyed in step (4).
1816 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1817 HLoopInformation* loop_info = it.Current();
1818 loop_info->Remove(this);
1819 if (loop_info->IsBackEdge(*this)) {
1820 // If this was the last back edge of the loop, we deliberately leave the
1821 // loop in an inconsistent state and will fail GraphChecker unless the
1822 // entire loop is removed during the pass.
1823 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001824 }
1825 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001826
David Brazdil9eeebf62016-03-24 11:18:15 +00001827 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001828 dominator_->RemoveDominatedBlock(this);
1829 SetDominator(nullptr);
1830
David Brazdil9eeebf62016-03-24 11:18:15 +00001831 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001832 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001833 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001834}
1835
1836void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001837 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001838 DCHECK(ContainsElement(dominated_blocks_, other));
1839 DCHECK_EQ(GetSingleSuccessor(), other);
1840 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001841 DCHECK(other->GetPhis().IsEmpty());
1842
David Brazdil2d7352b2015-04-20 14:52:42 +01001843 // Move instructions from `other` to `this`.
1844 DCHECK(EndsWithControlFlowInstruction());
1845 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001846 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001847 other->instructions_.SetBlockOfInstructions(this);
1848 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001849
David Brazdil2d7352b2015-04-20 14:52:42 +01001850 // Remove `other` from the loops it is included in.
1851 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1852 HLoopInformation* loop_info = it.Current();
1853 loop_info->Remove(other);
1854 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001855 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001856 }
1857 }
1858
1859 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001860 successors_.clear();
1861 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001862 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001863 successor->ReplacePredecessor(other, this);
1864 }
1865
David Brazdil2d7352b2015-04-20 14:52:42 +01001866 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001867 RemoveDominatedBlock(other);
1868 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1869 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001870 dominated->SetDominator(this);
1871 }
Vladimir Marko60584552015-09-03 13:35:12 +00001872 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001873 other->dominator_ = nullptr;
1874
1875 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001876 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001877
1878 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001879 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001880 other->SetGraph(nullptr);
1881}
1882
1883void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1884 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001885 DCHECK(GetDominatedBlocks().empty());
1886 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001887 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001888 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001889 DCHECK(other->GetPhis().IsEmpty());
1890 DCHECK(!other->IsInLoop());
1891
1892 // Move instructions from `other` to `this`.
1893 instructions_.Add(other->GetInstructions());
1894 other->instructions_.SetBlockOfInstructions(this);
1895
1896 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001897 successors_.clear();
1898 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001899 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001900 successor->ReplacePredecessor(other, this);
1901 }
1902
1903 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001904 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1905 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001906 dominated->SetDominator(this);
1907 }
Vladimir Marko60584552015-09-03 13:35:12 +00001908 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001909 other->dominator_ = nullptr;
1910 other->graph_ = nullptr;
1911}
1912
1913void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001914 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001915 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 predecessor->ReplaceSuccessor(this, other);
1917 }
Vladimir Marko60584552015-09-03 13:35:12 +00001918 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001919 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001920 successor->ReplacePredecessor(this, other);
1921 }
Vladimir Marko60584552015-09-03 13:35:12 +00001922 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1923 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001924 }
1925 GetDominator()->ReplaceDominatedBlock(this, other);
1926 other->SetDominator(GetDominator());
1927 dominator_ = nullptr;
1928 graph_ = nullptr;
1929}
1930
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001931void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001932 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001933 DCHECK(block->GetSuccessors().empty());
1934 DCHECK(block->GetPredecessors().empty());
1935 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001936 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001937 DCHECK(block->GetInstructions().IsEmpty());
1938 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001939
David Brazdilc7af85d2015-05-26 12:05:55 +01001940 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001941 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001942 }
1943
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001944 RemoveElement(reverse_post_order_, block);
1945 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001946 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001947}
1948
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001949void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1950 HBasicBlock* reference,
1951 bool replace_if_back_edge) {
1952 if (block->IsLoopHeader()) {
1953 // Clear the information of which blocks are contained in that loop. Since the
1954 // information is stored as a bit vector based on block ids, we have to update
1955 // it, as those block ids were specific to the callee graph and we are now adding
1956 // these blocks to the caller graph.
1957 block->GetLoopInformation()->ClearAllBlocks();
1958 }
1959
1960 // If not already in a loop, update the loop information.
1961 if (!block->IsInLoop()) {
1962 block->SetLoopInformation(reference->GetLoopInformation());
1963 }
1964
1965 // If the block is in a loop, update all its outward loops.
1966 HLoopInformation* loop_info = block->GetLoopInformation();
1967 if (loop_info != nullptr) {
1968 for (HLoopInformationOutwardIterator loop_it(*block);
1969 !loop_it.Done();
1970 loop_it.Advance()) {
1971 loop_it.Current()->Add(block);
1972 }
1973 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1974 loop_info->ReplaceBackEdge(reference, block);
1975 }
1976 }
1977
1978 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1979 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1980 ? reference->GetTryCatchInformation()
1981 : nullptr;
1982 block->SetTryCatchInformation(try_catch_info);
1983}
1984
Calin Juravle2e768302015-07-28 14:41:11 +00001985HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001986 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001987 // Update the environments in this graph to have the invoke's environment
1988 // as parent.
1989 {
1990 HReversePostOrderIterator it(*this);
1991 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1992 for (; !it.Done(); it.Advance()) {
1993 HBasicBlock* block = it.Current();
1994 for (HInstructionIterator instr_it(block->GetInstructions());
1995 !instr_it.Done();
1996 instr_it.Advance()) {
1997 HInstruction* current = instr_it.Current();
1998 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001999 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002000 current->GetEnvironment()->SetAndCopyParentChain(
2001 outer_graph->GetArena(), invoke->GetEnvironment());
2002 }
2003 }
2004 }
2005 }
2006 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
2007 if (HasBoundsChecks()) {
2008 outer_graph->SetHasBoundsChecks(true);
2009 }
2010
Calin Juravle2e768302015-07-28 14:41:11 +00002011 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002012 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002013 // Simple case of an entry block, a body block, and an exit block.
2014 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002015 HBasicBlock* body = GetBlocks()[1];
2016 DCHECK(GetBlocks()[0]->IsEntryBlock());
2017 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002018 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002019 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002020 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002021
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002022 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2023 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002024 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002025
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002026 // Replace the invoke with the return value of the inlined graph.
2027 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002028 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002029 } else {
2030 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002031 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002032
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002033 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002034 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002035 // Need to inline multiple blocks. We split `invoke`'s block
2036 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002037 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002038 // with the second half.
2039 ArenaAllocator* allocator = outer_graph->GetArena();
2040 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002041 // Note that we split before the invoke only to simplify polymorphic inlining.
2042 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002043
Vladimir Markoec7802a2015-10-01 20:57:57 +01002044 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002045 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002046 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002047 exit_block_->ReplaceWith(to);
2048
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002049 // Update the meta information surrounding blocks:
2050 // (1) the graph they are now in,
2051 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002052 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002053 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002054 // Note that we do not need to update catch phi inputs because they
2055 // correspond to the register file of the outer method which the inlinee
2056 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002057
2058 // We don't add the entry block, the exit block, and the first block, which
2059 // has been merged with `at`.
2060 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2061
2062 // We add the `to` block.
2063 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002064 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002065 + kNumberOfNewBlocksInCaller;
2066
2067 // Find the location of `at` in the outer graph's reverse post order. The new
2068 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002069 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002070 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2071
David Brazdil95177982015-10-30 12:56:58 -05002072 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2073 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002074 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2075 HBasicBlock* current = it.Current();
2076 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002077 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002078 DCHECK(current->GetGraph() == this);
2079 current->SetGraph(outer_graph);
2080 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002081 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002082 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002083 }
2084 }
2085
David Brazdil95177982015-10-30 12:56:58 -05002086 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002087 to->SetGraph(outer_graph);
2088 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002089 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002090 // Only `to` can become a back edge, as the inlined blocks
2091 // are predecessors of `to`.
2092 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002093
David Brazdil3f523062016-02-29 16:53:33 +00002094 // Update all predecessors of the exit block (now the `to` block)
2095 // to not `HReturn` but `HGoto` instead.
2096 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2097 if (to->GetPredecessors().size() == 1) {
2098 HBasicBlock* predecessor = to->GetPredecessors()[0];
2099 HInstruction* last = predecessor->GetLastInstruction();
2100 if (!returns_void) {
2101 return_value = last->InputAt(0);
2102 }
2103 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2104 predecessor->RemoveInstruction(last);
2105 } else {
2106 if (!returns_void) {
2107 // There will be multiple returns.
2108 return_value = new (allocator) HPhi(
2109 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2110 to->AddPhi(return_value->AsPhi());
2111 }
2112 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2113 HInstruction* last = predecessor->GetLastInstruction();
2114 if (!returns_void) {
2115 DCHECK(last->IsReturn());
2116 return_value->AsPhi()->AddInput(last->InputAt(0));
2117 }
2118 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2119 predecessor->RemoveInstruction(last);
2120 }
2121 }
2122 }
David Brazdil05144f42015-04-16 15:18:00 +01002123
2124 // Walk over the entry block and:
2125 // - Move constants from the entry block to the outer_graph's entry block,
2126 // - Replace HParameterValue instructions with their real value.
2127 // - Remove suspend checks, that hold an environment.
2128 // We must do this after the other blocks have been inlined, otherwise ids of
2129 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002130 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002131 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2132 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002133 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002134 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002135 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002136 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002137 replacement = outer_graph->GetIntConstant(
2138 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002139 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002140 replacement = outer_graph->GetLongConstant(
2141 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002142 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002143 replacement = outer_graph->GetFloatConstant(
2144 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002145 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002146 replacement = outer_graph->GetDoubleConstant(
2147 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002148 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002149 if (kIsDebugBuild
2150 && invoke->IsInvokeStaticOrDirect()
2151 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2152 // Ensure we do not use the last input of `invoke`, as it
2153 // contains a clinit check which is not an actual argument.
2154 size_t last_input_index = invoke->InputCount() - 1;
2155 DCHECK(parameter_index != last_input_index);
2156 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002157 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002158 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002159 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002160 } else {
2161 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2162 entry_block_->RemoveInstruction(current);
2163 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002164 if (replacement != nullptr) {
2165 current->ReplaceWith(replacement);
2166 // If the current is the return value then we need to update the latter.
2167 if (current == return_value) {
2168 DCHECK_EQ(entry_block_, return_value->GetBlock());
2169 return_value = replacement;
2170 }
2171 }
2172 }
2173
Calin Juravle2e768302015-07-28 14:41:11 +00002174 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002175}
2176
Mingyao Yang3584bce2015-05-19 16:01:59 -07002177/*
2178 * Loop will be transformed to:
2179 * old_pre_header
2180 * |
2181 * if_block
2182 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002183 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002184 * \ /
2185 * new_pre_header
2186 * |
2187 * header
2188 */
2189void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2190 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002191 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002192
Aart Bik3fc7f352015-11-20 22:03:03 -08002193 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002194 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002195 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2196 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002197 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2198 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002199 AddBlock(true_block);
2200 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002201 AddBlock(new_pre_header);
2202
Aart Bik3fc7f352015-11-20 22:03:03 -08002203 header->ReplacePredecessor(old_pre_header, new_pre_header);
2204 old_pre_header->successors_.clear();
2205 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002206
Aart Bik3fc7f352015-11-20 22:03:03 -08002207 old_pre_header->AddSuccessor(if_block);
2208 if_block->AddSuccessor(true_block); // True successor
2209 if_block->AddSuccessor(false_block); // False successor
2210 true_block->AddSuccessor(new_pre_header);
2211 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002212
Aart Bik3fc7f352015-11-20 22:03:03 -08002213 old_pre_header->dominated_blocks_.push_back(if_block);
2214 if_block->SetDominator(old_pre_header);
2215 if_block->dominated_blocks_.push_back(true_block);
2216 true_block->SetDominator(if_block);
2217 if_block->dominated_blocks_.push_back(false_block);
2218 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002219 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002220 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002221 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002222 header->SetDominator(new_pre_header);
2223
Aart Bik3fc7f352015-11-20 22:03:03 -08002224 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002225 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002226 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002227 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002228 reverse_post_order_[index_of_header++] = true_block;
2229 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002230 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002231
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002232 // The pre_header can never be a back edge of a loop.
2233 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2234 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2235 UpdateLoopAndTryInformationOfNewBlock(
2236 if_block, old_pre_header, /* replace_if_back_edge */ false);
2237 UpdateLoopAndTryInformationOfNewBlock(
2238 true_block, old_pre_header, /* replace_if_back_edge */ false);
2239 UpdateLoopAndTryInformationOfNewBlock(
2240 false_block, old_pre_header, /* replace_if_back_edge */ false);
2241 UpdateLoopAndTryInformationOfNewBlock(
2242 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002243}
2244
David Brazdilf5552582015-12-27 13:36:12 +00002245static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2246 SHARED_REQUIRES(Locks::mutator_lock_) {
2247 if (rti.IsValid()) {
2248 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2249 << " upper_bound_rti: " << upper_bound_rti
2250 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002251 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2252 << " upper_bound_rti: " << upper_bound_rti
2253 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002254 }
2255}
2256
Calin Juravle2e768302015-07-28 14:41:11 +00002257void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2258 if (kIsDebugBuild) {
2259 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2260 ScopedObjectAccess soa(Thread::Current());
2261 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2262 if (IsBoundType()) {
2263 // Having the test here spares us from making the method virtual just for
2264 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002265 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002266 }
2267 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002268 reference_type_handle_ = rti.GetTypeHandle();
2269 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002270}
2271
David Brazdilf5552582015-12-27 13:36:12 +00002272void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2273 if (kIsDebugBuild) {
2274 ScopedObjectAccess soa(Thread::Current());
2275 DCHECK(upper_bound.IsValid());
2276 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2277 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2278 }
2279 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002280 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002281}
2282
Vladimir Markoa1de9182016-02-25 11:37:38 +00002283ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002284 if (kIsDebugBuild) {
2285 ScopedObjectAccess soa(Thread::Current());
2286 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002287 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002288 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002289 if (!is_exact) {
2290 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2291 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2292 }
Calin Juravle2e768302015-07-28 14:41:11 +00002293 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002294 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002295}
2296
Calin Juravleacf735c2015-02-12 15:25:22 +00002297std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2298 ScopedObjectAccess soa(Thread::Current());
2299 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002300 << " is_valid=" << rhs.IsValid()
2301 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002302 << " is_exact=" << rhs.IsExact()
2303 << " ]";
2304 return os;
2305}
2306
Mark Mendellc4701932015-04-10 13:18:51 -04002307bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2308 // For now, assume that instructions in different blocks may use the
2309 // environment.
2310 // TODO: Use the control flow to decide if this is true.
2311 if (GetBlock() != other->GetBlock()) {
2312 return true;
2313 }
2314
2315 // We know that we are in the same block. Walk from 'this' to 'other',
2316 // checking to see if there is any instruction with an environment.
2317 HInstruction* current = this;
2318 for (; current != other && current != nullptr; current = current->GetNext()) {
2319 // This is a conservative check, as the instruction result may not be in
2320 // the referenced environment.
2321 if (current->HasEnvironment()) {
2322 return true;
2323 }
2324 }
2325
2326 // We should have been called with 'this' before 'other' in the block.
2327 // Just confirm this.
2328 DCHECK(current != nullptr);
2329 return false;
2330}
2331
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002332void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002333 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2334 IntrinsicSideEffects side_effects,
2335 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002336 intrinsic_ = intrinsic;
2337 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002338
Aart Bik5d75afe2015-12-14 11:57:01 -08002339 // Adjust method's side effects from intrinsic table.
2340 switch (side_effects) {
2341 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2342 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2343 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2344 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2345 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002346
2347 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2348 opt.SetDoesNotNeedDexCache();
2349 opt.SetDoesNotNeedEnvironment();
2350 } else {
2351 // If we need an environment, that means there will be a call, which can trigger GC.
2352 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2353 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002354 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002355 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002356}
2357
David Brazdil6de19382016-01-08 17:37:10 +00002358bool HNewInstance::IsStringAlloc() const {
2359 ScopedObjectAccess soa(Thread::Current());
2360 return GetReferenceTypeInfo().IsStringClass();
2361}
2362
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002363bool HInvoke::NeedsEnvironment() const {
2364 if (!IsIntrinsic()) {
2365 return true;
2366 }
2367 IntrinsicOptimizations opt(*this);
2368 return !opt.GetDoesNotNeedEnvironment();
2369}
2370
Vladimir Markodc151b22015-10-15 18:02:30 +01002371bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2372 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002373 return false;
2374 }
2375 if (!IsIntrinsic()) {
2376 return true;
2377 }
2378 IntrinsicOptimizations opt(*this);
2379 return !opt.GetDoesNotNeedDexCache();
2380}
2381
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002382void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2383 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2384 input->AddUseAt(this, index);
2385 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2386 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2387 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2388 InputRecordAt(i).GetUseNode()->SetIndex(i);
2389 }
2390}
2391
Vladimir Markob554b5a2015-11-06 12:57:55 +00002392void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2393 RemoveAsUserOfInput(index);
2394 inputs_.erase(inputs_.begin() + index);
2395 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2396 for (size_t i = index, e = InputCount(); i < e; ++i) {
2397 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2398 InputRecordAt(i).GetUseNode()->SetIndex(i);
2399 }
2400}
2401
Vladimir Markof64242a2015-12-01 14:58:23 +00002402std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2403 switch (rhs) {
2404 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2405 return os << "string_init";
2406 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2407 return os << "recursive";
2408 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2409 return os << "direct";
2410 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2411 return os << "direct_fixup";
2412 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2413 return os << "dex_cache_pc_relative";
2414 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2415 return os << "dex_cache_via_method";
2416 default:
2417 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2418 UNREACHABLE();
2419 }
2420}
2421
Vladimir Markofbb184a2015-11-13 14:47:00 +00002422std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2423 switch (rhs) {
2424 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2425 return os << "explicit";
2426 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2427 return os << "implicit";
2428 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2429 return os << "none";
2430 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002431 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2432 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002433 }
2434}
2435
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002436bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2437 HLoadString* other_load_string = other->AsLoadString();
2438 if (string_index_ != other_load_string->string_index_ ||
2439 GetPackedFields() != other_load_string->GetPackedFields()) {
2440 return false;
2441 }
2442 LoadKind load_kind = GetLoadKind();
2443 if (HasAddress(load_kind)) {
2444 return GetAddress() == other_load_string->GetAddress();
2445 } else if (HasStringReference(load_kind)) {
2446 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2447 } else {
2448 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2449 // If the string indexes and dex files are the same, dex cache element offsets
2450 // must also be the same, so we don't need to compare them.
2451 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2452 }
2453}
2454
2455void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2456 // Once sharpened, the load kind should not be changed again.
2457 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2458 SetPackedField<LoadKindField>(load_kind);
2459
2460 if (load_kind != LoadKind::kDexCacheViaMethod) {
2461 RemoveAsUserOfInput(0u);
2462 SetRawInputAt(0u, nullptr);
2463 }
2464 if (!NeedsEnvironment()) {
2465 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002466 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002467 }
2468}
2469
2470std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2471 switch (rhs) {
2472 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2473 return os << "BootImageLinkTimeAddress";
2474 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2475 return os << "BootImageLinkTimePcRelative";
2476 case HLoadString::LoadKind::kBootImageAddress:
2477 return os << "BootImageAddress";
2478 case HLoadString::LoadKind::kDexCacheAddress:
2479 return os << "DexCacheAddress";
2480 case HLoadString::LoadKind::kDexCachePcRelative:
2481 return os << "DexCachePcRelative";
2482 case HLoadString::LoadKind::kDexCacheViaMethod:
2483 return os << "DexCacheViaMethod";
2484 default:
2485 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2486 UNREACHABLE();
2487 }
2488}
2489
Mark Mendellc4701932015-04-10 13:18:51 -04002490void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002491 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2492 HEnvironment* user = use.GetUser();
2493 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002494 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002495 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002496}
2497
Roland Levillainc9b21f82016-03-23 16:36:59 +00002498// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002499HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2500 ArenaAllocator* allocator = GetArena();
2501
2502 if (cond->IsCondition() &&
2503 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2504 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2505 HInstruction* lhs = cond->InputAt(0);
2506 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002507 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002508 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2509 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2510 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2511 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2512 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2513 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2514 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2515 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2516 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2517 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2518 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002519 default:
2520 LOG(FATAL) << "Unexpected condition";
2521 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002522 }
2523 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2524 return replacement;
2525 } else if (cond->IsIntConstant()) {
2526 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002527 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002528 return GetIntConstant(1);
2529 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002530 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002531 return GetIntConstant(0);
2532 }
2533 } else {
2534 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2535 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2536 return replacement;
2537 }
2538}
2539
Roland Levillainc9285912015-12-18 10:38:42 +00002540std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2541 os << "["
2542 << " source=" << rhs.GetSource()
2543 << " destination=" << rhs.GetDestination()
2544 << " type=" << rhs.GetType()
2545 << " instruction=";
2546 if (rhs.GetInstruction() != nullptr) {
2547 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2548 } else {
2549 os << "null";
2550 }
2551 os << " ]";
2552 return os;
2553}
2554
Roland Levillain86503782016-02-11 19:07:30 +00002555std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2556 switch (rhs) {
2557 case TypeCheckKind::kUnresolvedCheck:
2558 return os << "unresolved_check";
2559 case TypeCheckKind::kExactCheck:
2560 return os << "exact_check";
2561 case TypeCheckKind::kClassHierarchyCheck:
2562 return os << "class_hierarchy_check";
2563 case TypeCheckKind::kAbstractClassCheck:
2564 return os << "abstract_class_check";
2565 case TypeCheckKind::kInterfaceCheck:
2566 return os << "interface_check";
2567 case TypeCheckKind::kArrayObjectCheck:
2568 return os << "array_object_check";
2569 case TypeCheckKind::kArrayCheck:
2570 return os << "array_check";
2571 default:
2572 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2573 UNREACHABLE();
2574 }
2575}
2576
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002577} // namespace art