blob: f1ca9288513bdb0160c5b2830d2e5664a8a1f147 [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"
Mathieu Chartier0795f232016-09-27 18:43:30 -070028#include "scoped_thread_state_change-inl.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
Aart Bik20e9db62016-09-14 10:52:13 -0700463static bool InSameLoop(HLoopInformation* first_loop, HLoopInformation* second_loop) {
464 return first_loop == second_loop;
465}
466
467static bool IsLoop(HLoopInformation* info) {
468 return info != nullptr;
469}
470
471static bool IsInnerLoop(HLoopInformation* outer, HLoopInformation* inner) {
472 return (inner != outer)
473 && (inner != nullptr)
474 && (outer != nullptr)
475 && inner->IsIn(*outer);
476}
477
478// Helper method to update work list for linear order.
479static void AddToListForLinearization(ArenaVector<HBasicBlock*>* worklist, HBasicBlock* block) {
480 HLoopInformation* block_loop = block->GetLoopInformation();
481 auto insert_pos = worklist->rbegin(); // insert_pos.base() will be the actual position.
482 for (auto end = worklist->rend(); insert_pos != end; ++insert_pos) {
483 HBasicBlock* current = *insert_pos;
484 HLoopInformation* current_loop = current->GetLoopInformation();
485 if (InSameLoop(block_loop, current_loop)
486 || !IsLoop(current_loop)
487 || IsInnerLoop(current_loop, block_loop)) {
488 // The block can be processed immediately.
489 break;
490 }
491 }
492 worklist->insert(insert_pos.base(), block);
493}
494
495// Helper method to validate linear order.
496static bool IsLinearOrderWellFormed(const HGraph& graph) {
497 for (HBasicBlock* header : graph.GetBlocks()) {
498 if (header == nullptr || !header->IsLoopHeader()) {
499 continue;
500 }
501 HLoopInformation* loop = header->GetLoopInformation();
502 size_t num_blocks = loop->GetBlocks().NumSetBits();
503 size_t found_blocks = 0u;
504 for (HLinearOrderIterator it(graph); !it.Done(); it.Advance()) {
505 HBasicBlock* current = it.Current();
506 if (loop->Contains(*current)) {
507 found_blocks++;
508 if (found_blocks == 1u && current != header) {
509 // First block is not the header.
510 return false;
511 } else if (found_blocks == num_blocks && !loop->IsBackEdge(*current)) {
512 // Last block is not a back edge.
513 return false;
514 }
515 } else if (found_blocks != 0u && found_blocks != num_blocks) {
516 // Blocks are not adjacent.
517 return false;
518 }
519 }
520 DCHECK_EQ(found_blocks, num_blocks);
521 }
522 return true;
523}
524
Aart Bik281c6812016-08-26 11:31:48 -0700525// TODO: return order, and give only liveness analysis ownership of graph's linear_order_?
Aart Bik20e9db62016-09-14 10:52:13 -0700526void HGraph::Linearize() {
Aart Bik281c6812016-08-26 11:31:48 -0700527 linear_order_.clear();
528
Aart Bik20e9db62016-09-14 10:52:13 -0700529 // Create a reverse post ordering with the following properties:
530 // - Blocks in a loop are consecutive,
531 // - Back-edge is the last block before loop exits.
532
533 // (1): Record the number of forward predecessors for each block. This is to
534 // ensure the resulting order is reverse post order. We could use the
535 // current reverse post order in the graph, but it would require making
536 // order queries to a GrowableArray, which is not the best data structure
537 // for it.
538 ArenaVector<uint32_t> forward_predecessors(blocks_.size(),
539 arena_->Adapter(kArenaAllocSsaLiveness));
540 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
541 HBasicBlock* block = it.Current();
542 size_t number_of_forward_predecessors = block->GetPredecessors().size();
543 if (block->IsLoopHeader()) {
544 number_of_forward_predecessors -= block->GetLoopInformation()->NumberOfBackEdges();
545 }
546 forward_predecessors[block->GetBlockId()] = number_of_forward_predecessors;
547 }
548
549 // (2): Following a worklist approach, first start with the entry block, and
550 // iterate over the successors. When all non-back edge predecessors of a
551 // successor block are visited, the successor block is added in the worklist
552 // following an order that satisfies the requirements to build our linear graph.
553 linear_order_.reserve(GetReversePostOrder().size());
554 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocSsaLiveness));
555 worklist.push_back(GetEntryBlock());
556 do {
557 HBasicBlock* current = worklist.back();
558 worklist.pop_back();
559 linear_order_.push_back(current);
560 for (HBasicBlock* successor : current->GetSuccessors()) {
561 int block_id = successor->GetBlockId();
562 size_t number_of_remaining_predecessors = forward_predecessors[block_id];
563 if (number_of_remaining_predecessors == 1) {
564 AddToListForLinearization(&worklist, successor);
565 }
566 forward_predecessors[block_id] = number_of_remaining_predecessors - 1;
567 }
568 } while (!worklist.empty());
569
570 DCHECK(HasIrreducibleLoops() || IsLinearOrderWellFormed(*this));
571}
572
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000573void HLoopInformation::Dump(std::ostream& os) {
574 os << "header: " << header_->GetBlockId() << std::endl;
575 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
576 for (HBasicBlock* block : back_edges_) {
577 os << "back edge: " << block->GetBlockId() << std::endl;
578 }
579 for (HBasicBlock* block : header_->GetPredecessors()) {
580 os << "predecessor: " << block->GetBlockId() << std::endl;
581 }
582 for (uint32_t idx : blocks_.Indexes()) {
583 os << " in loop: " << idx << std::endl;
584 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100585}
586
David Brazdil8d5b8b22015-03-24 10:51:52 +0000587void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000588 // New constants are inserted before the SuspendCheck at the bottom of the
589 // entry block. Note that this method can be called from the graph builder and
590 // the entry block therefore may not end with SuspendCheck->Goto yet.
591 HInstruction* insert_before = nullptr;
592
593 HInstruction* gota = entry_block_->GetLastInstruction();
594 if (gota != nullptr && gota->IsGoto()) {
595 HInstruction* suspend_check = gota->GetPrevious();
596 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
597 insert_before = suspend_check;
598 } else {
599 insert_before = gota;
600 }
601 }
602
603 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000604 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000605 } else {
606 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000607 }
608}
609
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600610HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100611 // For simplicity, don't bother reviving the cached null constant if it is
612 // not null and not in a block. Otherwise, we need to clear the instruction
613 // id and/or any invariants the graph is assuming when adding new instructions.
614 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600615 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000616 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000617 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000618 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000619 if (kIsDebugBuild) {
620 ScopedObjectAccess soa(Thread::Current());
621 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
622 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000623 return cached_null_constant_;
624}
625
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100626HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100627 // For simplicity, don't bother reviving the cached current method if it is
628 // not null and not in a block. Otherwise, we need to clear the instruction
629 // id and/or any invariants the graph is assuming when adding new instructions.
630 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700631 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600632 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
633 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100634 if (entry_block_->GetFirstInstruction() == nullptr) {
635 entry_block_->AddInstruction(cached_current_method_);
636 } else {
637 entry_block_->InsertInstructionBefore(
638 cached_current_method_, entry_block_->GetFirstInstruction());
639 }
640 }
641 return cached_current_method_;
642}
643
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600644HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000645 switch (type) {
646 case Primitive::Type::kPrimBoolean:
647 DCHECK(IsUint<1>(value));
648 FALLTHROUGH_INTENDED;
649 case Primitive::Type::kPrimByte:
650 case Primitive::Type::kPrimChar:
651 case Primitive::Type::kPrimShort:
652 case Primitive::Type::kPrimInt:
653 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600654 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000655
656 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600657 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000658
659 default:
660 LOG(FATAL) << "Unsupported constant type";
661 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000662 }
David Brazdil46e2a392015-03-16 17:31:52 +0000663}
664
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000665void HGraph::CacheFloatConstant(HFloatConstant* constant) {
666 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
667 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
668 cached_float_constants_.Overwrite(value, constant);
669}
670
671void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
672 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
673 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
674 cached_double_constants_.Overwrite(value, constant);
675}
676
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000677void HLoopInformation::Add(HBasicBlock* block) {
678 blocks_.SetBit(block->GetBlockId());
679}
680
David Brazdil46e2a392015-03-16 17:31:52 +0000681void HLoopInformation::Remove(HBasicBlock* block) {
682 blocks_.ClearBit(block->GetBlockId());
683}
684
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100685void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
686 if (blocks_.IsBitSet(block->GetBlockId())) {
687 return;
688 }
689
690 blocks_.SetBit(block->GetBlockId());
691 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100692 if (block->IsLoopHeader()) {
693 // We're visiting loops in post-order, so inner loops must have been
694 // populated already.
695 DCHECK(block->GetLoopInformation()->IsPopulated());
696 if (block->GetLoopInformation()->IsIrreducible()) {
697 contains_irreducible_loop_ = true;
698 }
699 }
Vladimir Marko60584552015-09-03 13:35:12 +0000700 for (HBasicBlock* predecessor : block->GetPredecessors()) {
701 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100702 }
703}
704
David Brazdilc2e8af92016-04-05 17:15:19 +0100705void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
706 size_t block_id = block->GetBlockId();
707
708 // If `block` is in `finalized`, we know its membership in the loop has been
709 // decided and it does not need to be revisited.
710 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000711 return;
712 }
713
David Brazdilc2e8af92016-04-05 17:15:19 +0100714 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000715 if (block->IsLoopHeader()) {
716 // If we hit a loop header in an irreducible loop, we first check if the
717 // pre header of that loop belongs to the currently analyzed loop. If it does,
718 // then we visit the back edges.
719 // Note that we cannot use GetPreHeader, as the loop may have not been populated
720 // yet.
721 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100722 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000723 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000724 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100725 blocks_.SetBit(block_id);
726 finalized->SetBit(block_id);
727 is_finalized = true;
728
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000729 HLoopInformation* info = block->GetLoopInformation();
730 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100731 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000732 }
733 }
734 } else {
735 // Visit all predecessors. If one predecessor is part of the loop, this
736 // block is also part of this loop.
737 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100738 PopulateIrreducibleRecursive(predecessor, finalized);
739 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000740 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100741 blocks_.SetBit(block_id);
742 finalized->SetBit(block_id);
743 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000744 }
745 }
746 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100747
748 // All predecessors have been recursively visited. Mark finalized if not marked yet.
749 if (!is_finalized) {
750 finalized->SetBit(block_id);
751 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000752}
753
754void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100755 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000756 // Populate this loop: starting with the back edge, recursively add predecessors
757 // that are not already part of that loop. Set the header as part of the loop
758 // to end the recursion.
759 // This is a recursive implementation of the algorithm described in
760 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100761 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000762 blocks_.SetBit(header_->GetBlockId());
763 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100764
David Brazdil3f4a5222016-05-06 12:46:21 +0100765 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100766
767 if (is_irreducible_loop) {
768 ArenaBitVector visited(graph->GetArena(),
769 graph->GetBlocks().size(),
770 /* expandable */ false,
771 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100772 // Stop marking blocks at the loop header.
773 visited.SetBit(header_->GetBlockId());
774
David Brazdilc2e8af92016-04-05 17:15:19 +0100775 for (HBasicBlock* back_edge : GetBackEdges()) {
776 PopulateIrreducibleRecursive(back_edge, &visited);
777 }
778 } else {
779 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000780 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100781 }
David Brazdila4b8c212015-05-07 09:59:30 +0100782 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100783
Vladimir Markofd66c502016-04-18 15:37:01 +0100784 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
785 // When compiling in OSR mode, all loops in the compiled method may be entered
786 // from the interpreter. We treat this OSR entry point just like an extra entry
787 // to an irreducible loop, so we need to mark the method's loops as irreducible.
788 // This does not apply to inlined loops which do not act as OSR entry points.
789 if (suspend_check_ == nullptr) {
790 // Just building the graph in OSR mode, this loop is not inlined. We never build an
791 // inner graph in OSR mode as we can do OSR transition only from the outer method.
792 is_irreducible_loop = true;
793 } else {
794 // Look at the suspend check's environment to determine if the loop was inlined.
795 DCHECK(suspend_check_->HasEnvironment());
796 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
797 is_irreducible_loop = true;
798 }
799 }
800 }
801 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100802 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100803 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100804 graph->SetHasIrreducibleLoops(true);
805 }
David Brazdila4b8c212015-05-07 09:59:30 +0100806}
807
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100808HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000809 HBasicBlock* block = header_->GetPredecessors()[0];
810 DCHECK(irreducible_ || (block == header_->GetDominator()));
811 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100812}
813
814bool HLoopInformation::Contains(const HBasicBlock& block) const {
815 return blocks_.IsBitSet(block.GetBlockId());
816}
817
818bool HLoopInformation::IsIn(const HLoopInformation& other) const {
819 return other.blocks_.IsBitSet(header_->GetBlockId());
820}
821
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800822bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
823 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700824}
825
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100826size_t HLoopInformation::GetLifetimeEnd() const {
827 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100828 for (HBasicBlock* back_edge : GetBackEdges()) {
829 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100830 }
831 return last_position;
832}
833
David Brazdil3f4a5222016-05-06 12:46:21 +0100834bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
835 for (HBasicBlock* back_edge : GetBackEdges()) {
836 DCHECK(back_edge->GetDominator() != nullptr);
837 if (!header_->Dominates(back_edge)) {
838 return true;
839 }
840 }
841 return false;
842}
843
Anton Shaminf89381f2016-05-16 16:44:13 +0600844bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
845 for (HBasicBlock* back_edge : GetBackEdges()) {
846 if (!block->Dominates(back_edge)) {
847 return false;
848 }
849 }
850 return true;
851}
852
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100853bool HBasicBlock::Dominates(HBasicBlock* other) const {
854 // Walk up the dominator tree from `other`, to find out if `this`
855 // is an ancestor.
856 HBasicBlock* current = other;
857 while (current != nullptr) {
858 if (current == this) {
859 return true;
860 }
861 current = current->GetDominator();
862 }
863 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100864}
865
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100866static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100867 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100868 for (size_t i = 0; i < inputs.size(); ++i) {
869 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100870 }
871 // Environment should be created later.
872 DCHECK(!instruction->HasEnvironment());
873}
874
Roland Levillainccc07a92014-09-16 14:48:16 +0100875void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
876 HInstruction* replacement) {
877 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400878 if (initial->IsControlFlow()) {
879 // We can only replace a control flow instruction with another control flow instruction.
880 DCHECK(replacement->IsControlFlow());
881 DCHECK_EQ(replacement->GetId(), -1);
882 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
883 DCHECK_EQ(initial->GetBlock(), this);
884 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100885 DCHECK(initial->GetUses().empty());
886 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400887 replacement->SetBlock(this);
888 replacement->SetId(GetGraph()->GetNextInstructionId());
889 instructions_.InsertInstructionBefore(replacement, initial);
890 UpdateInputsUsers(replacement);
891 } else {
892 InsertInstructionBefore(replacement, initial);
893 initial->ReplaceWith(replacement);
894 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100895 RemoveInstruction(initial);
896}
897
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100898static void Add(HInstructionList* instruction_list,
899 HBasicBlock* block,
900 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000901 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000902 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100903 instruction->SetBlock(block);
904 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100905 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100906 instruction_list->AddInstruction(instruction);
907}
908
909void HBasicBlock::AddInstruction(HInstruction* instruction) {
910 Add(&instructions_, this, instruction);
911}
912
913void HBasicBlock::AddPhi(HPhi* phi) {
914 Add(&phis_, this, phi);
915}
916
David Brazdilc3d743f2015-04-22 13:40:50 +0100917void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
918 DCHECK(!cursor->IsPhi());
919 DCHECK(!instruction->IsPhi());
920 DCHECK_EQ(instruction->GetId(), -1);
921 DCHECK_NE(cursor->GetId(), -1);
922 DCHECK_EQ(cursor->GetBlock(), this);
923 DCHECK(!instruction->IsControlFlow());
924 instruction->SetBlock(this);
925 instruction->SetId(GetGraph()->GetNextInstructionId());
926 UpdateInputsUsers(instruction);
927 instructions_.InsertInstructionBefore(instruction, cursor);
928}
929
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100930void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
931 DCHECK(!cursor->IsPhi());
932 DCHECK(!instruction->IsPhi());
933 DCHECK_EQ(instruction->GetId(), -1);
934 DCHECK_NE(cursor->GetId(), -1);
935 DCHECK_EQ(cursor->GetBlock(), this);
936 DCHECK(!instruction->IsControlFlow());
937 DCHECK(!cursor->IsControlFlow());
938 instruction->SetBlock(this);
939 instruction->SetId(GetGraph()->GetNextInstructionId());
940 UpdateInputsUsers(instruction);
941 instructions_.InsertInstructionAfter(instruction, cursor);
942}
943
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100944void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
945 DCHECK_EQ(phi->GetId(), -1);
946 DCHECK_NE(cursor->GetId(), -1);
947 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100948 phi->SetBlock(this);
949 phi->SetId(GetGraph()->GetNextInstructionId());
950 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100951 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100952}
953
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100954static void Remove(HInstructionList* instruction_list,
955 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000956 HInstruction* instruction,
957 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100958 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100959 instruction->SetBlock(nullptr);
960 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000961 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100962 DCHECK(instruction->GetUses().empty());
963 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000964 RemoveAsUser(instruction);
965 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100966}
967
David Brazdil1abb4192015-02-17 18:33:36 +0000968void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100969 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000970 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100971}
972
David Brazdil1abb4192015-02-17 18:33:36 +0000973void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
974 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100975}
976
David Brazdilc7508e92015-04-27 13:28:57 +0100977void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
978 if (instruction->IsPhi()) {
979 RemovePhi(instruction->AsPhi(), ensure_safety);
980 } else {
981 RemoveInstruction(instruction, ensure_safety);
982 }
983}
984
Vladimir Marko71bf8092015-09-15 15:33:14 +0100985void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
986 for (size_t i = 0; i < locals.size(); i++) {
987 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100988 SetRawEnvAt(i, instruction);
989 if (instruction != nullptr) {
990 instruction->AddEnvUseAt(this, i);
991 }
992 }
993}
994
David Brazdiled596192015-01-23 10:39:45 +0000995void HEnvironment::CopyFrom(HEnvironment* env) {
996 for (size_t i = 0; i < env->Size(); i++) {
997 HInstruction* instruction = env->GetInstructionAt(i);
998 SetRawEnvAt(i, instruction);
999 if (instruction != nullptr) {
1000 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001001 }
David Brazdiled596192015-01-23 10:39:45 +00001002 }
1003}
1004
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001005void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1006 HBasicBlock* loop_header) {
1007 DCHECK(loop_header->IsLoopHeader());
1008 for (size_t i = 0; i < env->Size(); i++) {
1009 HInstruction* instruction = env->GetInstructionAt(i);
1010 SetRawEnvAt(i, instruction);
1011 if (instruction == nullptr) {
1012 continue;
1013 }
1014 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1015 // At the end of the loop pre-header, the corresponding value for instruction
1016 // is the first input of the phi.
1017 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001018 SetRawEnvAt(i, initial);
1019 initial->AddEnvUseAt(this, i);
1020 } else {
1021 instruction->AddEnvUseAt(this, i);
1022 }
1023 }
1024}
1025
David Brazdil1abb4192015-02-17 18:33:36 +00001026void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001027 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1028 HInstruction* user = env_use.GetInstruction();
1029 auto before_env_use_node = env_use.GetBeforeUseNode();
1030 user->env_uses_.erase_after(before_env_use_node);
1031 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001032}
1033
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001034HInstruction::InstructionKind HInstruction::GetKind() const {
1035 return GetKindInternal();
1036}
1037
Calin Juravle77520bc2015-01-12 18:45:46 +00001038HInstruction* HInstruction::GetNextDisregardingMoves() const {
1039 HInstruction* next = GetNext();
1040 while (next != nullptr && next->IsParallelMove()) {
1041 next = next->GetNext();
1042 }
1043 return next;
1044}
1045
1046HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1047 HInstruction* previous = GetPrevious();
1048 while (previous != nullptr && previous->IsParallelMove()) {
1049 previous = previous->GetPrevious();
1050 }
1051 return previous;
1052}
1053
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001054void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001055 if (first_instruction_ == nullptr) {
1056 DCHECK(last_instruction_ == nullptr);
1057 first_instruction_ = last_instruction_ = instruction;
1058 } else {
1059 last_instruction_->next_ = instruction;
1060 instruction->previous_ = last_instruction_;
1061 last_instruction_ = instruction;
1062 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001063}
1064
David Brazdilc3d743f2015-04-22 13:40:50 +01001065void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1066 DCHECK(Contains(cursor));
1067 if (cursor == first_instruction_) {
1068 cursor->previous_ = instruction;
1069 instruction->next_ = cursor;
1070 first_instruction_ = instruction;
1071 } else {
1072 instruction->previous_ = cursor->previous_;
1073 instruction->next_ = cursor;
1074 cursor->previous_ = instruction;
1075 instruction->previous_->next_ = instruction;
1076 }
1077}
1078
1079void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1080 DCHECK(Contains(cursor));
1081 if (cursor == last_instruction_) {
1082 cursor->next_ = instruction;
1083 instruction->previous_ = cursor;
1084 last_instruction_ = instruction;
1085 } else {
1086 instruction->next_ = cursor->next_;
1087 instruction->previous_ = cursor;
1088 cursor->next_ = instruction;
1089 instruction->next_->previous_ = instruction;
1090 }
1091}
1092
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001093void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1094 if (instruction->previous_ != nullptr) {
1095 instruction->previous_->next_ = instruction->next_;
1096 }
1097 if (instruction->next_ != nullptr) {
1098 instruction->next_->previous_ = instruction->previous_;
1099 }
1100 if (instruction == first_instruction_) {
1101 first_instruction_ = instruction->next_;
1102 }
1103 if (instruction == last_instruction_) {
1104 last_instruction_ = instruction->previous_;
1105 }
1106}
1107
Roland Levillain6b469232014-09-25 10:10:38 +01001108bool HInstructionList::Contains(HInstruction* instruction) const {
1109 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1110 if (it.Current() == instruction) {
1111 return true;
1112 }
1113 }
1114 return false;
1115}
1116
Roland Levillainccc07a92014-09-16 14:48:16 +01001117bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1118 const HInstruction* instruction2) const {
1119 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1120 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1121 if (it.Current() == instruction1) {
1122 return true;
1123 }
1124 if (it.Current() == instruction2) {
1125 return false;
1126 }
1127 }
1128 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1129 return true;
1130}
1131
Roland Levillain6c82d402014-10-13 16:10:27 +01001132bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1133 if (other_instruction == this) {
1134 // An instruction does not strictly dominate itself.
1135 return false;
1136 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001137 HBasicBlock* block = GetBlock();
1138 HBasicBlock* other_block = other_instruction->GetBlock();
1139 if (block != other_block) {
1140 return GetBlock()->Dominates(other_instruction->GetBlock());
1141 } else {
1142 // If both instructions are in the same block, ensure this
1143 // instruction comes before `other_instruction`.
1144 if (IsPhi()) {
1145 if (!other_instruction->IsPhi()) {
1146 // Phis appear before non phi-instructions so this instruction
1147 // dominates `other_instruction`.
1148 return true;
1149 } else {
1150 // There is no order among phis.
1151 LOG(FATAL) << "There is no dominance between phis of a same block.";
1152 return false;
1153 }
1154 } else {
1155 // `this` is not a phi.
1156 if (other_instruction->IsPhi()) {
1157 // Phis appear before non phi-instructions so this instruction
1158 // does not dominate `other_instruction`.
1159 return false;
1160 } else {
1161 // Check whether this instruction comes before
1162 // `other_instruction` in the instruction list.
1163 return block->GetInstructions().FoundBefore(this, other_instruction);
1164 }
1165 }
1166 }
1167}
1168
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001169void HInstruction::RemoveEnvironment() {
1170 RemoveEnvironmentUses(this);
1171 environment_ = nullptr;
1172}
1173
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001174void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001175 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001176 // Note: fixup_end remains valid across splice_after().
1177 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1178 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1179 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001180
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001181 // Note: env_fixup_end remains valid across splice_after().
1182 auto env_fixup_end =
1183 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1184 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1185 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001186
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001187 DCHECK(uses_.empty());
1188 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001189}
1190
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001191void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001192 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001193 if (input_use.GetInstruction() == replacement) {
1194 // Nothing to do.
1195 return;
1196 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001197 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001198 // Note: fixup_end remains valid across splice_after().
1199 auto fixup_end =
1200 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1201 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1202 input_use.GetInstruction()->uses_,
1203 before_use_node);
1204 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1205 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001206}
1207
Nicolas Geoffray39468442014-09-02 15:17:15 +01001208size_t HInstruction::EnvironmentSize() const {
1209 return HasEnvironment() ? environment_->Size() : 0;
1210}
1211
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001212void HPhi::AddInput(HInstruction* input) {
1213 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001214 inputs_.push_back(HUserRecord<HInstruction*>(input));
1215 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001216}
1217
David Brazdil2d7352b2015-04-20 14:52:42 +01001218void HPhi::RemoveInputAt(size_t index) {
1219 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001220 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001221 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1222 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1223 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1224 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001225 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001226}
1227
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001228#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001229void H##name::Accept(HGraphVisitor* visitor) { \
1230 visitor->Visit##name(this); \
1231}
1232
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001233FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001234
1235#undef DEFINE_ACCEPT
1236
1237void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001238 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1239 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001240 if (block != nullptr) {
1241 VisitBasicBlock(block);
1242 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001243 }
1244}
1245
Roland Levillain633021e2014-10-01 14:12:25 +01001246void HGraphVisitor::VisitReversePostOrder() {
1247 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1248 VisitBasicBlock(it.Current());
1249 }
1250}
1251
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001252void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001253 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001254 it.Current()->Accept(this);
1255 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001256 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001257 it.Current()->Accept(this);
1258 }
1259}
1260
Mark Mendelle82549b2015-05-06 10:55:34 -04001261HConstant* HTypeConversion::TryStaticEvaluation() const {
1262 HGraph* graph = GetBlock()->GetGraph();
1263 if (GetInput()->IsIntConstant()) {
1264 int32_t value = GetInput()->AsIntConstant()->GetValue();
1265 switch (GetResultType()) {
1266 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001267 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001268 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001269 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001270 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001271 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001272 default:
1273 return nullptr;
1274 }
1275 } else if (GetInput()->IsLongConstant()) {
1276 int64_t value = GetInput()->AsLongConstant()->GetValue();
1277 switch (GetResultType()) {
1278 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001279 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001280 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001281 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001282 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001283 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001284 default:
1285 return nullptr;
1286 }
1287 } else if (GetInput()->IsFloatConstant()) {
1288 float value = GetInput()->AsFloatConstant()->GetValue();
1289 switch (GetResultType()) {
1290 case Primitive::kPrimInt:
1291 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001292 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001293 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001294 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001295 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001296 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1297 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001298 case Primitive::kPrimLong:
1299 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001300 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001301 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001302 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001303 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001304 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1305 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001306 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001307 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001308 default:
1309 return nullptr;
1310 }
1311 } else if (GetInput()->IsDoubleConstant()) {
1312 double value = GetInput()->AsDoubleConstant()->GetValue();
1313 switch (GetResultType()) {
1314 case Primitive::kPrimInt:
1315 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001316 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001317 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001318 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001319 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001320 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1321 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001322 case Primitive::kPrimLong:
1323 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001324 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001325 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001326 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001327 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001328 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1329 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001330 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001331 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001332 default:
1333 return nullptr;
1334 }
1335 }
1336 return nullptr;
1337}
1338
Roland Levillain9240d6a2014-10-20 16:47:04 +01001339HConstant* HUnaryOperation::TryStaticEvaluation() const {
1340 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001341 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001342 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001343 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001344 } else if (kEnableFloatingPointStaticEvaluation) {
1345 if (GetInput()->IsFloatConstant()) {
1346 return Evaluate(GetInput()->AsFloatConstant());
1347 } else if (GetInput()->IsDoubleConstant()) {
1348 return Evaluate(GetInput()->AsDoubleConstant());
1349 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001350 }
1351 return nullptr;
1352}
1353
1354HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001355 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1356 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001357 } else if (GetLeft()->IsLongConstant()) {
1358 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001359 // The binop(long, int) case is only valid for shifts and rotations.
1360 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001361 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1362 } else if (GetRight()->IsLongConstant()) {
1363 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001364 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001365 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001366 // The binop(null, null) case is only valid for equal and not-equal conditions.
1367 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001368 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001369 } else if (kEnableFloatingPointStaticEvaluation) {
1370 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1371 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1372 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1373 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1374 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001375 }
1376 return nullptr;
1377}
Dave Allison20dfc792014-06-16 20:44:29 -07001378
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001379HConstant* HBinaryOperation::GetConstantRight() const {
1380 if (GetRight()->IsConstant()) {
1381 return GetRight()->AsConstant();
1382 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1383 return GetLeft()->AsConstant();
1384 } else {
1385 return nullptr;
1386 }
1387}
1388
1389// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001390// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001391HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1392 HInstruction* most_constant_right = GetConstantRight();
1393 if (most_constant_right == nullptr) {
1394 return nullptr;
1395 } else if (most_constant_right == GetLeft()) {
1396 return GetRight();
1397 } else {
1398 return GetLeft();
1399 }
1400}
1401
Roland Levillain31dd3d62016-02-16 12:21:02 +00001402std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1403 switch (rhs) {
1404 case ComparisonBias::kNoBias:
1405 return os << "no_bias";
1406 case ComparisonBias::kGtBias:
1407 return os << "gt_bias";
1408 case ComparisonBias::kLtBias:
1409 return os << "lt_bias";
1410 default:
1411 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1412 UNREACHABLE();
1413 }
1414}
1415
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001416bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1417 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001418}
1419
Vladimir Marko372f10e2016-05-17 16:30:10 +01001420bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001421 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001422 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001423 if (!InstructionDataEquals(other)) return false;
1424 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001425 HConstInputsRef inputs = GetInputs();
1426 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001427 if (inputs.size() != other_inputs.size()) return false;
1428 for (size_t i = 0; i != inputs.size(); ++i) {
1429 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001430 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001431
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001432 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001433 return true;
1434}
1435
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001436std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1437#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1438 switch (rhs) {
1439 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1440 default:
1441 os << "Unknown instruction kind " << static_cast<int>(rhs);
1442 break;
1443 }
1444#undef DECLARE_CASE
1445 return os;
1446}
1447
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001448void HInstruction::MoveBefore(HInstruction* cursor) {
David Brazdild6c205e2016-06-07 14:20:52 +01001449 DCHECK(!IsPhi());
1450 DCHECK(!IsControlFlow());
1451 DCHECK(CanBeMoved());
1452 DCHECK(!cursor->IsPhi());
1453
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001454 next_->previous_ = previous_;
1455 if (previous_ != nullptr) {
1456 previous_->next_ = next_;
1457 }
1458 if (block_->instructions_.first_instruction_ == this) {
1459 block_->instructions_.first_instruction_ = next_;
1460 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001461 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001462
1463 previous_ = cursor->previous_;
1464 if (previous_ != nullptr) {
1465 previous_->next_ = this;
1466 }
1467 next_ = cursor;
1468 cursor->previous_ = this;
1469 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001470
1471 if (block_->instructions_.first_instruction_ == cursor) {
1472 block_->instructions_.first_instruction_ = this;
1473 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001474}
1475
Vladimir Markofb337ea2015-11-25 15:25:10 +00001476void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1477 DCHECK(!CanThrow());
1478 DCHECK(!HasSideEffects());
1479 DCHECK(!HasEnvironmentUses());
1480 DCHECK(HasNonEnvironmentUses());
1481 DCHECK(!IsPhi()); // Makes no sense for Phi.
1482 DCHECK_EQ(InputCount(), 0u);
1483
1484 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001485 auto uses_it = GetUses().begin();
1486 auto uses_end = GetUses().end();
1487 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1488 ++uses_it;
1489 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1490 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001491 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001492 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001493 // This instruction has uses in two or more blocks. Find the common dominator.
1494 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001495 for (; uses_it != uses_end; ++uses_it) {
1496 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001497 }
1498 target_block = finder.Get();
1499 DCHECK(target_block != nullptr);
1500 }
1501 // Move to the first dominator not in a loop.
1502 while (target_block->IsInLoop()) {
1503 target_block = target_block->GetDominator();
1504 DCHECK(target_block != nullptr);
1505 }
1506
1507 // Find insertion position.
1508 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001509 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1510 if (use.GetUser()->GetBlock() == target_block &&
1511 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1512 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001513 }
1514 }
1515 if (insert_pos == nullptr) {
1516 // No user in `target_block`, insert before the control flow instruction.
1517 insert_pos = target_block->GetLastInstruction();
1518 DCHECK(insert_pos->IsControlFlow());
1519 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1520 if (insert_pos->IsIf()) {
1521 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1522 if (if_input == insert_pos->GetPrevious()) {
1523 insert_pos = if_input;
1524 }
1525 }
1526 }
1527 MoveBefore(insert_pos);
1528}
1529
David Brazdilfc6a86a2015-06-26 10:33:45 +00001530HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001531 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001532 DCHECK_EQ(cursor->GetBlock(), this);
1533
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001534 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1535 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001536 new_block->instructions_.first_instruction_ = cursor;
1537 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1538 instructions_.last_instruction_ = cursor->previous_;
1539 if (cursor->previous_ == nullptr) {
1540 instructions_.first_instruction_ = nullptr;
1541 } else {
1542 cursor->previous_->next_ = nullptr;
1543 cursor->previous_ = nullptr;
1544 }
1545
1546 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001547 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001548
Vladimir Marko60584552015-09-03 13:35:12 +00001549 for (HBasicBlock* successor : GetSuccessors()) {
1550 new_block->successors_.push_back(successor);
1551 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001552 }
Vladimir Marko60584552015-09-03 13:35:12 +00001553 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001554 AddSuccessor(new_block);
1555
David Brazdil56e1acc2015-06-30 15:41:36 +01001556 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001557 return new_block;
1558}
1559
David Brazdild7558da2015-09-22 13:04:14 +01001560HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001561 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001562 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1563
1564 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1565
1566 for (HBasicBlock* predecessor : GetPredecessors()) {
1567 new_block->predecessors_.push_back(predecessor);
1568 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1569 }
1570 predecessors_.clear();
1571 AddPredecessor(new_block);
1572
1573 GetGraph()->AddBlock(new_block);
1574 return new_block;
1575}
1576
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001577HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1578 DCHECK_EQ(cursor->GetBlock(), this);
1579
1580 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1581 cursor->GetDexPc());
1582 new_block->instructions_.first_instruction_ = cursor;
1583 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1584 instructions_.last_instruction_ = cursor->previous_;
1585 if (cursor->previous_ == nullptr) {
1586 instructions_.first_instruction_ = nullptr;
1587 } else {
1588 cursor->previous_->next_ = nullptr;
1589 cursor->previous_ = nullptr;
1590 }
1591
1592 new_block->instructions_.SetBlockOfInstructions(new_block);
1593
1594 for (HBasicBlock* successor : GetSuccessors()) {
1595 new_block->successors_.push_back(successor);
1596 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1597 }
1598 successors_.clear();
1599
1600 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1601 dominated->dominator_ = new_block;
1602 new_block->dominated_blocks_.push_back(dominated);
1603 }
1604 dominated_blocks_.clear();
1605 return new_block;
1606}
1607
1608HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001609 DCHECK(!cursor->IsControlFlow());
1610 DCHECK_NE(instructions_.last_instruction_, cursor);
1611 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001612
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001613 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1614 new_block->instructions_.first_instruction_ = cursor->GetNext();
1615 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1616 cursor->next_->previous_ = nullptr;
1617 cursor->next_ = nullptr;
1618 instructions_.last_instruction_ = cursor;
1619
1620 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001621 for (HBasicBlock* successor : GetSuccessors()) {
1622 new_block->successors_.push_back(successor);
1623 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001624 }
Vladimir Marko60584552015-09-03 13:35:12 +00001625 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001626
Vladimir Marko60584552015-09-03 13:35:12 +00001627 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001628 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001629 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001630 }
Vladimir Marko60584552015-09-03 13:35:12 +00001631 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001632 return new_block;
1633}
1634
David Brazdilec16f792015-08-19 15:04:01 +01001635const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001636 if (EndsWithTryBoundary()) {
1637 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1638 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001639 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001640 return try_boundary;
1641 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001642 DCHECK(IsTryBlock());
1643 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001644 return nullptr;
1645 }
David Brazdilec16f792015-08-19 15:04:01 +01001646 } else if (IsTryBlock()) {
1647 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001648 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001649 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001650 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001651}
1652
David Brazdild7558da2015-09-22 13:04:14 +01001653bool HBasicBlock::HasThrowingInstructions() const {
1654 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1655 if (it.Current()->CanThrow()) {
1656 return true;
1657 }
1658 }
1659 return false;
1660}
1661
David Brazdilfc6a86a2015-06-26 10:33:45 +00001662static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1663 return block.GetPhis().IsEmpty()
1664 && !block.GetInstructions().IsEmpty()
1665 && block.GetFirstInstruction() == block.GetLastInstruction();
1666}
1667
David Brazdil46e2a392015-03-16 17:31:52 +00001668bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001669 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1670}
1671
1672bool HBasicBlock::IsSingleTryBoundary() const {
1673 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001674}
1675
David Brazdil8d5b8b22015-03-24 10:51:52 +00001676bool HBasicBlock::EndsWithControlFlowInstruction() const {
1677 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1678}
1679
David Brazdilb2bd1c52015-03-25 11:17:37 +00001680bool HBasicBlock::EndsWithIf() const {
1681 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1682}
1683
David Brazdilffee3d32015-07-06 11:48:53 +01001684bool HBasicBlock::EndsWithTryBoundary() const {
1685 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1686}
1687
David Brazdilb2bd1c52015-03-25 11:17:37 +00001688bool HBasicBlock::HasSinglePhi() const {
1689 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1690}
1691
David Brazdild26a4112015-11-10 11:07:31 +00001692ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1693 if (EndsWithTryBoundary()) {
1694 // The normal-flow successor of HTryBoundary is always stored at index zero.
1695 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1696 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1697 } else {
1698 // All successors of blocks not ending with TryBoundary are normal.
1699 return ArrayRef<HBasicBlock* const>(successors_);
1700 }
1701}
1702
1703ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1704 if (EndsWithTryBoundary()) {
1705 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1706 } else {
1707 // Blocks not ending with TryBoundary do not have exceptional successors.
1708 return ArrayRef<HBasicBlock* const>();
1709 }
1710}
1711
David Brazdilffee3d32015-07-06 11:48:53 +01001712bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001713 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1714 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1715
1716 size_t length = handlers1.size();
1717 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001718 return false;
1719 }
1720
David Brazdilb618ade2015-07-29 10:31:29 +01001721 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001722 for (size_t i = 0; i < length; ++i) {
1723 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001724 return false;
1725 }
1726 }
1727 return true;
1728}
1729
David Brazdil2d7352b2015-04-20 14:52:42 +01001730size_t HInstructionList::CountSize() const {
1731 size_t size = 0;
1732 HInstruction* current = first_instruction_;
1733 for (; current != nullptr; current = current->GetNext()) {
1734 size++;
1735 }
1736 return size;
1737}
1738
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001739void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1740 for (HInstruction* current = first_instruction_;
1741 current != nullptr;
1742 current = current->GetNext()) {
1743 current->SetBlock(block);
1744 }
1745}
1746
1747void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1748 DCHECK(Contains(cursor));
1749 if (!instruction_list.IsEmpty()) {
1750 if (cursor == last_instruction_) {
1751 last_instruction_ = instruction_list.last_instruction_;
1752 } else {
1753 cursor->next_->previous_ = instruction_list.last_instruction_;
1754 }
1755 instruction_list.last_instruction_->next_ = cursor->next_;
1756 cursor->next_ = instruction_list.first_instruction_;
1757 instruction_list.first_instruction_->previous_ = cursor;
1758 }
1759}
1760
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001761void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1762 DCHECK(Contains(cursor));
1763 if (!instruction_list.IsEmpty()) {
1764 if (cursor == first_instruction_) {
1765 first_instruction_ = instruction_list.first_instruction_;
1766 } else {
1767 cursor->previous_->next_ = instruction_list.first_instruction_;
1768 }
1769 instruction_list.last_instruction_->next_ = cursor;
1770 instruction_list.first_instruction_->previous_ = cursor->previous_;
1771 cursor->previous_ = instruction_list.last_instruction_;
1772 }
1773}
1774
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001775void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001776 if (IsEmpty()) {
1777 first_instruction_ = instruction_list.first_instruction_;
1778 last_instruction_ = instruction_list.last_instruction_;
1779 } else {
1780 AddAfter(last_instruction_, instruction_list);
1781 }
1782}
1783
David Brazdil04ff4e82015-12-10 13:54:52 +00001784// Should be called on instructions in a dead block in post order. This method
1785// assumes `insn` has been removed from all users with the exception of catch
1786// phis because of missing exceptional edges in the graph. It removes the
1787// instruction from catch phi uses, together with inputs of other catch phis in
1788// the catch block at the same index, as these must be dead too.
1789static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1790 DCHECK(!insn->HasEnvironmentUses());
1791 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001792 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1793 size_t use_index = use.GetIndex();
1794 HBasicBlock* user_block = use.GetUser()->GetBlock();
1795 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001796 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1797 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1798 }
1799 }
1800}
1801
David Brazdil2d7352b2015-04-20 14:52:42 +01001802void HBasicBlock::DisconnectAndDelete() {
1803 // Dominators must be removed after all the blocks they dominate. This way
1804 // a loop header is removed last, a requirement for correct loop information
1805 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001806 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001807
David Brazdil9eeebf62016-03-24 11:18:15 +00001808 // The following steps gradually remove the block from all its dependants in
1809 // post order (b/27683071).
1810
1811 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1812 // We need to do this before step (4) which destroys the predecessor list.
1813 HBasicBlock* loop_update_start = this;
1814 if (IsLoopHeader()) {
1815 HLoopInformation* loop_info = GetLoopInformation();
1816 // All other blocks in this loop should have been removed because the header
1817 // was their dominator.
1818 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1819 DCHECK(!loop_info->IsIrreducible());
1820 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1821 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1822 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001823 }
1824
David Brazdil9eeebf62016-03-24 11:18:15 +00001825 // (2) Disconnect the block from its successors and update their phis.
1826 for (HBasicBlock* successor : successors_) {
1827 // Delete this block from the list of predecessors.
1828 size_t this_index = successor->GetPredecessorIndexOf(this);
1829 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1830
1831 // Check that `successor` has other predecessors, otherwise `this` is the
1832 // dominator of `successor` which violates the order DCHECKed at the top.
1833 DCHECK(!successor->predecessors_.empty());
1834
1835 // Remove this block's entries in the successor's phis. Skip exceptional
1836 // successors because catch phi inputs do not correspond to predecessor
1837 // blocks but throwing instructions. The inputs of the catch phis will be
1838 // updated in step (3).
1839 if (!successor->IsCatchBlock()) {
1840 if (successor->predecessors_.size() == 1u) {
1841 // The successor has just one predecessor left. Replace phis with the only
1842 // remaining input.
1843 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1844 HPhi* phi = phi_it.Current()->AsPhi();
1845 phi->ReplaceWith(phi->InputAt(1 - this_index));
1846 successor->RemovePhi(phi);
1847 }
1848 } else {
1849 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1850 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1851 }
1852 }
1853 }
1854 }
1855 successors_.clear();
1856
1857 // (3) Remove instructions and phis. Instructions should have no remaining uses
1858 // except in catch phis. If an instruction is used by a catch phi at `index`,
1859 // remove `index`-th input of all phis in the catch block since they are
1860 // guaranteed dead. Note that we may miss dead inputs this way but the
1861 // graph will always remain consistent.
1862 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1863 HInstruction* insn = it.Current();
1864 RemoveUsesOfDeadInstruction(insn);
1865 RemoveInstruction(insn);
1866 }
1867 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1868 HPhi* insn = it.Current()->AsPhi();
1869 RemoveUsesOfDeadInstruction(insn);
1870 RemovePhi(insn);
1871 }
1872
1873 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001874 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001875 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001876 // We should not see any back edges as they would have been removed by step (3).
1877 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1878
David Brazdil2d7352b2015-04-20 14:52:42 +01001879 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001880 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1881 // This block is the only normal-flow successor of the TryBoundary which
1882 // makes `predecessor` dead. Since DCE removes blocks in post order,
1883 // exception handlers of this TryBoundary were already visited and any
1884 // remaining handlers therefore must be live. We remove `predecessor` from
1885 // their list of predecessors.
1886 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1887 while (predecessor->GetSuccessors().size() > 1) {
1888 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1889 DCHECK(handler->IsCatchBlock());
1890 predecessor->RemoveSuccessor(handler);
1891 handler->RemovePredecessor(predecessor);
1892 }
1893 }
1894
David Brazdil2d7352b2015-04-20 14:52:42 +01001895 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001896 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1897 if (num_pred_successors == 1u) {
1898 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001899 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1900 // successor. Replace those with a HGoto.
1901 DCHECK(last_instruction->IsIf() ||
1902 last_instruction->IsPackedSwitch() ||
1903 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001904 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001905 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001906 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001907 // The predecessor has no remaining successors and therefore must be dead.
1908 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001909 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001910 predecessor->RemoveInstruction(last_instruction);
1911 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001912 // There are multiple successors left. The removed block might be a successor
1913 // of a PackedSwitch which will be completely removed (perhaps replaced with
1914 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1915 // case, leave `last_instruction` as is for now.
1916 DCHECK(last_instruction->IsPackedSwitch() ||
1917 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001918 }
David Brazdil46e2a392015-03-16 17:31:52 +00001919 }
Vladimir Marko60584552015-09-03 13:35:12 +00001920 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001921
David Brazdil9eeebf62016-03-24 11:18:15 +00001922 // (5) Remove the block from all loops it is included in. Skip the inner-most
1923 // loop if this is the loop header (see definition of `loop_update_start`)
1924 // because the loop header's predecessor list has been destroyed in step (4).
1925 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1926 HLoopInformation* loop_info = it.Current();
1927 loop_info->Remove(this);
1928 if (loop_info->IsBackEdge(*this)) {
1929 // If this was the last back edge of the loop, we deliberately leave the
1930 // loop in an inconsistent state and will fail GraphChecker unless the
1931 // entire loop is removed during the pass.
1932 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001933 }
1934 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001935
David Brazdil9eeebf62016-03-24 11:18:15 +00001936 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001937 dominator_->RemoveDominatedBlock(this);
1938 SetDominator(nullptr);
1939
David Brazdil9eeebf62016-03-24 11:18:15 +00001940 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001941 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001942 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001943}
1944
1945void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001946 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001947 DCHECK(ContainsElement(dominated_blocks_, other));
1948 DCHECK_EQ(GetSingleSuccessor(), other);
1949 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001950 DCHECK(other->GetPhis().IsEmpty());
1951
David Brazdil2d7352b2015-04-20 14:52:42 +01001952 // Move instructions from `other` to `this`.
1953 DCHECK(EndsWithControlFlowInstruction());
1954 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001955 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001956 other->instructions_.SetBlockOfInstructions(this);
1957 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001958
David Brazdil2d7352b2015-04-20 14:52:42 +01001959 // Remove `other` from the loops it is included in.
1960 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1961 HLoopInformation* loop_info = it.Current();
1962 loop_info->Remove(other);
1963 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001964 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001965 }
1966 }
1967
1968 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001969 successors_.clear();
1970 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001971 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001972 successor->ReplacePredecessor(other, this);
1973 }
1974
David Brazdil2d7352b2015-04-20 14:52:42 +01001975 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001976 RemoveDominatedBlock(other);
1977 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1978 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001979 dominated->SetDominator(this);
1980 }
Vladimir Marko60584552015-09-03 13:35:12 +00001981 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001982 other->dominator_ = nullptr;
1983
1984 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001985 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001986
1987 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001988 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001989 other->SetGraph(nullptr);
1990}
1991
1992void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1993 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001994 DCHECK(GetDominatedBlocks().empty());
1995 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001996 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001997 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001998 DCHECK(other->GetPhis().IsEmpty());
1999 DCHECK(!other->IsInLoop());
2000
2001 // Move instructions from `other` to `this`.
2002 instructions_.Add(other->GetInstructions());
2003 other->instructions_.SetBlockOfInstructions(this);
2004
2005 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002006 successors_.clear();
2007 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002008 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01002009 successor->ReplacePredecessor(other, this);
2010 }
2011
2012 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002013 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
2014 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002015 dominated->SetDominator(this);
2016 }
Vladimir Marko60584552015-09-03 13:35:12 +00002017 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002018 other->dominator_ = nullptr;
2019 other->graph_ = nullptr;
2020}
2021
2022void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002023 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002024 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002025 predecessor->ReplaceSuccessor(this, other);
2026 }
Vladimir Marko60584552015-09-03 13:35:12 +00002027 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002028 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002029 successor->ReplacePredecessor(this, other);
2030 }
Vladimir Marko60584552015-09-03 13:35:12 +00002031 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2032 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002033 }
2034 GetDominator()->ReplaceDominatedBlock(this, other);
2035 other->SetDominator(GetDominator());
2036 dominator_ = nullptr;
2037 graph_ = nullptr;
2038}
2039
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002040void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002041 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002042 DCHECK(block->GetSuccessors().empty());
2043 DCHECK(block->GetPredecessors().empty());
2044 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002045 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002046 DCHECK(block->GetInstructions().IsEmpty());
2047 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002048
David Brazdilc7af85d2015-05-26 12:05:55 +01002049 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002050 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002051 }
2052
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002053 RemoveElement(reverse_post_order_, block);
2054 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002055 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002056}
2057
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002058void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2059 HBasicBlock* reference,
2060 bool replace_if_back_edge) {
2061 if (block->IsLoopHeader()) {
2062 // Clear the information of which blocks are contained in that loop. Since the
2063 // information is stored as a bit vector based on block ids, we have to update
2064 // it, as those block ids were specific to the callee graph and we are now adding
2065 // these blocks to the caller graph.
2066 block->GetLoopInformation()->ClearAllBlocks();
2067 }
2068
2069 // If not already in a loop, update the loop information.
2070 if (!block->IsInLoop()) {
2071 block->SetLoopInformation(reference->GetLoopInformation());
2072 }
2073
2074 // If the block is in a loop, update all its outward loops.
2075 HLoopInformation* loop_info = block->GetLoopInformation();
2076 if (loop_info != nullptr) {
2077 for (HLoopInformationOutwardIterator loop_it(*block);
2078 !loop_it.Done();
2079 loop_it.Advance()) {
2080 loop_it.Current()->Add(block);
2081 }
2082 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2083 loop_info->ReplaceBackEdge(reference, block);
2084 }
2085 }
2086
2087 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2088 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2089 ? reference->GetTryCatchInformation()
2090 : nullptr;
2091 block->SetTryCatchInformation(try_catch_info);
2092}
2093
Calin Juravle2e768302015-07-28 14:41:11 +00002094HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002095 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002096 // Update the environments in this graph to have the invoke's environment
2097 // as parent.
2098 {
2099 HReversePostOrderIterator it(*this);
2100 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
2101 for (; !it.Done(); it.Advance()) {
2102 HBasicBlock* block = it.Current();
2103 for (HInstructionIterator instr_it(block->GetInstructions());
2104 !instr_it.Done();
2105 instr_it.Advance()) {
2106 HInstruction* current = instr_it.Current();
2107 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002108 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002109 current->GetEnvironment()->SetAndCopyParentChain(
2110 outer_graph->GetArena(), invoke->GetEnvironment());
2111 }
2112 }
2113 }
2114 }
2115 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
2116 if (HasBoundsChecks()) {
2117 outer_graph->SetHasBoundsChecks(true);
2118 }
2119
Calin Juravle2e768302015-07-28 14:41:11 +00002120 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002121 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002122 // Simple case of an entry block, a body block, and an exit block.
2123 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002124 HBasicBlock* body = GetBlocks()[1];
2125 DCHECK(GetBlocks()[0]->IsEntryBlock());
2126 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002127 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002128 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002129 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002130
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002131 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2132 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002133 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002134
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002135 // Replace the invoke with the return value of the inlined graph.
2136 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002137 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002138 } else {
2139 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002140 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002141
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002142 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002143 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002144 // Need to inline multiple blocks. We split `invoke`'s block
2145 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002146 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002147 // with the second half.
2148 ArenaAllocator* allocator = outer_graph->GetArena();
2149 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002150 // Note that we split before the invoke only to simplify polymorphic inlining.
2151 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002152
Vladimir Markoec7802a2015-10-01 20:57:57 +01002153 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002154 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002155 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002156 exit_block_->ReplaceWith(to);
2157
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002158 // Update the meta information surrounding blocks:
2159 // (1) the graph they are now in,
2160 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002161 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002162 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002163 // Note that we do not need to update catch phi inputs because they
2164 // correspond to the register file of the outer method which the inlinee
2165 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002166
2167 // We don't add the entry block, the exit block, and the first block, which
2168 // has been merged with `at`.
2169 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2170
2171 // We add the `to` block.
2172 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002173 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002174 + kNumberOfNewBlocksInCaller;
2175
2176 // Find the location of `at` in the outer graph's reverse post order. The new
2177 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002178 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002179 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2180
David Brazdil95177982015-10-30 12:56:58 -05002181 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2182 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002183 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2184 HBasicBlock* current = it.Current();
2185 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002186 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002187 DCHECK(current->GetGraph() == this);
2188 current->SetGraph(outer_graph);
2189 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002190 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002191 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002192 }
2193 }
2194
David Brazdil95177982015-10-30 12:56:58 -05002195 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002196 to->SetGraph(outer_graph);
2197 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002198 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002199 // Only `to` can become a back edge, as the inlined blocks
2200 // are predecessors of `to`.
2201 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002202
David Brazdil3f523062016-02-29 16:53:33 +00002203 // Update all predecessors of the exit block (now the `to` block)
2204 // to not `HReturn` but `HGoto` instead.
2205 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2206 if (to->GetPredecessors().size() == 1) {
2207 HBasicBlock* predecessor = to->GetPredecessors()[0];
2208 HInstruction* last = predecessor->GetLastInstruction();
2209 if (!returns_void) {
2210 return_value = last->InputAt(0);
2211 }
2212 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2213 predecessor->RemoveInstruction(last);
2214 } else {
2215 if (!returns_void) {
2216 // There will be multiple returns.
2217 return_value = new (allocator) HPhi(
2218 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2219 to->AddPhi(return_value->AsPhi());
2220 }
2221 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2222 HInstruction* last = predecessor->GetLastInstruction();
2223 if (!returns_void) {
2224 DCHECK(last->IsReturn());
2225 return_value->AsPhi()->AddInput(last->InputAt(0));
2226 }
2227 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2228 predecessor->RemoveInstruction(last);
2229 }
2230 }
2231 }
David Brazdil05144f42015-04-16 15:18:00 +01002232
2233 // Walk over the entry block and:
2234 // - Move constants from the entry block to the outer_graph's entry block,
2235 // - Replace HParameterValue instructions with their real value.
2236 // - Remove suspend checks, that hold an environment.
2237 // We must do this after the other blocks have been inlined, otherwise ids of
2238 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002239 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002240 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2241 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002242 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002243 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002244 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002245 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002246 replacement = outer_graph->GetIntConstant(
2247 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002248 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002249 replacement = outer_graph->GetLongConstant(
2250 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002251 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002252 replacement = outer_graph->GetFloatConstant(
2253 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002254 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002255 replacement = outer_graph->GetDoubleConstant(
2256 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002257 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002258 if (kIsDebugBuild
2259 && invoke->IsInvokeStaticOrDirect()
2260 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2261 // Ensure we do not use the last input of `invoke`, as it
2262 // contains a clinit check which is not an actual argument.
2263 size_t last_input_index = invoke->InputCount() - 1;
2264 DCHECK(parameter_index != last_input_index);
2265 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002266 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002267 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002268 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002269 } else {
2270 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2271 entry_block_->RemoveInstruction(current);
2272 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002273 if (replacement != nullptr) {
2274 current->ReplaceWith(replacement);
2275 // If the current is the return value then we need to update the latter.
2276 if (current == return_value) {
2277 DCHECK_EQ(entry_block_, return_value->GetBlock());
2278 return_value = replacement;
2279 }
2280 }
2281 }
2282
Calin Juravle2e768302015-07-28 14:41:11 +00002283 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002284}
2285
Mingyao Yang3584bce2015-05-19 16:01:59 -07002286/*
2287 * Loop will be transformed to:
2288 * old_pre_header
2289 * |
2290 * if_block
2291 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002292 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002293 * \ /
2294 * new_pre_header
2295 * |
2296 * header
2297 */
2298void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2299 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002300 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002301
Aart Bik3fc7f352015-11-20 22:03:03 -08002302 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002303 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002304 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2305 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002306 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2307 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002308 AddBlock(true_block);
2309 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002310 AddBlock(new_pre_header);
2311
Aart Bik3fc7f352015-11-20 22:03:03 -08002312 header->ReplacePredecessor(old_pre_header, new_pre_header);
2313 old_pre_header->successors_.clear();
2314 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002315
Aart Bik3fc7f352015-11-20 22:03:03 -08002316 old_pre_header->AddSuccessor(if_block);
2317 if_block->AddSuccessor(true_block); // True successor
2318 if_block->AddSuccessor(false_block); // False successor
2319 true_block->AddSuccessor(new_pre_header);
2320 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002321
Aart Bik3fc7f352015-11-20 22:03:03 -08002322 old_pre_header->dominated_blocks_.push_back(if_block);
2323 if_block->SetDominator(old_pre_header);
2324 if_block->dominated_blocks_.push_back(true_block);
2325 true_block->SetDominator(if_block);
2326 if_block->dominated_blocks_.push_back(false_block);
2327 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002328 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002329 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002330 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002331 header->SetDominator(new_pre_header);
2332
Aart Bik3fc7f352015-11-20 22:03:03 -08002333 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002334 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002335 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002336 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002337 reverse_post_order_[index_of_header++] = true_block;
2338 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002339 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002340
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002341 // The pre_header can never be a back edge of a loop.
2342 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2343 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2344 UpdateLoopAndTryInformationOfNewBlock(
2345 if_block, old_pre_header, /* replace_if_back_edge */ false);
2346 UpdateLoopAndTryInformationOfNewBlock(
2347 true_block, old_pre_header, /* replace_if_back_edge */ false);
2348 UpdateLoopAndTryInformationOfNewBlock(
2349 false_block, old_pre_header, /* replace_if_back_edge */ false);
2350 UpdateLoopAndTryInformationOfNewBlock(
2351 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002352}
2353
David Brazdilf5552582015-12-27 13:36:12 +00002354static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002355 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002356 if (rti.IsValid()) {
2357 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2358 << " upper_bound_rti: " << upper_bound_rti
2359 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002360 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2361 << " upper_bound_rti: " << upper_bound_rti
2362 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002363 }
2364}
2365
Calin Juravle2e768302015-07-28 14:41:11 +00002366void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2367 if (kIsDebugBuild) {
2368 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2369 ScopedObjectAccess soa(Thread::Current());
2370 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2371 if (IsBoundType()) {
2372 // Having the test here spares us from making the method virtual just for
2373 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002374 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002375 }
2376 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002377 reference_type_handle_ = rti.GetTypeHandle();
2378 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002379}
2380
David Brazdilf5552582015-12-27 13:36:12 +00002381void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2382 if (kIsDebugBuild) {
2383 ScopedObjectAccess soa(Thread::Current());
2384 DCHECK(upper_bound.IsValid());
2385 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2386 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2387 }
2388 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002389 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002390}
2391
Vladimir Markoa1de9182016-02-25 11:37:38 +00002392ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002393 if (kIsDebugBuild) {
2394 ScopedObjectAccess soa(Thread::Current());
2395 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002396 if (!is_exact) {
2397 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2398 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2399 }
Calin Juravle2e768302015-07-28 14:41:11 +00002400 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002401 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002402}
2403
Calin Juravleacf735c2015-02-12 15:25:22 +00002404std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2405 ScopedObjectAccess soa(Thread::Current());
2406 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002407 << " is_valid=" << rhs.IsValid()
2408 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002409 << " is_exact=" << rhs.IsExact()
2410 << " ]";
2411 return os;
2412}
2413
Mark Mendellc4701932015-04-10 13:18:51 -04002414bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2415 // For now, assume that instructions in different blocks may use the
2416 // environment.
2417 // TODO: Use the control flow to decide if this is true.
2418 if (GetBlock() != other->GetBlock()) {
2419 return true;
2420 }
2421
2422 // We know that we are in the same block. Walk from 'this' to 'other',
2423 // checking to see if there is any instruction with an environment.
2424 HInstruction* current = this;
2425 for (; current != other && current != nullptr; current = current->GetNext()) {
2426 // This is a conservative check, as the instruction result may not be in
2427 // the referenced environment.
2428 if (current->HasEnvironment()) {
2429 return true;
2430 }
2431 }
2432
2433 // We should have been called with 'this' before 'other' in the block.
2434 // Just confirm this.
2435 DCHECK(current != nullptr);
2436 return false;
2437}
2438
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002439void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002440 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2441 IntrinsicSideEffects side_effects,
2442 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002443 intrinsic_ = intrinsic;
2444 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002445
Aart Bik5d75afe2015-12-14 11:57:01 -08002446 // Adjust method's side effects from intrinsic table.
2447 switch (side_effects) {
2448 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2449 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2450 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2451 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2452 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002453
2454 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2455 opt.SetDoesNotNeedDexCache();
2456 opt.SetDoesNotNeedEnvironment();
2457 } else {
2458 // If we need an environment, that means there will be a call, which can trigger GC.
2459 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2460 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002461 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002462 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002463}
2464
David Brazdil6de19382016-01-08 17:37:10 +00002465bool HNewInstance::IsStringAlloc() const {
2466 ScopedObjectAccess soa(Thread::Current());
2467 return GetReferenceTypeInfo().IsStringClass();
2468}
2469
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002470bool HInvoke::NeedsEnvironment() const {
2471 if (!IsIntrinsic()) {
2472 return true;
2473 }
2474 IntrinsicOptimizations opt(*this);
2475 return !opt.GetDoesNotNeedEnvironment();
2476}
2477
Vladimir Markodc151b22015-10-15 18:02:30 +01002478bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2479 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002480 return false;
2481 }
2482 if (!IsIntrinsic()) {
2483 return true;
2484 }
2485 IntrinsicOptimizations opt(*this);
2486 return !opt.GetDoesNotNeedDexCache();
2487}
2488
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002489void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2490 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2491 input->AddUseAt(this, index);
2492 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002493 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
2494 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
2495 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002496 }
2497}
2498
Vladimir Markob554b5a2015-11-06 12:57:55 +00002499void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2500 RemoveAsUserOfInput(index);
2501 inputs_.erase(inputs_.begin() + index);
2502 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002503 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
2504 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
2505 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Markob554b5a2015-11-06 12:57:55 +00002506 }
2507}
2508
Vladimir Markof64242a2015-12-01 14:58:23 +00002509std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2510 switch (rhs) {
2511 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2512 return os << "string_init";
2513 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2514 return os << "recursive";
2515 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2516 return os << "direct";
2517 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2518 return os << "direct_fixup";
2519 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2520 return os << "dex_cache_pc_relative";
2521 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2522 return os << "dex_cache_via_method";
2523 default:
2524 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2525 UNREACHABLE();
2526 }
2527}
2528
Vladimir Markofbb184a2015-11-13 14:47:00 +00002529std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2530 switch (rhs) {
2531 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2532 return os << "explicit";
2533 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2534 return os << "implicit";
2535 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2536 return os << "none";
2537 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002538 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2539 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002540 }
2541}
2542
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002543bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2544 const HLoadClass* other_load_class = other->AsLoadClass();
2545 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2546 // names rather than type indexes. However, we shall also have to re-think the hash code.
2547 if (type_index_ != other_load_class->type_index_ ||
2548 GetPackedFields() != other_load_class->GetPackedFields()) {
2549 return false;
2550 }
2551 LoadKind load_kind = GetLoadKind();
2552 if (HasAddress(load_kind)) {
2553 return GetAddress() == other_load_class->GetAddress();
2554 } else if (HasTypeReference(load_kind)) {
2555 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
2556 } else {
2557 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2558 // If the type indexes and dex files are the same, dex cache element offsets
2559 // must also be the same, so we don't need to compare them.
2560 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
2561 }
2562}
2563
2564void HLoadClass::SetLoadKindInternal(LoadKind load_kind) {
2565 // Once sharpened, the load kind should not be changed again.
2566 // Also, kReferrersClass should never be overwritten.
2567 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2568 SetPackedField<LoadKindField>(load_kind);
2569
2570 if (load_kind != LoadKind::kDexCacheViaMethod) {
2571 RemoveAsUserOfInput(0u);
2572 SetRawInputAt(0u, nullptr);
2573 }
2574 if (!NeedsEnvironment()) {
2575 RemoveEnvironment();
2576 SetSideEffects(SideEffects::None());
2577 }
2578}
2579
2580std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2581 switch (rhs) {
2582 case HLoadClass::LoadKind::kReferrersClass:
2583 return os << "ReferrersClass";
2584 case HLoadClass::LoadKind::kBootImageLinkTimeAddress:
2585 return os << "BootImageLinkTimeAddress";
2586 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2587 return os << "BootImageLinkTimePcRelative";
2588 case HLoadClass::LoadKind::kBootImageAddress:
2589 return os << "BootImageAddress";
2590 case HLoadClass::LoadKind::kDexCacheAddress:
2591 return os << "DexCacheAddress";
2592 case HLoadClass::LoadKind::kDexCachePcRelative:
2593 return os << "DexCachePcRelative";
2594 case HLoadClass::LoadKind::kDexCacheViaMethod:
2595 return os << "DexCacheViaMethod";
2596 default:
2597 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2598 UNREACHABLE();
2599 }
2600}
2601
Vladimir Marko372f10e2016-05-17 16:30:10 +01002602bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2603 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002604 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2605 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002606 if (string_index_ != other_load_string->string_index_ ||
2607 GetPackedFields() != other_load_string->GetPackedFields()) {
2608 return false;
2609 }
2610 LoadKind load_kind = GetLoadKind();
2611 if (HasAddress(load_kind)) {
2612 return GetAddress() == other_load_string->GetAddress();
Vladimir Marko5f926052016-09-30 17:04:49 +00002613 } else if (HasStringReference(load_kind)) {
2614 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002615 } else {
Vladimir Marko5f926052016-09-30 17:04:49 +00002616 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2617 // If the string indexes and dex files are the same, dex cache element offsets
2618 // must also be the same, so we don't need to compare them.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002619 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2620 }
2621}
2622
2623void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2624 // Once sharpened, the load kind should not be changed again.
2625 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2626 SetPackedField<LoadKindField>(load_kind);
2627
2628 if (load_kind != LoadKind::kDexCacheViaMethod) {
2629 RemoveAsUserOfInput(0u);
2630 SetRawInputAt(0u, nullptr);
2631 }
2632 if (!NeedsEnvironment()) {
2633 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002634 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002635 }
2636}
2637
2638std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2639 switch (rhs) {
2640 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2641 return os << "BootImageLinkTimeAddress";
2642 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2643 return os << "BootImageLinkTimePcRelative";
2644 case HLoadString::LoadKind::kBootImageAddress:
2645 return os << "BootImageAddress";
2646 case HLoadString::LoadKind::kDexCacheAddress:
2647 return os << "DexCacheAddress";
Vladimir Marko5f926052016-09-30 17:04:49 +00002648 case HLoadString::LoadKind::kDexCachePcRelative:
2649 return os << "DexCachePcRelative";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002650 case HLoadString::LoadKind::kDexCacheViaMethod:
2651 return os << "DexCacheViaMethod";
2652 default:
2653 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2654 UNREACHABLE();
2655 }
2656}
2657
Mark Mendellc4701932015-04-10 13:18:51 -04002658void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002659 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2660 HEnvironment* user = use.GetUser();
2661 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002662 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002663 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002664}
2665
Roland Levillainc9b21f82016-03-23 16:36:59 +00002666// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002667HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2668 ArenaAllocator* allocator = GetArena();
2669
2670 if (cond->IsCondition() &&
2671 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2672 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2673 HInstruction* lhs = cond->InputAt(0);
2674 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002675 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002676 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2677 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2678 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2679 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2680 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2681 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2682 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2683 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2684 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2685 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2686 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002687 default:
2688 LOG(FATAL) << "Unexpected condition";
2689 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002690 }
2691 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2692 return replacement;
2693 } else if (cond->IsIntConstant()) {
2694 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002695 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002696 return GetIntConstant(1);
2697 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002698 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002699 return GetIntConstant(0);
2700 }
2701 } else {
2702 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2703 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2704 return replacement;
2705 }
2706}
2707
Roland Levillainc9285912015-12-18 10:38:42 +00002708std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2709 os << "["
2710 << " source=" << rhs.GetSource()
2711 << " destination=" << rhs.GetDestination()
2712 << " type=" << rhs.GetType()
2713 << " instruction=";
2714 if (rhs.GetInstruction() != nullptr) {
2715 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2716 } else {
2717 os << "null";
2718 }
2719 os << " ]";
2720 return os;
2721}
2722
Roland Levillain86503782016-02-11 19:07:30 +00002723std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2724 switch (rhs) {
2725 case TypeCheckKind::kUnresolvedCheck:
2726 return os << "unresolved_check";
2727 case TypeCheckKind::kExactCheck:
2728 return os << "exact_check";
2729 case TypeCheckKind::kClassHierarchyCheck:
2730 return os << "class_hierarchy_check";
2731 case TypeCheckKind::kAbstractClassCheck:
2732 return os << "abstract_class_check";
2733 case TypeCheckKind::kInterfaceCheck:
2734 return os << "interface_check";
2735 case TypeCheckKind::kArrayObjectCheck:
2736 return os << "array_object_check";
2737 case TypeCheckKind::kArrayCheck:
2738 return os << "array_check";
2739 default:
2740 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2741 UNREACHABLE();
2742 }
2743}
2744
Andreas Gampe26de38b2016-07-27 17:53:11 -07002745std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2746 switch (kind) {
2747 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002748 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002749 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002750 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002751 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002752 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002753 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002754 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002755 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002756 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002757
2758 default:
2759 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2760 UNREACHABLE();
2761 }
2762}
2763
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002764} // namespace art