blob: 150d6b029b15dc756357eed41549a76ac6d9b9ef [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) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100104 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000105 RemoveEnvironmentUses(instruction);
106}
107
Roland Levillainfc600dc2014-12-02 17:16:31 +0000108void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100109 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100111 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000112 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100113 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000114 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
115 RemoveAsUser(it.Current());
116 }
117 }
118 }
119}
120
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100121void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100122 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000123 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100124 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000125 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100126 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000127 for (HBasicBlock* successor : block->GetSuccessors()) {
128 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000129 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100130 // Remove the block from the list of blocks, so that further analyses
131 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100132 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600133 if (block->IsExitBlock()) {
134 SetExitBlock(nullptr);
135 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000136 // Mark the block as removed. This is used by the HGraphBuilder to discard
137 // the block as a branch target.
138 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000139 }
140 }
141}
142
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000143GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000144 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000145
David Brazdil86ea7ee2016-02-16 09:26:07 +0000146 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147 FindBackEdges(&visited);
148
David Brazdil86ea7ee2016-02-16 09:26:07 +0000149 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000150 // the initial DFS as users from other instructions, so that
151 // users can be safely removed before uses later.
152 RemoveInstructionsAsUsersFromDeadBlocks(visited);
153
David Brazdil86ea7ee2016-02-16 09:26:07 +0000154 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000155 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 // predecessors list of live blocks.
157 RemoveDeadBlocks(visited);
158
David Brazdil86ea7ee2016-02-16 09:26:07 +0000159 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100160 // dominators and the reverse post order.
161 SimplifyCFG();
162
David Brazdil86ea7ee2016-02-16 09:26:07 +0000163 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100164 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000165
David Brazdil86ea7ee2016-02-16 09:26:07 +0000166 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167 // set the loop information on each block.
168 GraphAnalysisResult result = AnalyzeLoops();
169 if (result != kAnalysisSuccess) {
170 return result;
171 }
172
David Brazdil86ea7ee2016-02-16 09:26:07 +0000173 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000174 // which needs the information to build catch block phis from values of
175 // locals at throwing instructions inside try blocks.
176 ComputeTryBlockInformation();
177
178 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100179}
180
181void HGraph::ClearDominanceInformation() {
182 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
183 it.Current()->ClearDominanceInformation();
184 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100185 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100186}
187
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000188void HGraph::ClearLoopInformation() {
189 SetHasIrreducibleLoops(false);
190 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000191 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000192 }
193}
194
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100195void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000196 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100197 dominator_ = nullptr;
198}
199
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000200HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
201 HInstruction* instruction = GetFirstInstruction();
202 while (instruction->IsParallelMove()) {
203 instruction = instruction->GetNext();
204 }
205 return instruction;
206}
207
David Brazdil3f4a5222016-05-06 12:46:21 +0100208static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
209 DCHECK(ContainsElement(block->GetSuccessors(), successor));
210
211 HBasicBlock* old_dominator = successor->GetDominator();
212 HBasicBlock* new_dominator =
213 (old_dominator == nullptr) ? block
214 : CommonDominator::ForPair(old_dominator, block);
215
216 if (old_dominator == new_dominator) {
217 return false;
218 } else {
219 successor->SetDominator(new_dominator);
220 return true;
221 }
222}
223
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100224void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100225 DCHECK(reverse_post_order_.empty());
226 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100228
229 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100230 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100231 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100232 ArenaVector<size_t> successors_visited(blocks_.size(),
233 0u,
234 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100235 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100236 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 constexpr size_t kDefaultWorklistSize = 8;
238 worklist.reserve(kDefaultWorklistSize);
239 worklist.push_back(entry_block_);
240
241 while (!worklist.empty()) {
242 HBasicBlock* current = worklist.back();
243 uint32_t current_id = current->GetBlockId();
244 if (successors_visited[current_id] == current->GetSuccessors().size()) {
245 worklist.pop_back();
246 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100247 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100248 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100249
250 // Once all the forward edges have been visited, we know the immediate
251 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100252 if (++visits[successor->GetBlockId()] ==
253 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100254 reverse_post_order_.push_back(successor);
255 worklist.push_back(successor);
256 }
257 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000258 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000259
David Brazdil3f4a5222016-05-06 12:46:21 +0100260 // Check if the graph has back edges not dominated by their respective headers.
261 // If so, we need to update the dominators of those headers and recursively of
262 // their successors. We do that with a fix-point iteration over all blocks.
263 // The algorithm is guaranteed to terminate because it loops only if the sum
264 // of all dominator chains has decreased in the current iteration.
265 bool must_run_fix_point = false;
266 for (HBasicBlock* block : blocks_) {
267 if (block != nullptr &&
268 block->IsLoopHeader() &&
269 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
270 must_run_fix_point = true;
271 break;
272 }
273 }
274 if (must_run_fix_point) {
275 bool update_occurred = true;
276 while (update_occurred) {
277 update_occurred = false;
278 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
279 HBasicBlock* block = it.Current();
280 for (HBasicBlock* successor : block->GetSuccessors()) {
281 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
282 }
283 }
284 }
285 }
286
287 // Make sure that there are no remaining blocks whose dominator information
288 // needs to be updated.
289 if (kIsDebugBuild) {
290 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
291 HBasicBlock* block = it.Current();
292 for (HBasicBlock* successor : block->GetSuccessors()) {
293 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
294 }
295 }
296 }
297
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000298 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000299 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000300 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
301 HBasicBlock* block = it.Current();
302 if (!block->IsEntryBlock()) {
303 block->GetDominator()->AddDominatedBlock(block);
304 }
305 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000306}
307
David Brazdilfc6a86a2015-06-26 10:33:45 +0000308HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000309 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
310 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000311 // Use `InsertBetween` to ensure the predecessor index and successor index of
312 // `block` and `successor` are preserved.
313 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000314 return new_block;
315}
316
317void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
318 // Insert a new node between `block` and `successor` to split the
319 // critical edge.
320 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600321 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100322 if (successor->IsLoopHeader()) {
323 // If we split at a back edge boundary, make the new block the back edge.
324 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000325 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100326 info->RemoveBackEdge(block);
327 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100328 }
329 }
330}
331
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100332void HGraph::SimplifyLoop(HBasicBlock* header) {
333 HLoopInformation* info = header->GetLoopInformation();
334
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100335 // Make sure the loop has only one pre header. This simplifies SSA building by having
336 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000337 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
338 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000339 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000340 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100341 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100342 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600343 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100344
Vladimir Marko60584552015-09-03 13:35:12 +0000345 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100346 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100347 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100348 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100349 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100350 }
351 }
352 pre_header->AddSuccessor(header);
353 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100354
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100355 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100356 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
357 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000358 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100359 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100360 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000361 header->predecessors_[pred] = to_swap;
362 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100363 break;
364 }
365 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100366 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100367
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100368 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000369 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
370 // Called from DeadBlockElimination. Update SuspendCheck pointer.
371 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100372 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100373}
374
David Brazdilffee3d32015-07-06 11:48:53 +0100375void HGraph::ComputeTryBlockInformation() {
376 // Iterate in reverse post order to propagate try membership information from
377 // predecessors to their successors.
378 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
379 HBasicBlock* block = it.Current();
380 if (block->IsEntryBlock() || block->IsCatchBlock()) {
381 // Catch blocks after simplification have only exceptional predecessors
382 // and hence are never in tries.
383 continue;
384 }
385
386 // Infer try membership from the first predecessor. Having simplified loops,
387 // the first predecessor can never be a back edge and therefore it must have
388 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100389 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100390 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100391 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000392 if (try_entry != nullptr &&
393 (block->GetTryCatchInformation() == nullptr ||
394 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
395 // We are either setting try block membership for the first time or it
396 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100397 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
398 }
David Brazdilffee3d32015-07-06 11:48:53 +0100399 }
400}
401
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000403// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000405 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100406 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
407 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
408 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
409 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100410 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000411 if (block->GetSuccessors().size() > 1) {
412 // Only split normal-flow edges. We cannot split exceptional edges as they
413 // are synthesized (approximate real control flow), and we do not need to
414 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000415 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
416 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
417 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100418 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000419 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000420 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
421 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000422 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000423 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100424 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000425 // SplitCriticalEdge could have invalidated the `normal_successors`
426 // ArrayRef. We must re-acquire it.
427 normal_successors = block->GetNormalSuccessors();
428 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
429 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430 }
431 }
432 }
433 if (block->IsLoopHeader()) {
434 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000435 } else if (!block->IsEntryBlock() &&
436 block->GetFirstInstruction() != nullptr &&
437 block->GetFirstInstruction()->IsSuspendCheck()) {
438 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000439 // a loop got dismantled. Just remove the suspend check.
440 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100441 }
442 }
443}
444
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000445GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100446 // We iterate post order to ensure we visit inner loops before outer loops.
447 // `PopulateRecursive` needs this guarantee to know whether a natural loop
448 // contains an irreducible loop.
449 for (HPostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100450 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100451 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100452 if (block->IsCatchBlock()) {
453 // TODO: Dealing with exceptional back edges could be tricky because
454 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000455 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100456 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000457 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100458 }
459 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000460 return kAnalysisSuccess;
461}
462
463void HLoopInformation::Dump(std::ostream& os) {
464 os << "header: " << header_->GetBlockId() << std::endl;
465 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
466 for (HBasicBlock* block : back_edges_) {
467 os << "back edge: " << block->GetBlockId() << std::endl;
468 }
469 for (HBasicBlock* block : header_->GetPredecessors()) {
470 os << "predecessor: " << block->GetBlockId() << std::endl;
471 }
472 for (uint32_t idx : blocks_.Indexes()) {
473 os << " in loop: " << idx << std::endl;
474 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100475}
476
David Brazdil8d5b8b22015-03-24 10:51:52 +0000477void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000478 // New constants are inserted before the SuspendCheck at the bottom of the
479 // entry block. Note that this method can be called from the graph builder and
480 // the entry block therefore may not end with SuspendCheck->Goto yet.
481 HInstruction* insert_before = nullptr;
482
483 HInstruction* gota = entry_block_->GetLastInstruction();
484 if (gota != nullptr && gota->IsGoto()) {
485 HInstruction* suspend_check = gota->GetPrevious();
486 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
487 insert_before = suspend_check;
488 } else {
489 insert_before = gota;
490 }
491 }
492
493 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000494 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000495 } else {
496 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000497 }
498}
499
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600500HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100501 // For simplicity, don't bother reviving the cached null constant if it is
502 // not null and not in a block. Otherwise, we need to clear the instruction
503 // id and/or any invariants the graph is assuming when adding new instructions.
504 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600505 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000506 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000507 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000508 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000509 if (kIsDebugBuild) {
510 ScopedObjectAccess soa(Thread::Current());
511 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
512 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000513 return cached_null_constant_;
514}
515
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100516HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100517 // For simplicity, don't bother reviving the cached current method if it is
518 // not null and not in a block. Otherwise, we need to clear the instruction
519 // id and/or any invariants the graph is assuming when adding new instructions.
520 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700521 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600522 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
523 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100524 if (entry_block_->GetFirstInstruction() == nullptr) {
525 entry_block_->AddInstruction(cached_current_method_);
526 } else {
527 entry_block_->InsertInstructionBefore(
528 cached_current_method_, entry_block_->GetFirstInstruction());
529 }
530 }
531 return cached_current_method_;
532}
533
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600534HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000535 switch (type) {
536 case Primitive::Type::kPrimBoolean:
537 DCHECK(IsUint<1>(value));
538 FALLTHROUGH_INTENDED;
539 case Primitive::Type::kPrimByte:
540 case Primitive::Type::kPrimChar:
541 case Primitive::Type::kPrimShort:
542 case Primitive::Type::kPrimInt:
543 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600544 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000545
546 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548
549 default:
550 LOG(FATAL) << "Unsupported constant type";
551 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000552 }
David Brazdil46e2a392015-03-16 17:31:52 +0000553}
554
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000555void HGraph::CacheFloatConstant(HFloatConstant* constant) {
556 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
557 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
558 cached_float_constants_.Overwrite(value, constant);
559}
560
561void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
562 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
563 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
564 cached_double_constants_.Overwrite(value, constant);
565}
566
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000567void HLoopInformation::Add(HBasicBlock* block) {
568 blocks_.SetBit(block->GetBlockId());
569}
570
David Brazdil46e2a392015-03-16 17:31:52 +0000571void HLoopInformation::Remove(HBasicBlock* block) {
572 blocks_.ClearBit(block->GetBlockId());
573}
574
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100575void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
576 if (blocks_.IsBitSet(block->GetBlockId())) {
577 return;
578 }
579
580 blocks_.SetBit(block->GetBlockId());
581 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100582 if (block->IsLoopHeader()) {
583 // We're visiting loops in post-order, so inner loops must have been
584 // populated already.
585 DCHECK(block->GetLoopInformation()->IsPopulated());
586 if (block->GetLoopInformation()->IsIrreducible()) {
587 contains_irreducible_loop_ = true;
588 }
589 }
Vladimir Marko60584552015-09-03 13:35:12 +0000590 for (HBasicBlock* predecessor : block->GetPredecessors()) {
591 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100592 }
593}
594
David Brazdilc2e8af92016-04-05 17:15:19 +0100595void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
596 size_t block_id = block->GetBlockId();
597
598 // If `block` is in `finalized`, we know its membership in the loop has been
599 // decided and it does not need to be revisited.
600 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000601 return;
602 }
603
David Brazdilc2e8af92016-04-05 17:15:19 +0100604 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000605 if (block->IsLoopHeader()) {
606 // If we hit a loop header in an irreducible loop, we first check if the
607 // pre header of that loop belongs to the currently analyzed loop. If it does,
608 // then we visit the back edges.
609 // Note that we cannot use GetPreHeader, as the loop may have not been populated
610 // yet.
611 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100612 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000613 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000614 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100615 blocks_.SetBit(block_id);
616 finalized->SetBit(block_id);
617 is_finalized = true;
618
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619 HLoopInformation* info = block->GetLoopInformation();
620 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100621 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000622 }
623 }
624 } else {
625 // Visit all predecessors. If one predecessor is part of the loop, this
626 // block is also part of this loop.
627 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100628 PopulateIrreducibleRecursive(predecessor, finalized);
629 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000630 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100631 blocks_.SetBit(block_id);
632 finalized->SetBit(block_id);
633 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000634 }
635 }
636 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100637
638 // All predecessors have been recursively visited. Mark finalized if not marked yet.
639 if (!is_finalized) {
640 finalized->SetBit(block_id);
641 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000642}
643
644void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100645 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 // Populate this loop: starting with the back edge, recursively add predecessors
647 // that are not already part of that loop. Set the header as part of the loop
648 // to end the recursion.
649 // This is a recursive implementation of the algorithm described in
650 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100651 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000652 blocks_.SetBit(header_->GetBlockId());
653 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100654
David Brazdil3f4a5222016-05-06 12:46:21 +0100655 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100656
657 if (is_irreducible_loop) {
658 ArenaBitVector visited(graph->GetArena(),
659 graph->GetBlocks().size(),
660 /* expandable */ false,
661 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100662 // Stop marking blocks at the loop header.
663 visited.SetBit(header_->GetBlockId());
664
David Brazdilc2e8af92016-04-05 17:15:19 +0100665 for (HBasicBlock* back_edge : GetBackEdges()) {
666 PopulateIrreducibleRecursive(back_edge, &visited);
667 }
668 } else {
669 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000670 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100671 }
David Brazdila4b8c212015-05-07 09:59:30 +0100672 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100673
Vladimir Markofd66c502016-04-18 15:37:01 +0100674 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
675 // When compiling in OSR mode, all loops in the compiled method may be entered
676 // from the interpreter. We treat this OSR entry point just like an extra entry
677 // to an irreducible loop, so we need to mark the method's loops as irreducible.
678 // This does not apply to inlined loops which do not act as OSR entry points.
679 if (suspend_check_ == nullptr) {
680 // Just building the graph in OSR mode, this loop is not inlined. We never build an
681 // inner graph in OSR mode as we can do OSR transition only from the outer method.
682 is_irreducible_loop = true;
683 } else {
684 // Look at the suspend check's environment to determine if the loop was inlined.
685 DCHECK(suspend_check_->HasEnvironment());
686 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
687 is_irreducible_loop = true;
688 }
689 }
690 }
691 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100692 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100693 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100694 graph->SetHasIrreducibleLoops(true);
695 }
David Brazdila4b8c212015-05-07 09:59:30 +0100696}
697
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100698HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000699 HBasicBlock* block = header_->GetPredecessors()[0];
700 DCHECK(irreducible_ || (block == header_->GetDominator()));
701 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100702}
703
704bool HLoopInformation::Contains(const HBasicBlock& block) const {
705 return blocks_.IsBitSet(block.GetBlockId());
706}
707
708bool HLoopInformation::IsIn(const HLoopInformation& other) const {
709 return other.blocks_.IsBitSet(header_->GetBlockId());
710}
711
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800712bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
713 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700714}
715
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100716size_t HLoopInformation::GetLifetimeEnd() const {
717 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100718 for (HBasicBlock* back_edge : GetBackEdges()) {
719 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100720 }
721 return last_position;
722}
723
David Brazdil3f4a5222016-05-06 12:46:21 +0100724bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
725 for (HBasicBlock* back_edge : GetBackEdges()) {
726 DCHECK(back_edge->GetDominator() != nullptr);
727 if (!header_->Dominates(back_edge)) {
728 return true;
729 }
730 }
731 return false;
732}
733
Anton Shaminf89381f2016-05-16 16:44:13 +0600734bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
735 for (HBasicBlock* back_edge : GetBackEdges()) {
736 if (!block->Dominates(back_edge)) {
737 return false;
738 }
739 }
740 return true;
741}
742
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100743bool HBasicBlock::Dominates(HBasicBlock* other) const {
744 // Walk up the dominator tree from `other`, to find out if `this`
745 // is an ancestor.
746 HBasicBlock* current = other;
747 while (current != nullptr) {
748 if (current == this) {
749 return true;
750 }
751 current = current->GetDominator();
752 }
753 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100754}
755
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100756static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100757 auto&& inputs = instruction->GetInputs();
758 for (size_t i = 0; i < inputs.size(); ++i) {
759 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100760 }
761 // Environment should be created later.
762 DCHECK(!instruction->HasEnvironment());
763}
764
Roland Levillainccc07a92014-09-16 14:48:16 +0100765void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
766 HInstruction* replacement) {
767 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400768 if (initial->IsControlFlow()) {
769 // We can only replace a control flow instruction with another control flow instruction.
770 DCHECK(replacement->IsControlFlow());
771 DCHECK_EQ(replacement->GetId(), -1);
772 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
773 DCHECK_EQ(initial->GetBlock(), this);
774 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100775 DCHECK(initial->GetUses().empty());
776 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400777 replacement->SetBlock(this);
778 replacement->SetId(GetGraph()->GetNextInstructionId());
779 instructions_.InsertInstructionBefore(replacement, initial);
780 UpdateInputsUsers(replacement);
781 } else {
782 InsertInstructionBefore(replacement, initial);
783 initial->ReplaceWith(replacement);
784 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100785 RemoveInstruction(initial);
786}
787
David Brazdil74eb1b22015-12-14 11:44:01 +0000788void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
789 DCHECK(!cursor->IsPhi());
790 DCHECK(!insn->IsPhi());
791 DCHECK(!insn->IsControlFlow());
792 DCHECK(insn->CanBeMoved());
793 DCHECK(!insn->HasSideEffects());
794
795 HBasicBlock* from_block = insn->GetBlock();
796 HBasicBlock* to_block = cursor->GetBlock();
797 DCHECK(from_block != to_block);
798
799 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
800 insn->SetBlock(to_block);
801 to_block->instructions_.InsertInstructionBefore(insn, cursor);
802}
803
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100804static void Add(HInstructionList* instruction_list,
805 HBasicBlock* block,
806 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000807 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000808 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100809 instruction->SetBlock(block);
810 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100811 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100812 instruction_list->AddInstruction(instruction);
813}
814
815void HBasicBlock::AddInstruction(HInstruction* instruction) {
816 Add(&instructions_, this, instruction);
817}
818
819void HBasicBlock::AddPhi(HPhi* phi) {
820 Add(&phis_, this, phi);
821}
822
David Brazdilc3d743f2015-04-22 13:40:50 +0100823void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
824 DCHECK(!cursor->IsPhi());
825 DCHECK(!instruction->IsPhi());
826 DCHECK_EQ(instruction->GetId(), -1);
827 DCHECK_NE(cursor->GetId(), -1);
828 DCHECK_EQ(cursor->GetBlock(), this);
829 DCHECK(!instruction->IsControlFlow());
830 instruction->SetBlock(this);
831 instruction->SetId(GetGraph()->GetNextInstructionId());
832 UpdateInputsUsers(instruction);
833 instructions_.InsertInstructionBefore(instruction, cursor);
834}
835
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100836void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
837 DCHECK(!cursor->IsPhi());
838 DCHECK(!instruction->IsPhi());
839 DCHECK_EQ(instruction->GetId(), -1);
840 DCHECK_NE(cursor->GetId(), -1);
841 DCHECK_EQ(cursor->GetBlock(), this);
842 DCHECK(!instruction->IsControlFlow());
843 DCHECK(!cursor->IsControlFlow());
844 instruction->SetBlock(this);
845 instruction->SetId(GetGraph()->GetNextInstructionId());
846 UpdateInputsUsers(instruction);
847 instructions_.InsertInstructionAfter(instruction, cursor);
848}
849
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100850void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
851 DCHECK_EQ(phi->GetId(), -1);
852 DCHECK_NE(cursor->GetId(), -1);
853 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100854 phi->SetBlock(this);
855 phi->SetId(GetGraph()->GetNextInstructionId());
856 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100857 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100858}
859
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100860static void Remove(HInstructionList* instruction_list,
861 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000862 HInstruction* instruction,
863 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100864 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865 instruction->SetBlock(nullptr);
866 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000867 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100868 DCHECK(instruction->GetUses().empty());
869 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000870 RemoveAsUser(instruction);
871 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100872}
873
David Brazdil1abb4192015-02-17 18:33:36 +0000874void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100875 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000876 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100877}
878
David Brazdil1abb4192015-02-17 18:33:36 +0000879void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
880 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100881}
882
David Brazdilc7508e92015-04-27 13:28:57 +0100883void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
884 if (instruction->IsPhi()) {
885 RemovePhi(instruction->AsPhi(), ensure_safety);
886 } else {
887 RemoveInstruction(instruction, ensure_safety);
888 }
889}
890
Vladimir Marko71bf8092015-09-15 15:33:14 +0100891void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
892 for (size_t i = 0; i < locals.size(); i++) {
893 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100894 SetRawEnvAt(i, instruction);
895 if (instruction != nullptr) {
896 instruction->AddEnvUseAt(this, i);
897 }
898 }
899}
900
David Brazdiled596192015-01-23 10:39:45 +0000901void HEnvironment::CopyFrom(HEnvironment* env) {
902 for (size_t i = 0; i < env->Size(); i++) {
903 HInstruction* instruction = env->GetInstructionAt(i);
904 SetRawEnvAt(i, instruction);
905 if (instruction != nullptr) {
906 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100907 }
David Brazdiled596192015-01-23 10:39:45 +0000908 }
909}
910
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700911void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
912 HBasicBlock* loop_header) {
913 DCHECK(loop_header->IsLoopHeader());
914 for (size_t i = 0; i < env->Size(); i++) {
915 HInstruction* instruction = env->GetInstructionAt(i);
916 SetRawEnvAt(i, instruction);
917 if (instruction == nullptr) {
918 continue;
919 }
920 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
921 // At the end of the loop pre-header, the corresponding value for instruction
922 // is the first input of the phi.
923 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700924 SetRawEnvAt(i, initial);
925 initial->AddEnvUseAt(this, i);
926 } else {
927 instruction->AddEnvUseAt(this, i);
928 }
929 }
930}
931
David Brazdil1abb4192015-02-17 18:33:36 +0000932void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100933 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
934 HInstruction* user = env_use.GetInstruction();
935 auto before_env_use_node = env_use.GetBeforeUseNode();
936 user->env_uses_.erase_after(before_env_use_node);
937 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938}
939
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000940HInstruction::InstructionKind HInstruction::GetKind() const {
941 return GetKindInternal();
942}
943
Calin Juravle77520bc2015-01-12 18:45:46 +0000944HInstruction* HInstruction::GetNextDisregardingMoves() const {
945 HInstruction* next = GetNext();
946 while (next != nullptr && next->IsParallelMove()) {
947 next = next->GetNext();
948 }
949 return next;
950}
951
952HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
953 HInstruction* previous = GetPrevious();
954 while (previous != nullptr && previous->IsParallelMove()) {
955 previous = previous->GetPrevious();
956 }
957 return previous;
958}
959
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100960void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000961 if (first_instruction_ == nullptr) {
962 DCHECK(last_instruction_ == nullptr);
963 first_instruction_ = last_instruction_ = instruction;
964 } else {
965 last_instruction_->next_ = instruction;
966 instruction->previous_ = last_instruction_;
967 last_instruction_ = instruction;
968 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000969}
970
David Brazdilc3d743f2015-04-22 13:40:50 +0100971void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
972 DCHECK(Contains(cursor));
973 if (cursor == first_instruction_) {
974 cursor->previous_ = instruction;
975 instruction->next_ = cursor;
976 first_instruction_ = instruction;
977 } else {
978 instruction->previous_ = cursor->previous_;
979 instruction->next_ = cursor;
980 cursor->previous_ = instruction;
981 instruction->previous_->next_ = instruction;
982 }
983}
984
985void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
986 DCHECK(Contains(cursor));
987 if (cursor == last_instruction_) {
988 cursor->next_ = instruction;
989 instruction->previous_ = cursor;
990 last_instruction_ = instruction;
991 } else {
992 instruction->next_ = cursor->next_;
993 instruction->previous_ = cursor;
994 cursor->next_ = instruction;
995 instruction->next_->previous_ = instruction;
996 }
997}
998
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100999void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1000 if (instruction->previous_ != nullptr) {
1001 instruction->previous_->next_ = instruction->next_;
1002 }
1003 if (instruction->next_ != nullptr) {
1004 instruction->next_->previous_ = instruction->previous_;
1005 }
1006 if (instruction == first_instruction_) {
1007 first_instruction_ = instruction->next_;
1008 }
1009 if (instruction == last_instruction_) {
1010 last_instruction_ = instruction->previous_;
1011 }
1012}
1013
Roland Levillain6b469232014-09-25 10:10:38 +01001014bool HInstructionList::Contains(HInstruction* instruction) const {
1015 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1016 if (it.Current() == instruction) {
1017 return true;
1018 }
1019 }
1020 return false;
1021}
1022
Roland Levillainccc07a92014-09-16 14:48:16 +01001023bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1024 const HInstruction* instruction2) const {
1025 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1026 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1027 if (it.Current() == instruction1) {
1028 return true;
1029 }
1030 if (it.Current() == instruction2) {
1031 return false;
1032 }
1033 }
1034 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1035 return true;
1036}
1037
Roland Levillain6c82d402014-10-13 16:10:27 +01001038bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1039 if (other_instruction == this) {
1040 // An instruction does not strictly dominate itself.
1041 return false;
1042 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001043 HBasicBlock* block = GetBlock();
1044 HBasicBlock* other_block = other_instruction->GetBlock();
1045 if (block != other_block) {
1046 return GetBlock()->Dominates(other_instruction->GetBlock());
1047 } else {
1048 // If both instructions are in the same block, ensure this
1049 // instruction comes before `other_instruction`.
1050 if (IsPhi()) {
1051 if (!other_instruction->IsPhi()) {
1052 // Phis appear before non phi-instructions so this instruction
1053 // dominates `other_instruction`.
1054 return true;
1055 } else {
1056 // There is no order among phis.
1057 LOG(FATAL) << "There is no dominance between phis of a same block.";
1058 return false;
1059 }
1060 } else {
1061 // `this` is not a phi.
1062 if (other_instruction->IsPhi()) {
1063 // Phis appear before non phi-instructions so this instruction
1064 // does not dominate `other_instruction`.
1065 return false;
1066 } else {
1067 // Check whether this instruction comes before
1068 // `other_instruction` in the instruction list.
1069 return block->GetInstructions().FoundBefore(this, other_instruction);
1070 }
1071 }
1072 }
1073}
1074
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001075void HInstruction::RemoveEnvironment() {
1076 RemoveEnvironmentUses(this);
1077 environment_ = nullptr;
1078}
1079
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001080void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001081 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001082 // Note: fixup_end remains valid across splice_after().
1083 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1084 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1085 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001086
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001087 // Note: env_fixup_end remains valid across splice_after().
1088 auto env_fixup_end =
1089 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1090 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1091 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001092
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001093 DCHECK(uses_.empty());
1094 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001095}
1096
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001097void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001098 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001099 if (input_use.GetInstruction() == replacement) {
1100 // Nothing to do.
1101 return;
1102 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001103 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001104 // Note: fixup_end remains valid across splice_after().
1105 auto fixup_end =
1106 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1107 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1108 input_use.GetInstruction()->uses_,
1109 before_use_node);
1110 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1111 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001112}
1113
Nicolas Geoffray39468442014-09-02 15:17:15 +01001114size_t HInstruction::EnvironmentSize() const {
1115 return HasEnvironment() ? environment_->Size() : 0;
1116}
1117
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001118void HPhi::AddInput(HInstruction* input) {
1119 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001120 inputs_.push_back(HUserRecord<HInstruction*>(input));
1121 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122}
1123
David Brazdil2d7352b2015-04-20 14:52:42 +01001124void HPhi::RemoveInputAt(size_t index) {
1125 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001126 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001127 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1128 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1129 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1130 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001131 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001132}
1133
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001134#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001135void H##name::Accept(HGraphVisitor* visitor) { \
1136 visitor->Visit##name(this); \
1137}
1138
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001139FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001140
1141#undef DEFINE_ACCEPT
1142
1143void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001144 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1145 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001146 if (block != nullptr) {
1147 VisitBasicBlock(block);
1148 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001149 }
1150}
1151
Roland Levillain633021e2014-10-01 14:12:25 +01001152void HGraphVisitor::VisitReversePostOrder() {
1153 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1154 VisitBasicBlock(it.Current());
1155 }
1156}
1157
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001158void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001159 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001160 it.Current()->Accept(this);
1161 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001162 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001163 it.Current()->Accept(this);
1164 }
1165}
1166
Mark Mendelle82549b2015-05-06 10:55:34 -04001167HConstant* HTypeConversion::TryStaticEvaluation() const {
1168 HGraph* graph = GetBlock()->GetGraph();
1169 if (GetInput()->IsIntConstant()) {
1170 int32_t value = GetInput()->AsIntConstant()->GetValue();
1171 switch (GetResultType()) {
1172 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001173 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001174 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001175 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001176 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001177 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001178 default:
1179 return nullptr;
1180 }
1181 } else if (GetInput()->IsLongConstant()) {
1182 int64_t value = GetInput()->AsLongConstant()->GetValue();
1183 switch (GetResultType()) {
1184 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001185 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001186 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001187 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001188 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001189 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001190 default:
1191 return nullptr;
1192 }
1193 } else if (GetInput()->IsFloatConstant()) {
1194 float value = GetInput()->AsFloatConstant()->GetValue();
1195 switch (GetResultType()) {
1196 case Primitive::kPrimInt:
1197 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001198 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001199 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001200 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001201 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001202 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1203 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001204 case Primitive::kPrimLong:
1205 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001206 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001207 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001208 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001209 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001210 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1211 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001212 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001213 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001214 default:
1215 return nullptr;
1216 }
1217 } else if (GetInput()->IsDoubleConstant()) {
1218 double value = GetInput()->AsDoubleConstant()->GetValue();
1219 switch (GetResultType()) {
1220 case Primitive::kPrimInt:
1221 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001222 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001223 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001224 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001225 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001226 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1227 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001228 case Primitive::kPrimLong:
1229 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001230 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001231 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001232 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001233 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001234 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1235 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001236 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001237 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001238 default:
1239 return nullptr;
1240 }
1241 }
1242 return nullptr;
1243}
1244
Roland Levillain9240d6a2014-10-20 16:47:04 +01001245HConstant* HUnaryOperation::TryStaticEvaluation() const {
1246 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001247 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001248 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001249 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001250 } else if (kEnableFloatingPointStaticEvaluation) {
1251 if (GetInput()->IsFloatConstant()) {
1252 return Evaluate(GetInput()->AsFloatConstant());
1253 } else if (GetInput()->IsDoubleConstant()) {
1254 return Evaluate(GetInput()->AsDoubleConstant());
1255 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001256 }
1257 return nullptr;
1258}
1259
1260HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001261 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1262 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001263 } else if (GetLeft()->IsLongConstant()) {
1264 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001265 // The binop(long, int) case is only valid for shifts and rotations.
1266 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001267 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1268 } else if (GetRight()->IsLongConstant()) {
1269 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001270 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001271 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001272 // The binop(null, null) case is only valid for equal and not-equal conditions.
1273 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001274 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001275 } else if (kEnableFloatingPointStaticEvaluation) {
1276 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1277 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1278 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1279 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1280 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001281 }
1282 return nullptr;
1283}
Dave Allison20dfc792014-06-16 20:44:29 -07001284
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001285HConstant* HBinaryOperation::GetConstantRight() const {
1286 if (GetRight()->IsConstant()) {
1287 return GetRight()->AsConstant();
1288 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1289 return GetLeft()->AsConstant();
1290 } else {
1291 return nullptr;
1292 }
1293}
1294
1295// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001296// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001297HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1298 HInstruction* most_constant_right = GetConstantRight();
1299 if (most_constant_right == nullptr) {
1300 return nullptr;
1301 } else if (most_constant_right == GetLeft()) {
1302 return GetRight();
1303 } else {
1304 return GetLeft();
1305 }
1306}
1307
Roland Levillain31dd3d62016-02-16 12:21:02 +00001308std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1309 switch (rhs) {
1310 case ComparisonBias::kNoBias:
1311 return os << "no_bias";
1312 case ComparisonBias::kGtBias:
1313 return os << "gt_bias";
1314 case ComparisonBias::kLtBias:
1315 return os << "lt_bias";
1316 default:
1317 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1318 UNREACHABLE();
1319 }
1320}
1321
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001322bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1323 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001324}
1325
Vladimir Marko372f10e2016-05-17 16:30:10 +01001326bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001327 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001328 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001329 if (!InstructionDataEquals(other)) return false;
1330 if (GetType() != other->GetType()) return false;
Vladimir Marko372f10e2016-05-17 16:30:10 +01001331 auto&& inputs = GetInputs();
1332 auto&& other_inputs = other->GetInputs();
1333 if (inputs.size() != other_inputs.size()) return false;
1334 for (size_t i = 0; i != inputs.size(); ++i) {
1335 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001336 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001337
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001338 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001339 return true;
1340}
1341
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001342std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1343#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1344 switch (rhs) {
1345 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1346 default:
1347 os << "Unknown instruction kind " << static_cast<int>(rhs);
1348 break;
1349 }
1350#undef DECLARE_CASE
1351 return os;
1352}
1353
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001354void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001355 next_->previous_ = previous_;
1356 if (previous_ != nullptr) {
1357 previous_->next_ = next_;
1358 }
1359 if (block_->instructions_.first_instruction_ == this) {
1360 block_->instructions_.first_instruction_ = next_;
1361 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001362 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001363
1364 previous_ = cursor->previous_;
1365 if (previous_ != nullptr) {
1366 previous_->next_ = this;
1367 }
1368 next_ = cursor;
1369 cursor->previous_ = this;
1370 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001371
1372 if (block_->instructions_.first_instruction_ == cursor) {
1373 block_->instructions_.first_instruction_ = this;
1374 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001375}
1376
Vladimir Markofb337ea2015-11-25 15:25:10 +00001377void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1378 DCHECK(!CanThrow());
1379 DCHECK(!HasSideEffects());
1380 DCHECK(!HasEnvironmentUses());
1381 DCHECK(HasNonEnvironmentUses());
1382 DCHECK(!IsPhi()); // Makes no sense for Phi.
1383 DCHECK_EQ(InputCount(), 0u);
1384
1385 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001386 auto uses_it = GetUses().begin();
1387 auto uses_end = GetUses().end();
1388 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1389 ++uses_it;
1390 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1391 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001392 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001393 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001394 // This instruction has uses in two or more blocks. Find the common dominator.
1395 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001396 for (; uses_it != uses_end; ++uses_it) {
1397 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001398 }
1399 target_block = finder.Get();
1400 DCHECK(target_block != nullptr);
1401 }
1402 // Move to the first dominator not in a loop.
1403 while (target_block->IsInLoop()) {
1404 target_block = target_block->GetDominator();
1405 DCHECK(target_block != nullptr);
1406 }
1407
1408 // Find insertion position.
1409 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001410 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1411 if (use.GetUser()->GetBlock() == target_block &&
1412 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1413 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001414 }
1415 }
1416 if (insert_pos == nullptr) {
1417 // No user in `target_block`, insert before the control flow instruction.
1418 insert_pos = target_block->GetLastInstruction();
1419 DCHECK(insert_pos->IsControlFlow());
1420 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1421 if (insert_pos->IsIf()) {
1422 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1423 if (if_input == insert_pos->GetPrevious()) {
1424 insert_pos = if_input;
1425 }
1426 }
1427 }
1428 MoveBefore(insert_pos);
1429}
1430
David Brazdilfc6a86a2015-06-26 10:33:45 +00001431HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001432 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001433 DCHECK_EQ(cursor->GetBlock(), this);
1434
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001435 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1436 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001437 new_block->instructions_.first_instruction_ = cursor;
1438 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1439 instructions_.last_instruction_ = cursor->previous_;
1440 if (cursor->previous_ == nullptr) {
1441 instructions_.first_instruction_ = nullptr;
1442 } else {
1443 cursor->previous_->next_ = nullptr;
1444 cursor->previous_ = nullptr;
1445 }
1446
1447 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001448 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001449
Vladimir Marko60584552015-09-03 13:35:12 +00001450 for (HBasicBlock* successor : GetSuccessors()) {
1451 new_block->successors_.push_back(successor);
1452 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001453 }
Vladimir Marko60584552015-09-03 13:35:12 +00001454 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001455 AddSuccessor(new_block);
1456
David Brazdil56e1acc2015-06-30 15:41:36 +01001457 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001458 return new_block;
1459}
1460
David Brazdild7558da2015-09-22 13:04:14 +01001461HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001462 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001463 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1464
1465 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1466
1467 for (HBasicBlock* predecessor : GetPredecessors()) {
1468 new_block->predecessors_.push_back(predecessor);
1469 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1470 }
1471 predecessors_.clear();
1472 AddPredecessor(new_block);
1473
1474 GetGraph()->AddBlock(new_block);
1475 return new_block;
1476}
1477
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001478HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1479 DCHECK_EQ(cursor->GetBlock(), this);
1480
1481 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1482 cursor->GetDexPc());
1483 new_block->instructions_.first_instruction_ = cursor;
1484 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1485 instructions_.last_instruction_ = cursor->previous_;
1486 if (cursor->previous_ == nullptr) {
1487 instructions_.first_instruction_ = nullptr;
1488 } else {
1489 cursor->previous_->next_ = nullptr;
1490 cursor->previous_ = nullptr;
1491 }
1492
1493 new_block->instructions_.SetBlockOfInstructions(new_block);
1494
1495 for (HBasicBlock* successor : GetSuccessors()) {
1496 new_block->successors_.push_back(successor);
1497 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1498 }
1499 successors_.clear();
1500
1501 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1502 dominated->dominator_ = new_block;
1503 new_block->dominated_blocks_.push_back(dominated);
1504 }
1505 dominated_blocks_.clear();
1506 return new_block;
1507}
1508
1509HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001510 DCHECK(!cursor->IsControlFlow());
1511 DCHECK_NE(instructions_.last_instruction_, cursor);
1512 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001513
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001514 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1515 new_block->instructions_.first_instruction_ = cursor->GetNext();
1516 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1517 cursor->next_->previous_ = nullptr;
1518 cursor->next_ = nullptr;
1519 instructions_.last_instruction_ = cursor;
1520
1521 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001522 for (HBasicBlock* successor : GetSuccessors()) {
1523 new_block->successors_.push_back(successor);
1524 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001525 }
Vladimir Marko60584552015-09-03 13:35:12 +00001526 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001527
Vladimir Marko60584552015-09-03 13:35:12 +00001528 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001529 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001530 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001531 }
Vladimir Marko60584552015-09-03 13:35:12 +00001532 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001533 return new_block;
1534}
1535
David Brazdilec16f792015-08-19 15:04:01 +01001536const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001537 if (EndsWithTryBoundary()) {
1538 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1539 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001540 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001541 return try_boundary;
1542 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001543 DCHECK(IsTryBlock());
1544 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001545 return nullptr;
1546 }
David Brazdilec16f792015-08-19 15:04:01 +01001547 } else if (IsTryBlock()) {
1548 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001549 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001550 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001551 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001552}
1553
David Brazdild7558da2015-09-22 13:04:14 +01001554bool HBasicBlock::HasThrowingInstructions() const {
1555 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1556 if (it.Current()->CanThrow()) {
1557 return true;
1558 }
1559 }
1560 return false;
1561}
1562
David Brazdilfc6a86a2015-06-26 10:33:45 +00001563static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1564 return block.GetPhis().IsEmpty()
1565 && !block.GetInstructions().IsEmpty()
1566 && block.GetFirstInstruction() == block.GetLastInstruction();
1567}
1568
David Brazdil46e2a392015-03-16 17:31:52 +00001569bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001570 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1571}
1572
1573bool HBasicBlock::IsSingleTryBoundary() const {
1574 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001575}
1576
David Brazdil8d5b8b22015-03-24 10:51:52 +00001577bool HBasicBlock::EndsWithControlFlowInstruction() const {
1578 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1579}
1580
David Brazdilb2bd1c52015-03-25 11:17:37 +00001581bool HBasicBlock::EndsWithIf() const {
1582 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1583}
1584
David Brazdilffee3d32015-07-06 11:48:53 +01001585bool HBasicBlock::EndsWithTryBoundary() const {
1586 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1587}
1588
David Brazdilb2bd1c52015-03-25 11:17:37 +00001589bool HBasicBlock::HasSinglePhi() const {
1590 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1591}
1592
David Brazdild26a4112015-11-10 11:07:31 +00001593ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1594 if (EndsWithTryBoundary()) {
1595 // The normal-flow successor of HTryBoundary is always stored at index zero.
1596 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1597 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1598 } else {
1599 // All successors of blocks not ending with TryBoundary are normal.
1600 return ArrayRef<HBasicBlock* const>(successors_);
1601 }
1602}
1603
1604ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1605 if (EndsWithTryBoundary()) {
1606 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1607 } else {
1608 // Blocks not ending with TryBoundary do not have exceptional successors.
1609 return ArrayRef<HBasicBlock* const>();
1610 }
1611}
1612
David Brazdilffee3d32015-07-06 11:48:53 +01001613bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001614 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1615 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1616
1617 size_t length = handlers1.size();
1618 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001619 return false;
1620 }
1621
David Brazdilb618ade2015-07-29 10:31:29 +01001622 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001623 for (size_t i = 0; i < length; ++i) {
1624 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001625 return false;
1626 }
1627 }
1628 return true;
1629}
1630
David Brazdil2d7352b2015-04-20 14:52:42 +01001631size_t HInstructionList::CountSize() const {
1632 size_t size = 0;
1633 HInstruction* current = first_instruction_;
1634 for (; current != nullptr; current = current->GetNext()) {
1635 size++;
1636 }
1637 return size;
1638}
1639
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001640void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1641 for (HInstruction* current = first_instruction_;
1642 current != nullptr;
1643 current = current->GetNext()) {
1644 current->SetBlock(block);
1645 }
1646}
1647
1648void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1649 DCHECK(Contains(cursor));
1650 if (!instruction_list.IsEmpty()) {
1651 if (cursor == last_instruction_) {
1652 last_instruction_ = instruction_list.last_instruction_;
1653 } else {
1654 cursor->next_->previous_ = instruction_list.last_instruction_;
1655 }
1656 instruction_list.last_instruction_->next_ = cursor->next_;
1657 cursor->next_ = instruction_list.first_instruction_;
1658 instruction_list.first_instruction_->previous_ = cursor;
1659 }
1660}
1661
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001662void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1663 DCHECK(Contains(cursor));
1664 if (!instruction_list.IsEmpty()) {
1665 if (cursor == first_instruction_) {
1666 first_instruction_ = instruction_list.first_instruction_;
1667 } else {
1668 cursor->previous_->next_ = instruction_list.first_instruction_;
1669 }
1670 instruction_list.last_instruction_->next_ = cursor;
1671 instruction_list.first_instruction_->previous_ = cursor->previous_;
1672 cursor->previous_ = instruction_list.last_instruction_;
1673 }
1674}
1675
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001676void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001677 if (IsEmpty()) {
1678 first_instruction_ = instruction_list.first_instruction_;
1679 last_instruction_ = instruction_list.last_instruction_;
1680 } else {
1681 AddAfter(last_instruction_, instruction_list);
1682 }
1683}
1684
David Brazdil04ff4e82015-12-10 13:54:52 +00001685// Should be called on instructions in a dead block in post order. This method
1686// assumes `insn` has been removed from all users with the exception of catch
1687// phis because of missing exceptional edges in the graph. It removes the
1688// instruction from catch phi uses, together with inputs of other catch phis in
1689// the catch block at the same index, as these must be dead too.
1690static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1691 DCHECK(!insn->HasEnvironmentUses());
1692 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001693 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1694 size_t use_index = use.GetIndex();
1695 HBasicBlock* user_block = use.GetUser()->GetBlock();
1696 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001697 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1698 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1699 }
1700 }
1701}
1702
David Brazdil2d7352b2015-04-20 14:52:42 +01001703void HBasicBlock::DisconnectAndDelete() {
1704 // Dominators must be removed after all the blocks they dominate. This way
1705 // a loop header is removed last, a requirement for correct loop information
1706 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001707 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001708
David Brazdil9eeebf62016-03-24 11:18:15 +00001709 // The following steps gradually remove the block from all its dependants in
1710 // post order (b/27683071).
1711
1712 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1713 // We need to do this before step (4) which destroys the predecessor list.
1714 HBasicBlock* loop_update_start = this;
1715 if (IsLoopHeader()) {
1716 HLoopInformation* loop_info = GetLoopInformation();
1717 // All other blocks in this loop should have been removed because the header
1718 // was their dominator.
1719 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1720 DCHECK(!loop_info->IsIrreducible());
1721 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1722 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1723 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001724 }
1725
David Brazdil9eeebf62016-03-24 11:18:15 +00001726 // (2) Disconnect the block from its successors and update their phis.
1727 for (HBasicBlock* successor : successors_) {
1728 // Delete this block from the list of predecessors.
1729 size_t this_index = successor->GetPredecessorIndexOf(this);
1730 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1731
1732 // Check that `successor` has other predecessors, otherwise `this` is the
1733 // dominator of `successor` which violates the order DCHECKed at the top.
1734 DCHECK(!successor->predecessors_.empty());
1735
1736 // Remove this block's entries in the successor's phis. Skip exceptional
1737 // successors because catch phi inputs do not correspond to predecessor
1738 // blocks but throwing instructions. The inputs of the catch phis will be
1739 // updated in step (3).
1740 if (!successor->IsCatchBlock()) {
1741 if (successor->predecessors_.size() == 1u) {
1742 // The successor has just one predecessor left. Replace phis with the only
1743 // remaining input.
1744 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1745 HPhi* phi = phi_it.Current()->AsPhi();
1746 phi->ReplaceWith(phi->InputAt(1 - this_index));
1747 successor->RemovePhi(phi);
1748 }
1749 } else {
1750 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1751 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1752 }
1753 }
1754 }
1755 }
1756 successors_.clear();
1757
1758 // (3) Remove instructions and phis. Instructions should have no remaining uses
1759 // except in catch phis. If an instruction is used by a catch phi at `index`,
1760 // remove `index`-th input of all phis in the catch block since they are
1761 // guaranteed dead. Note that we may miss dead inputs this way but the
1762 // graph will always remain consistent.
1763 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1764 HInstruction* insn = it.Current();
1765 RemoveUsesOfDeadInstruction(insn);
1766 RemoveInstruction(insn);
1767 }
1768 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1769 HPhi* insn = it.Current()->AsPhi();
1770 RemoveUsesOfDeadInstruction(insn);
1771 RemovePhi(insn);
1772 }
1773
1774 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001775 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001776 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001777 // We should not see any back edges as they would have been removed by step (3).
1778 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1779
David Brazdil2d7352b2015-04-20 14:52:42 +01001780 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001781 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1782 // This block is the only normal-flow successor of the TryBoundary which
1783 // makes `predecessor` dead. Since DCE removes blocks in post order,
1784 // exception handlers of this TryBoundary were already visited and any
1785 // remaining handlers therefore must be live. We remove `predecessor` from
1786 // their list of predecessors.
1787 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1788 while (predecessor->GetSuccessors().size() > 1) {
1789 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1790 DCHECK(handler->IsCatchBlock());
1791 predecessor->RemoveSuccessor(handler);
1792 handler->RemovePredecessor(predecessor);
1793 }
1794 }
1795
David Brazdil2d7352b2015-04-20 14:52:42 +01001796 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001797 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1798 if (num_pred_successors == 1u) {
1799 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001800 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1801 // successor. Replace those with a HGoto.
1802 DCHECK(last_instruction->IsIf() ||
1803 last_instruction->IsPackedSwitch() ||
1804 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001805 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001806 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001807 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001808 // The predecessor has no remaining successors and therefore must be dead.
1809 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001810 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001811 predecessor->RemoveInstruction(last_instruction);
1812 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001813 // There are multiple successors left. The removed block might be a successor
1814 // of a PackedSwitch which will be completely removed (perhaps replaced with
1815 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1816 // case, leave `last_instruction` as is for now.
1817 DCHECK(last_instruction->IsPackedSwitch() ||
1818 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001819 }
David Brazdil46e2a392015-03-16 17:31:52 +00001820 }
Vladimir Marko60584552015-09-03 13:35:12 +00001821 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001822
David Brazdil9eeebf62016-03-24 11:18:15 +00001823 // (5) Remove the block from all loops it is included in. Skip the inner-most
1824 // loop if this is the loop header (see definition of `loop_update_start`)
1825 // because the loop header's predecessor list has been destroyed in step (4).
1826 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1827 HLoopInformation* loop_info = it.Current();
1828 loop_info->Remove(this);
1829 if (loop_info->IsBackEdge(*this)) {
1830 // If this was the last back edge of the loop, we deliberately leave the
1831 // loop in an inconsistent state and will fail GraphChecker unless the
1832 // entire loop is removed during the pass.
1833 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001834 }
1835 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001836
David Brazdil9eeebf62016-03-24 11:18:15 +00001837 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001838 dominator_->RemoveDominatedBlock(this);
1839 SetDominator(nullptr);
1840
David Brazdil9eeebf62016-03-24 11:18:15 +00001841 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001842 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001843 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001844}
1845
1846void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001847 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001848 DCHECK(ContainsElement(dominated_blocks_, other));
1849 DCHECK_EQ(GetSingleSuccessor(), other);
1850 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001851 DCHECK(other->GetPhis().IsEmpty());
1852
David Brazdil2d7352b2015-04-20 14:52:42 +01001853 // Move instructions from `other` to `this`.
1854 DCHECK(EndsWithControlFlowInstruction());
1855 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001856 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001857 other->instructions_.SetBlockOfInstructions(this);
1858 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001859
David Brazdil2d7352b2015-04-20 14:52:42 +01001860 // Remove `other` from the loops it is included in.
1861 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1862 HLoopInformation* loop_info = it.Current();
1863 loop_info->Remove(other);
1864 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001865 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001866 }
1867 }
1868
1869 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001870 successors_.clear();
1871 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001872 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001873 successor->ReplacePredecessor(other, this);
1874 }
1875
David Brazdil2d7352b2015-04-20 14:52:42 +01001876 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001877 RemoveDominatedBlock(other);
1878 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1879 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001880 dominated->SetDominator(this);
1881 }
Vladimir Marko60584552015-09-03 13:35:12 +00001882 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001883 other->dominator_ = nullptr;
1884
1885 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001886 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001887
1888 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001889 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001890 other->SetGraph(nullptr);
1891}
1892
1893void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1894 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001895 DCHECK(GetDominatedBlocks().empty());
1896 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001897 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001898 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001899 DCHECK(other->GetPhis().IsEmpty());
1900 DCHECK(!other->IsInLoop());
1901
1902 // Move instructions from `other` to `this`.
1903 instructions_.Add(other->GetInstructions());
1904 other->instructions_.SetBlockOfInstructions(this);
1905
1906 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001907 successors_.clear();
1908 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001909 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001910 successor->ReplacePredecessor(other, this);
1911 }
1912
1913 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001914 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1915 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 dominated->SetDominator(this);
1917 }
Vladimir Marko60584552015-09-03 13:35:12 +00001918 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001919 other->dominator_ = nullptr;
1920 other->graph_ = nullptr;
1921}
1922
1923void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001924 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001925 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001926 predecessor->ReplaceSuccessor(this, other);
1927 }
Vladimir Marko60584552015-09-03 13:35:12 +00001928 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001929 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 successor->ReplacePredecessor(this, other);
1931 }
Vladimir Marko60584552015-09-03 13:35:12 +00001932 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1933 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001934 }
1935 GetDominator()->ReplaceDominatedBlock(this, other);
1936 other->SetDominator(GetDominator());
1937 dominator_ = nullptr;
1938 graph_ = nullptr;
1939}
1940
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001941void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001942 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001943 DCHECK(block->GetSuccessors().empty());
1944 DCHECK(block->GetPredecessors().empty());
1945 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001946 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001947 DCHECK(block->GetInstructions().IsEmpty());
1948 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001949
David Brazdilc7af85d2015-05-26 12:05:55 +01001950 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001951 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001952 }
1953
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001954 RemoveElement(reverse_post_order_, block);
1955 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001956 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001957}
1958
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001959void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1960 HBasicBlock* reference,
1961 bool replace_if_back_edge) {
1962 if (block->IsLoopHeader()) {
1963 // Clear the information of which blocks are contained in that loop. Since the
1964 // information is stored as a bit vector based on block ids, we have to update
1965 // it, as those block ids were specific to the callee graph and we are now adding
1966 // these blocks to the caller graph.
1967 block->GetLoopInformation()->ClearAllBlocks();
1968 }
1969
1970 // If not already in a loop, update the loop information.
1971 if (!block->IsInLoop()) {
1972 block->SetLoopInformation(reference->GetLoopInformation());
1973 }
1974
1975 // If the block is in a loop, update all its outward loops.
1976 HLoopInformation* loop_info = block->GetLoopInformation();
1977 if (loop_info != nullptr) {
1978 for (HLoopInformationOutwardIterator loop_it(*block);
1979 !loop_it.Done();
1980 loop_it.Advance()) {
1981 loop_it.Current()->Add(block);
1982 }
1983 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1984 loop_info->ReplaceBackEdge(reference, block);
1985 }
1986 }
1987
1988 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1989 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1990 ? reference->GetTryCatchInformation()
1991 : nullptr;
1992 block->SetTryCatchInformation(try_catch_info);
1993}
1994
Calin Juravle2e768302015-07-28 14:41:11 +00001995HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001996 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001997 // Update the environments in this graph to have the invoke's environment
1998 // as parent.
1999 {
2000 HReversePostOrderIterator it(*this);
2001 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
2002 for (; !it.Done(); it.Advance()) {
2003 HBasicBlock* block = it.Current();
2004 for (HInstructionIterator instr_it(block->GetInstructions());
2005 !instr_it.Done();
2006 instr_it.Advance()) {
2007 HInstruction* current = instr_it.Current();
2008 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002009 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002010 current->GetEnvironment()->SetAndCopyParentChain(
2011 outer_graph->GetArena(), invoke->GetEnvironment());
2012 }
2013 }
2014 }
2015 }
2016 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
2017 if (HasBoundsChecks()) {
2018 outer_graph->SetHasBoundsChecks(true);
2019 }
2020
Calin Juravle2e768302015-07-28 14:41:11 +00002021 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002022 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002023 // Simple case of an entry block, a body block, and an exit block.
2024 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002025 HBasicBlock* body = GetBlocks()[1];
2026 DCHECK(GetBlocks()[0]->IsEntryBlock());
2027 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002028 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002029 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002030 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002031
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002032 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2033 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002034 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002035
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002036 // Replace the invoke with the return value of the inlined graph.
2037 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002038 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002039 } else {
2040 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002041 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002042
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002043 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002044 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002045 // Need to inline multiple blocks. We split `invoke`'s block
2046 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002047 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002048 // with the second half.
2049 ArenaAllocator* allocator = outer_graph->GetArena();
2050 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002051 // Note that we split before the invoke only to simplify polymorphic inlining.
2052 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002053
Vladimir Markoec7802a2015-10-01 20:57:57 +01002054 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002055 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002056 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002057 exit_block_->ReplaceWith(to);
2058
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002059 // Update the meta information surrounding blocks:
2060 // (1) the graph they are now in,
2061 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002062 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002063 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002064 // Note that we do not need to update catch phi inputs because they
2065 // correspond to the register file of the outer method which the inlinee
2066 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002067
2068 // We don't add the entry block, the exit block, and the first block, which
2069 // has been merged with `at`.
2070 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2071
2072 // We add the `to` block.
2073 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002074 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002075 + kNumberOfNewBlocksInCaller;
2076
2077 // Find the location of `at` in the outer graph's reverse post order. The new
2078 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002079 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002080 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2081
David Brazdil95177982015-10-30 12:56:58 -05002082 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2083 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002084 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2085 HBasicBlock* current = it.Current();
2086 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002087 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002088 DCHECK(current->GetGraph() == this);
2089 current->SetGraph(outer_graph);
2090 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002091 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002092 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002093 }
2094 }
2095
David Brazdil95177982015-10-30 12:56:58 -05002096 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002097 to->SetGraph(outer_graph);
2098 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002099 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002100 // Only `to` can become a back edge, as the inlined blocks
2101 // are predecessors of `to`.
2102 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002103
David Brazdil3f523062016-02-29 16:53:33 +00002104 // Update all predecessors of the exit block (now the `to` block)
2105 // to not `HReturn` but `HGoto` instead.
2106 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2107 if (to->GetPredecessors().size() == 1) {
2108 HBasicBlock* predecessor = to->GetPredecessors()[0];
2109 HInstruction* last = predecessor->GetLastInstruction();
2110 if (!returns_void) {
2111 return_value = last->InputAt(0);
2112 }
2113 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2114 predecessor->RemoveInstruction(last);
2115 } else {
2116 if (!returns_void) {
2117 // There will be multiple returns.
2118 return_value = new (allocator) HPhi(
2119 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2120 to->AddPhi(return_value->AsPhi());
2121 }
2122 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2123 HInstruction* last = predecessor->GetLastInstruction();
2124 if (!returns_void) {
2125 DCHECK(last->IsReturn());
2126 return_value->AsPhi()->AddInput(last->InputAt(0));
2127 }
2128 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2129 predecessor->RemoveInstruction(last);
2130 }
2131 }
2132 }
David Brazdil05144f42015-04-16 15:18:00 +01002133
2134 // Walk over the entry block and:
2135 // - Move constants from the entry block to the outer_graph's entry block,
2136 // - Replace HParameterValue instructions with their real value.
2137 // - Remove suspend checks, that hold an environment.
2138 // We must do this after the other blocks have been inlined, otherwise ids of
2139 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002140 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002141 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2142 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002143 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002144 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002145 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002146 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002147 replacement = outer_graph->GetIntConstant(
2148 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002149 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002150 replacement = outer_graph->GetLongConstant(
2151 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002152 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002153 replacement = outer_graph->GetFloatConstant(
2154 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002155 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002156 replacement = outer_graph->GetDoubleConstant(
2157 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002158 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002159 if (kIsDebugBuild
2160 && invoke->IsInvokeStaticOrDirect()
2161 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2162 // Ensure we do not use the last input of `invoke`, as it
2163 // contains a clinit check which is not an actual argument.
2164 size_t last_input_index = invoke->InputCount() - 1;
2165 DCHECK(parameter_index != last_input_index);
2166 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002167 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002168 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002169 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002170 } else {
2171 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2172 entry_block_->RemoveInstruction(current);
2173 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002174 if (replacement != nullptr) {
2175 current->ReplaceWith(replacement);
2176 // If the current is the return value then we need to update the latter.
2177 if (current == return_value) {
2178 DCHECK_EQ(entry_block_, return_value->GetBlock());
2179 return_value = replacement;
2180 }
2181 }
2182 }
2183
Calin Juravle2e768302015-07-28 14:41:11 +00002184 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002185}
2186
Mingyao Yang3584bce2015-05-19 16:01:59 -07002187/*
2188 * Loop will be transformed to:
2189 * old_pre_header
2190 * |
2191 * if_block
2192 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002193 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002194 * \ /
2195 * new_pre_header
2196 * |
2197 * header
2198 */
2199void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2200 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002201 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002202
Aart Bik3fc7f352015-11-20 22:03:03 -08002203 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002204 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002205 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2206 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002207 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2208 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002209 AddBlock(true_block);
2210 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002211 AddBlock(new_pre_header);
2212
Aart Bik3fc7f352015-11-20 22:03:03 -08002213 header->ReplacePredecessor(old_pre_header, new_pre_header);
2214 old_pre_header->successors_.clear();
2215 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002216
Aart Bik3fc7f352015-11-20 22:03:03 -08002217 old_pre_header->AddSuccessor(if_block);
2218 if_block->AddSuccessor(true_block); // True successor
2219 if_block->AddSuccessor(false_block); // False successor
2220 true_block->AddSuccessor(new_pre_header);
2221 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002222
Aart Bik3fc7f352015-11-20 22:03:03 -08002223 old_pre_header->dominated_blocks_.push_back(if_block);
2224 if_block->SetDominator(old_pre_header);
2225 if_block->dominated_blocks_.push_back(true_block);
2226 true_block->SetDominator(if_block);
2227 if_block->dominated_blocks_.push_back(false_block);
2228 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002229 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002230 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002231 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002232 header->SetDominator(new_pre_header);
2233
Aart Bik3fc7f352015-11-20 22:03:03 -08002234 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002235 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002236 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002237 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002238 reverse_post_order_[index_of_header++] = true_block;
2239 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002240 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002241
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002242 // The pre_header can never be a back edge of a loop.
2243 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2244 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2245 UpdateLoopAndTryInformationOfNewBlock(
2246 if_block, old_pre_header, /* replace_if_back_edge */ false);
2247 UpdateLoopAndTryInformationOfNewBlock(
2248 true_block, old_pre_header, /* replace_if_back_edge */ false);
2249 UpdateLoopAndTryInformationOfNewBlock(
2250 false_block, old_pre_header, /* replace_if_back_edge */ false);
2251 UpdateLoopAndTryInformationOfNewBlock(
2252 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002253}
2254
David Brazdilf5552582015-12-27 13:36:12 +00002255static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2256 SHARED_REQUIRES(Locks::mutator_lock_) {
2257 if (rti.IsValid()) {
2258 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2259 << " upper_bound_rti: " << upper_bound_rti
2260 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002261 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2262 << " upper_bound_rti: " << upper_bound_rti
2263 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002264 }
2265}
2266
Calin Juravle2e768302015-07-28 14:41:11 +00002267void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2268 if (kIsDebugBuild) {
2269 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2270 ScopedObjectAccess soa(Thread::Current());
2271 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2272 if (IsBoundType()) {
2273 // Having the test here spares us from making the method virtual just for
2274 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002275 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002276 }
2277 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002278 reference_type_handle_ = rti.GetTypeHandle();
2279 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002280}
2281
David Brazdilf5552582015-12-27 13:36:12 +00002282void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2283 if (kIsDebugBuild) {
2284 ScopedObjectAccess soa(Thread::Current());
2285 DCHECK(upper_bound.IsValid());
2286 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2287 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2288 }
2289 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002290 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002291}
2292
Vladimir Markoa1de9182016-02-25 11:37:38 +00002293ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002294 if (kIsDebugBuild) {
2295 ScopedObjectAccess soa(Thread::Current());
2296 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002297 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002298 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002299 if (!is_exact) {
2300 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2301 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2302 }
Calin Juravle2e768302015-07-28 14:41:11 +00002303 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002304 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002305}
2306
Calin Juravleacf735c2015-02-12 15:25:22 +00002307std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2308 ScopedObjectAccess soa(Thread::Current());
2309 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002310 << " is_valid=" << rhs.IsValid()
2311 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002312 << " is_exact=" << rhs.IsExact()
2313 << " ]";
2314 return os;
2315}
2316
Mark Mendellc4701932015-04-10 13:18:51 -04002317bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2318 // For now, assume that instructions in different blocks may use the
2319 // environment.
2320 // TODO: Use the control flow to decide if this is true.
2321 if (GetBlock() != other->GetBlock()) {
2322 return true;
2323 }
2324
2325 // We know that we are in the same block. Walk from 'this' to 'other',
2326 // checking to see if there is any instruction with an environment.
2327 HInstruction* current = this;
2328 for (; current != other && current != nullptr; current = current->GetNext()) {
2329 // This is a conservative check, as the instruction result may not be in
2330 // the referenced environment.
2331 if (current->HasEnvironment()) {
2332 return true;
2333 }
2334 }
2335
2336 // We should have been called with 'this' before 'other' in the block.
2337 // Just confirm this.
2338 DCHECK(current != nullptr);
2339 return false;
2340}
2341
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002342void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002343 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2344 IntrinsicSideEffects side_effects,
2345 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002346 intrinsic_ = intrinsic;
2347 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002348
Aart Bik5d75afe2015-12-14 11:57:01 -08002349 // Adjust method's side effects from intrinsic table.
2350 switch (side_effects) {
2351 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2352 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2353 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2354 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2355 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002356
2357 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2358 opt.SetDoesNotNeedDexCache();
2359 opt.SetDoesNotNeedEnvironment();
2360 } else {
2361 // If we need an environment, that means there will be a call, which can trigger GC.
2362 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2363 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002364 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002365 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002366}
2367
David Brazdil6de19382016-01-08 17:37:10 +00002368bool HNewInstance::IsStringAlloc() const {
2369 ScopedObjectAccess soa(Thread::Current());
2370 return GetReferenceTypeInfo().IsStringClass();
2371}
2372
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002373bool HInvoke::NeedsEnvironment() const {
2374 if (!IsIntrinsic()) {
2375 return true;
2376 }
2377 IntrinsicOptimizations opt(*this);
2378 return !opt.GetDoesNotNeedEnvironment();
2379}
2380
Vladimir Markodc151b22015-10-15 18:02:30 +01002381bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2382 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002383 return false;
2384 }
2385 if (!IsIntrinsic()) {
2386 return true;
2387 }
2388 IntrinsicOptimizations opt(*this);
2389 return !opt.GetDoesNotNeedDexCache();
2390}
2391
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002392void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2393 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2394 input->AddUseAt(this, index);
2395 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002396 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
2397 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
2398 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002399 }
2400}
2401
Vladimir Markob554b5a2015-11-06 12:57:55 +00002402void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2403 RemoveAsUserOfInput(index);
2404 inputs_.erase(inputs_.begin() + index);
2405 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002406 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
2407 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
2408 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Markob554b5a2015-11-06 12:57:55 +00002409 }
2410}
2411
Vladimir Markof64242a2015-12-01 14:58:23 +00002412std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2413 switch (rhs) {
2414 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2415 return os << "string_init";
2416 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2417 return os << "recursive";
2418 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2419 return os << "direct";
2420 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2421 return os << "direct_fixup";
2422 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2423 return os << "dex_cache_pc_relative";
2424 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2425 return os << "dex_cache_via_method";
2426 default:
2427 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2428 UNREACHABLE();
2429 }
2430}
2431
Vladimir Markofbb184a2015-11-13 14:47:00 +00002432std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2433 switch (rhs) {
2434 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2435 return os << "explicit";
2436 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2437 return os << "implicit";
2438 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2439 return os << "none";
2440 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002441 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2442 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002443 }
2444}
2445
Vladimir Marko372f10e2016-05-17 16:30:10 +01002446bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2447 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002448 if (string_index_ != other_load_string->string_index_ ||
2449 GetPackedFields() != other_load_string->GetPackedFields()) {
2450 return false;
2451 }
2452 LoadKind load_kind = GetLoadKind();
2453 if (HasAddress(load_kind)) {
2454 return GetAddress() == other_load_string->GetAddress();
2455 } else if (HasStringReference(load_kind)) {
2456 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2457 } else {
2458 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2459 // If the string indexes and dex files are the same, dex cache element offsets
2460 // must also be the same, so we don't need to compare them.
2461 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2462 }
2463}
2464
2465void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2466 // Once sharpened, the load kind should not be changed again.
2467 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2468 SetPackedField<LoadKindField>(load_kind);
2469
2470 if (load_kind != LoadKind::kDexCacheViaMethod) {
2471 RemoveAsUserOfInput(0u);
2472 SetRawInputAt(0u, nullptr);
2473 }
2474 if (!NeedsEnvironment()) {
2475 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002476 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002477 }
2478}
2479
2480std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2481 switch (rhs) {
2482 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2483 return os << "BootImageLinkTimeAddress";
2484 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2485 return os << "BootImageLinkTimePcRelative";
2486 case HLoadString::LoadKind::kBootImageAddress:
2487 return os << "BootImageAddress";
2488 case HLoadString::LoadKind::kDexCacheAddress:
2489 return os << "DexCacheAddress";
2490 case HLoadString::LoadKind::kDexCachePcRelative:
2491 return os << "DexCachePcRelative";
2492 case HLoadString::LoadKind::kDexCacheViaMethod:
2493 return os << "DexCacheViaMethod";
2494 default:
2495 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2496 UNREACHABLE();
2497 }
2498}
2499
Mark Mendellc4701932015-04-10 13:18:51 -04002500void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002501 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2502 HEnvironment* user = use.GetUser();
2503 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002504 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002505 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002506}
2507
Roland Levillainc9b21f82016-03-23 16:36:59 +00002508// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002509HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2510 ArenaAllocator* allocator = GetArena();
2511
2512 if (cond->IsCondition() &&
2513 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2514 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2515 HInstruction* lhs = cond->InputAt(0);
2516 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002517 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002518 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2519 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2520 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2521 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2522 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2523 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2524 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2525 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2526 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2527 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2528 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002529 default:
2530 LOG(FATAL) << "Unexpected condition";
2531 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002532 }
2533 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2534 return replacement;
2535 } else if (cond->IsIntConstant()) {
2536 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002537 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002538 return GetIntConstant(1);
2539 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002540 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002541 return GetIntConstant(0);
2542 }
2543 } else {
2544 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2545 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2546 return replacement;
2547 }
2548}
2549
Roland Levillainc9285912015-12-18 10:38:42 +00002550std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2551 os << "["
2552 << " source=" << rhs.GetSource()
2553 << " destination=" << rhs.GetDestination()
2554 << " type=" << rhs.GetType()
2555 << " instruction=";
2556 if (rhs.GetInstruction() != nullptr) {
2557 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2558 } else {
2559 os << "null";
2560 }
2561 os << " ]";
2562 return os;
2563}
2564
Roland Levillain86503782016-02-11 19:07:30 +00002565std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2566 switch (rhs) {
2567 case TypeCheckKind::kUnresolvedCheck:
2568 return os << "unresolved_check";
2569 case TypeCheckKind::kExactCheck:
2570 return os << "exact_check";
2571 case TypeCheckKind::kClassHierarchyCheck:
2572 return os << "class_hierarchy_check";
2573 case TypeCheckKind::kAbstractClassCheck:
2574 return os << "abstract_class_check";
2575 case TypeCheckKind::kInterfaceCheck:
2576 return os << "interface_check";
2577 case TypeCheckKind::kArrayObjectCheck:
2578 return os << "array_object_check";
2579 case TypeCheckKind::kArrayCheck:
2580 return os << "array_check";
2581 default:
2582 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2583 UNREACHABLE();
2584 }
2585}
2586
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002587} // namespace art