blob: cea29bca2bc30f19600b01f96e0685a216c60110 [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
525void HGraph::Linearize() {
526 // Create a reverse post ordering with the following properties:
527 // - Blocks in a loop are consecutive,
528 // - Back-edge is the last block before loop exits.
529
530 // (1): Record the number of forward predecessors for each block. This is to
531 // ensure the resulting order is reverse post order. We could use the
532 // current reverse post order in the graph, but it would require making
533 // order queries to a GrowableArray, which is not the best data structure
534 // for it.
535 ArenaVector<uint32_t> forward_predecessors(blocks_.size(),
536 arena_->Adapter(kArenaAllocSsaLiveness));
537 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
538 HBasicBlock* block = it.Current();
539 size_t number_of_forward_predecessors = block->GetPredecessors().size();
540 if (block->IsLoopHeader()) {
541 number_of_forward_predecessors -= block->GetLoopInformation()->NumberOfBackEdges();
542 }
543 forward_predecessors[block->GetBlockId()] = number_of_forward_predecessors;
544 }
545
546 // (2): Following a worklist approach, first start with the entry block, and
547 // iterate over the successors. When all non-back edge predecessors of a
548 // successor block are visited, the successor block is added in the worklist
549 // following an order that satisfies the requirements to build our linear graph.
550 linear_order_.reserve(GetReversePostOrder().size());
551 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocSsaLiveness));
552 worklist.push_back(GetEntryBlock());
553 do {
554 HBasicBlock* current = worklist.back();
555 worklist.pop_back();
556 linear_order_.push_back(current);
557 for (HBasicBlock* successor : current->GetSuccessors()) {
558 int block_id = successor->GetBlockId();
559 size_t number_of_remaining_predecessors = forward_predecessors[block_id];
560 if (number_of_remaining_predecessors == 1) {
561 AddToListForLinearization(&worklist, successor);
562 }
563 forward_predecessors[block_id] = number_of_remaining_predecessors - 1;
564 }
565 } while (!worklist.empty());
566
567 DCHECK(HasIrreducibleLoops() || IsLinearOrderWellFormed(*this));
568}
569
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000570void HLoopInformation::Dump(std::ostream& os) {
571 os << "header: " << header_->GetBlockId() << std::endl;
572 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
573 for (HBasicBlock* block : back_edges_) {
574 os << "back edge: " << block->GetBlockId() << std::endl;
575 }
576 for (HBasicBlock* block : header_->GetPredecessors()) {
577 os << "predecessor: " << block->GetBlockId() << std::endl;
578 }
579 for (uint32_t idx : blocks_.Indexes()) {
580 os << " in loop: " << idx << std::endl;
581 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100582}
583
David Brazdil8d5b8b22015-03-24 10:51:52 +0000584void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000585 // New constants are inserted before the SuspendCheck at the bottom of the
586 // entry block. Note that this method can be called from the graph builder and
587 // the entry block therefore may not end with SuspendCheck->Goto yet.
588 HInstruction* insert_before = nullptr;
589
590 HInstruction* gota = entry_block_->GetLastInstruction();
591 if (gota != nullptr && gota->IsGoto()) {
592 HInstruction* suspend_check = gota->GetPrevious();
593 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
594 insert_before = suspend_check;
595 } else {
596 insert_before = gota;
597 }
598 }
599
600 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000601 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000602 } else {
603 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000604 }
605}
606
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600607HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100608 // For simplicity, don't bother reviving the cached null constant if it is
609 // not null and not in a block. Otherwise, we need to clear the instruction
610 // id and/or any invariants the graph is assuming when adding new instructions.
611 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600612 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000613 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000614 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000615 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000616 if (kIsDebugBuild) {
617 ScopedObjectAccess soa(Thread::Current());
618 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
619 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000620 return cached_null_constant_;
621}
622
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100623HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100624 // For simplicity, don't bother reviving the cached current method if it is
625 // not null and not in a block. Otherwise, we need to clear the instruction
626 // id and/or any invariants the graph is assuming when adding new instructions.
627 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700628 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600629 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
630 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100631 if (entry_block_->GetFirstInstruction() == nullptr) {
632 entry_block_->AddInstruction(cached_current_method_);
633 } else {
634 entry_block_->InsertInstructionBefore(
635 cached_current_method_, entry_block_->GetFirstInstruction());
636 }
637 }
638 return cached_current_method_;
639}
640
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600641HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000642 switch (type) {
643 case Primitive::Type::kPrimBoolean:
644 DCHECK(IsUint<1>(value));
645 FALLTHROUGH_INTENDED;
646 case Primitive::Type::kPrimByte:
647 case Primitive::Type::kPrimChar:
648 case Primitive::Type::kPrimShort:
649 case Primitive::Type::kPrimInt:
650 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600651 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000652
653 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600654 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000655
656 default:
657 LOG(FATAL) << "Unsupported constant type";
658 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000659 }
David Brazdil46e2a392015-03-16 17:31:52 +0000660}
661
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000662void HGraph::CacheFloatConstant(HFloatConstant* constant) {
663 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
664 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
665 cached_float_constants_.Overwrite(value, constant);
666}
667
668void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
669 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
670 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
671 cached_double_constants_.Overwrite(value, constant);
672}
673
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000674void HLoopInformation::Add(HBasicBlock* block) {
675 blocks_.SetBit(block->GetBlockId());
676}
677
David Brazdil46e2a392015-03-16 17:31:52 +0000678void HLoopInformation::Remove(HBasicBlock* block) {
679 blocks_.ClearBit(block->GetBlockId());
680}
681
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100682void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
683 if (blocks_.IsBitSet(block->GetBlockId())) {
684 return;
685 }
686
687 blocks_.SetBit(block->GetBlockId());
688 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100689 if (block->IsLoopHeader()) {
690 // We're visiting loops in post-order, so inner loops must have been
691 // populated already.
692 DCHECK(block->GetLoopInformation()->IsPopulated());
693 if (block->GetLoopInformation()->IsIrreducible()) {
694 contains_irreducible_loop_ = true;
695 }
696 }
Vladimir Marko60584552015-09-03 13:35:12 +0000697 for (HBasicBlock* predecessor : block->GetPredecessors()) {
698 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100699 }
700}
701
David Brazdilc2e8af92016-04-05 17:15:19 +0100702void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
703 size_t block_id = block->GetBlockId();
704
705 // If `block` is in `finalized`, we know its membership in the loop has been
706 // decided and it does not need to be revisited.
707 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000708 return;
709 }
710
David Brazdilc2e8af92016-04-05 17:15:19 +0100711 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000712 if (block->IsLoopHeader()) {
713 // If we hit a loop header in an irreducible loop, we first check if the
714 // pre header of that loop belongs to the currently analyzed loop. If it does,
715 // then we visit the back edges.
716 // Note that we cannot use GetPreHeader, as the loop may have not been populated
717 // yet.
718 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100719 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000720 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000721 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100722 blocks_.SetBit(block_id);
723 finalized->SetBit(block_id);
724 is_finalized = true;
725
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000726 HLoopInformation* info = block->GetLoopInformation();
727 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100728 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000729 }
730 }
731 } else {
732 // Visit all predecessors. If one predecessor is part of the loop, this
733 // block is also part of this loop.
734 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100735 PopulateIrreducibleRecursive(predecessor, finalized);
736 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000737 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100738 blocks_.SetBit(block_id);
739 finalized->SetBit(block_id);
740 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000741 }
742 }
743 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100744
745 // All predecessors have been recursively visited. Mark finalized if not marked yet.
746 if (!is_finalized) {
747 finalized->SetBit(block_id);
748 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000749}
750
751void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100752 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000753 // Populate this loop: starting with the back edge, recursively add predecessors
754 // that are not already part of that loop. Set the header as part of the loop
755 // to end the recursion.
756 // This is a recursive implementation of the algorithm described in
757 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100758 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000759 blocks_.SetBit(header_->GetBlockId());
760 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100761
David Brazdil3f4a5222016-05-06 12:46:21 +0100762 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100763
764 if (is_irreducible_loop) {
765 ArenaBitVector visited(graph->GetArena(),
766 graph->GetBlocks().size(),
767 /* expandable */ false,
768 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100769 // Stop marking blocks at the loop header.
770 visited.SetBit(header_->GetBlockId());
771
David Brazdilc2e8af92016-04-05 17:15:19 +0100772 for (HBasicBlock* back_edge : GetBackEdges()) {
773 PopulateIrreducibleRecursive(back_edge, &visited);
774 }
775 } else {
776 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000777 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100778 }
David Brazdila4b8c212015-05-07 09:59:30 +0100779 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100780
Vladimir Markofd66c502016-04-18 15:37:01 +0100781 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
782 // When compiling in OSR mode, all loops in the compiled method may be entered
783 // from the interpreter. We treat this OSR entry point just like an extra entry
784 // to an irreducible loop, so we need to mark the method's loops as irreducible.
785 // This does not apply to inlined loops which do not act as OSR entry points.
786 if (suspend_check_ == nullptr) {
787 // Just building the graph in OSR mode, this loop is not inlined. We never build an
788 // inner graph in OSR mode as we can do OSR transition only from the outer method.
789 is_irreducible_loop = true;
790 } else {
791 // Look at the suspend check's environment to determine if the loop was inlined.
792 DCHECK(suspend_check_->HasEnvironment());
793 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
794 is_irreducible_loop = true;
795 }
796 }
797 }
798 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100799 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100800 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100801 graph->SetHasIrreducibleLoops(true);
802 }
David Brazdila4b8c212015-05-07 09:59:30 +0100803}
804
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100805HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000806 HBasicBlock* block = header_->GetPredecessors()[0];
807 DCHECK(irreducible_ || (block == header_->GetDominator()));
808 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100809}
810
811bool HLoopInformation::Contains(const HBasicBlock& block) const {
812 return blocks_.IsBitSet(block.GetBlockId());
813}
814
815bool HLoopInformation::IsIn(const HLoopInformation& other) const {
816 return other.blocks_.IsBitSet(header_->GetBlockId());
817}
818
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800819bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
820 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700821}
822
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100823size_t HLoopInformation::GetLifetimeEnd() const {
824 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100825 for (HBasicBlock* back_edge : GetBackEdges()) {
826 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100827 }
828 return last_position;
829}
830
David Brazdil3f4a5222016-05-06 12:46:21 +0100831bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
832 for (HBasicBlock* back_edge : GetBackEdges()) {
833 DCHECK(back_edge->GetDominator() != nullptr);
834 if (!header_->Dominates(back_edge)) {
835 return true;
836 }
837 }
838 return false;
839}
840
Anton Shaminf89381f2016-05-16 16:44:13 +0600841bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
842 for (HBasicBlock* back_edge : GetBackEdges()) {
843 if (!block->Dominates(back_edge)) {
844 return false;
845 }
846 }
847 return true;
848}
849
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100850bool HBasicBlock::Dominates(HBasicBlock* other) const {
851 // Walk up the dominator tree from `other`, to find out if `this`
852 // is an ancestor.
853 HBasicBlock* current = other;
854 while (current != nullptr) {
855 if (current == this) {
856 return true;
857 }
858 current = current->GetDominator();
859 }
860 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100861}
862
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100863static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100864 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100865 for (size_t i = 0; i < inputs.size(); ++i) {
866 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100867 }
868 // Environment should be created later.
869 DCHECK(!instruction->HasEnvironment());
870}
871
Roland Levillainccc07a92014-09-16 14:48:16 +0100872void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
873 HInstruction* replacement) {
874 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400875 if (initial->IsControlFlow()) {
876 // We can only replace a control flow instruction with another control flow instruction.
877 DCHECK(replacement->IsControlFlow());
878 DCHECK_EQ(replacement->GetId(), -1);
879 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
880 DCHECK_EQ(initial->GetBlock(), this);
881 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100882 DCHECK(initial->GetUses().empty());
883 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400884 replacement->SetBlock(this);
885 replacement->SetId(GetGraph()->GetNextInstructionId());
886 instructions_.InsertInstructionBefore(replacement, initial);
887 UpdateInputsUsers(replacement);
888 } else {
889 InsertInstructionBefore(replacement, initial);
890 initial->ReplaceWith(replacement);
891 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100892 RemoveInstruction(initial);
893}
894
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895static void Add(HInstructionList* instruction_list,
896 HBasicBlock* block,
897 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000898 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000899 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100900 instruction->SetBlock(block);
901 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100902 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100903 instruction_list->AddInstruction(instruction);
904}
905
906void HBasicBlock::AddInstruction(HInstruction* instruction) {
907 Add(&instructions_, this, instruction);
908}
909
910void HBasicBlock::AddPhi(HPhi* phi) {
911 Add(&phis_, this, phi);
912}
913
David Brazdilc3d743f2015-04-22 13:40:50 +0100914void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
915 DCHECK(!cursor->IsPhi());
916 DCHECK(!instruction->IsPhi());
917 DCHECK_EQ(instruction->GetId(), -1);
918 DCHECK_NE(cursor->GetId(), -1);
919 DCHECK_EQ(cursor->GetBlock(), this);
920 DCHECK(!instruction->IsControlFlow());
921 instruction->SetBlock(this);
922 instruction->SetId(GetGraph()->GetNextInstructionId());
923 UpdateInputsUsers(instruction);
924 instructions_.InsertInstructionBefore(instruction, cursor);
925}
926
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100927void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
928 DCHECK(!cursor->IsPhi());
929 DCHECK(!instruction->IsPhi());
930 DCHECK_EQ(instruction->GetId(), -1);
931 DCHECK_NE(cursor->GetId(), -1);
932 DCHECK_EQ(cursor->GetBlock(), this);
933 DCHECK(!instruction->IsControlFlow());
934 DCHECK(!cursor->IsControlFlow());
935 instruction->SetBlock(this);
936 instruction->SetId(GetGraph()->GetNextInstructionId());
937 UpdateInputsUsers(instruction);
938 instructions_.InsertInstructionAfter(instruction, cursor);
939}
940
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100941void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
942 DCHECK_EQ(phi->GetId(), -1);
943 DCHECK_NE(cursor->GetId(), -1);
944 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100945 phi->SetBlock(this);
946 phi->SetId(GetGraph()->GetNextInstructionId());
947 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100948 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100949}
950
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100951static void Remove(HInstructionList* instruction_list,
952 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000953 HInstruction* instruction,
954 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100955 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100956 instruction->SetBlock(nullptr);
957 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000958 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100959 DCHECK(instruction->GetUses().empty());
960 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000961 RemoveAsUser(instruction);
962 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100963}
964
David Brazdil1abb4192015-02-17 18:33:36 +0000965void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100966 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000967 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100968}
969
David Brazdil1abb4192015-02-17 18:33:36 +0000970void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
971 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100972}
973
David Brazdilc7508e92015-04-27 13:28:57 +0100974void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
975 if (instruction->IsPhi()) {
976 RemovePhi(instruction->AsPhi(), ensure_safety);
977 } else {
978 RemoveInstruction(instruction, ensure_safety);
979 }
980}
981
Vladimir Marko71bf8092015-09-15 15:33:14 +0100982void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
983 for (size_t i = 0; i < locals.size(); i++) {
984 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100985 SetRawEnvAt(i, instruction);
986 if (instruction != nullptr) {
987 instruction->AddEnvUseAt(this, i);
988 }
989 }
990}
991
David Brazdiled596192015-01-23 10:39:45 +0000992void HEnvironment::CopyFrom(HEnvironment* env) {
993 for (size_t i = 0; i < env->Size(); i++) {
994 HInstruction* instruction = env->GetInstructionAt(i);
995 SetRawEnvAt(i, instruction);
996 if (instruction != nullptr) {
997 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100998 }
David Brazdiled596192015-01-23 10:39:45 +0000999 }
1000}
1001
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001002void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1003 HBasicBlock* loop_header) {
1004 DCHECK(loop_header->IsLoopHeader());
1005 for (size_t i = 0; i < env->Size(); i++) {
1006 HInstruction* instruction = env->GetInstructionAt(i);
1007 SetRawEnvAt(i, instruction);
1008 if (instruction == nullptr) {
1009 continue;
1010 }
1011 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1012 // At the end of the loop pre-header, the corresponding value for instruction
1013 // is the first input of the phi.
1014 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001015 SetRawEnvAt(i, initial);
1016 initial->AddEnvUseAt(this, i);
1017 } else {
1018 instruction->AddEnvUseAt(this, i);
1019 }
1020 }
1021}
1022
David Brazdil1abb4192015-02-17 18:33:36 +00001023void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001024 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1025 HInstruction* user = env_use.GetInstruction();
1026 auto before_env_use_node = env_use.GetBeforeUseNode();
1027 user->env_uses_.erase_after(before_env_use_node);
1028 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001029}
1030
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001031HInstruction::InstructionKind HInstruction::GetKind() const {
1032 return GetKindInternal();
1033}
1034
Calin Juravle77520bc2015-01-12 18:45:46 +00001035HInstruction* HInstruction::GetNextDisregardingMoves() const {
1036 HInstruction* next = GetNext();
1037 while (next != nullptr && next->IsParallelMove()) {
1038 next = next->GetNext();
1039 }
1040 return next;
1041}
1042
1043HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1044 HInstruction* previous = GetPrevious();
1045 while (previous != nullptr && previous->IsParallelMove()) {
1046 previous = previous->GetPrevious();
1047 }
1048 return previous;
1049}
1050
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001051void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001052 if (first_instruction_ == nullptr) {
1053 DCHECK(last_instruction_ == nullptr);
1054 first_instruction_ = last_instruction_ = instruction;
1055 } else {
1056 last_instruction_->next_ = instruction;
1057 instruction->previous_ = last_instruction_;
1058 last_instruction_ = instruction;
1059 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001060}
1061
David Brazdilc3d743f2015-04-22 13:40:50 +01001062void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1063 DCHECK(Contains(cursor));
1064 if (cursor == first_instruction_) {
1065 cursor->previous_ = instruction;
1066 instruction->next_ = cursor;
1067 first_instruction_ = instruction;
1068 } else {
1069 instruction->previous_ = cursor->previous_;
1070 instruction->next_ = cursor;
1071 cursor->previous_ = instruction;
1072 instruction->previous_->next_ = instruction;
1073 }
1074}
1075
1076void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1077 DCHECK(Contains(cursor));
1078 if (cursor == last_instruction_) {
1079 cursor->next_ = instruction;
1080 instruction->previous_ = cursor;
1081 last_instruction_ = instruction;
1082 } else {
1083 instruction->next_ = cursor->next_;
1084 instruction->previous_ = cursor;
1085 cursor->next_ = instruction;
1086 instruction->next_->previous_ = instruction;
1087 }
1088}
1089
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001090void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1091 if (instruction->previous_ != nullptr) {
1092 instruction->previous_->next_ = instruction->next_;
1093 }
1094 if (instruction->next_ != nullptr) {
1095 instruction->next_->previous_ = instruction->previous_;
1096 }
1097 if (instruction == first_instruction_) {
1098 first_instruction_ = instruction->next_;
1099 }
1100 if (instruction == last_instruction_) {
1101 last_instruction_ = instruction->previous_;
1102 }
1103}
1104
Roland Levillain6b469232014-09-25 10:10:38 +01001105bool HInstructionList::Contains(HInstruction* instruction) const {
1106 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1107 if (it.Current() == instruction) {
1108 return true;
1109 }
1110 }
1111 return false;
1112}
1113
Roland Levillainccc07a92014-09-16 14:48:16 +01001114bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1115 const HInstruction* instruction2) const {
1116 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1117 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1118 if (it.Current() == instruction1) {
1119 return true;
1120 }
1121 if (it.Current() == instruction2) {
1122 return false;
1123 }
1124 }
1125 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1126 return true;
1127}
1128
Roland Levillain6c82d402014-10-13 16:10:27 +01001129bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1130 if (other_instruction == this) {
1131 // An instruction does not strictly dominate itself.
1132 return false;
1133 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001134 HBasicBlock* block = GetBlock();
1135 HBasicBlock* other_block = other_instruction->GetBlock();
1136 if (block != other_block) {
1137 return GetBlock()->Dominates(other_instruction->GetBlock());
1138 } else {
1139 // If both instructions are in the same block, ensure this
1140 // instruction comes before `other_instruction`.
1141 if (IsPhi()) {
1142 if (!other_instruction->IsPhi()) {
1143 // Phis appear before non phi-instructions so this instruction
1144 // dominates `other_instruction`.
1145 return true;
1146 } else {
1147 // There is no order among phis.
1148 LOG(FATAL) << "There is no dominance between phis of a same block.";
1149 return false;
1150 }
1151 } else {
1152 // `this` is not a phi.
1153 if (other_instruction->IsPhi()) {
1154 // Phis appear before non phi-instructions so this instruction
1155 // does not dominate `other_instruction`.
1156 return false;
1157 } else {
1158 // Check whether this instruction comes before
1159 // `other_instruction` in the instruction list.
1160 return block->GetInstructions().FoundBefore(this, other_instruction);
1161 }
1162 }
1163 }
1164}
1165
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001166void HInstruction::RemoveEnvironment() {
1167 RemoveEnvironmentUses(this);
1168 environment_ = nullptr;
1169}
1170
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001171void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001172 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001173 // Note: fixup_end remains valid across splice_after().
1174 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1175 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1176 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001177
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001178 // Note: env_fixup_end remains valid across splice_after().
1179 auto env_fixup_end =
1180 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1181 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1182 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001183
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001184 DCHECK(uses_.empty());
1185 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001186}
1187
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001188void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001189 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001190 if (input_use.GetInstruction() == replacement) {
1191 // Nothing to do.
1192 return;
1193 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001194 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001195 // Note: fixup_end remains valid across splice_after().
1196 auto fixup_end =
1197 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1198 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1199 input_use.GetInstruction()->uses_,
1200 before_use_node);
1201 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1202 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001203}
1204
Nicolas Geoffray39468442014-09-02 15:17:15 +01001205size_t HInstruction::EnvironmentSize() const {
1206 return HasEnvironment() ? environment_->Size() : 0;
1207}
1208
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001209void HPhi::AddInput(HInstruction* input) {
1210 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001211 inputs_.push_back(HUserRecord<HInstruction*>(input));
1212 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001213}
1214
David Brazdil2d7352b2015-04-20 14:52:42 +01001215void HPhi::RemoveInputAt(size_t index) {
1216 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001217 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001218 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1219 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1220 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1221 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001222 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001223}
1224
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001225#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001226void H##name::Accept(HGraphVisitor* visitor) { \
1227 visitor->Visit##name(this); \
1228}
1229
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001230FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001231
1232#undef DEFINE_ACCEPT
1233
1234void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001235 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1236 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001237 if (block != nullptr) {
1238 VisitBasicBlock(block);
1239 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001240 }
1241}
1242
Roland Levillain633021e2014-10-01 14:12:25 +01001243void HGraphVisitor::VisitReversePostOrder() {
1244 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1245 VisitBasicBlock(it.Current());
1246 }
1247}
1248
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001249void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001250 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001251 it.Current()->Accept(this);
1252 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001253 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001254 it.Current()->Accept(this);
1255 }
1256}
1257
Mark Mendelle82549b2015-05-06 10:55:34 -04001258HConstant* HTypeConversion::TryStaticEvaluation() const {
1259 HGraph* graph = GetBlock()->GetGraph();
1260 if (GetInput()->IsIntConstant()) {
1261 int32_t value = GetInput()->AsIntConstant()->GetValue();
1262 switch (GetResultType()) {
1263 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001264 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001265 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001266 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001267 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001268 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001269 default:
1270 return nullptr;
1271 }
1272 } else if (GetInput()->IsLongConstant()) {
1273 int64_t value = GetInput()->AsLongConstant()->GetValue();
1274 switch (GetResultType()) {
1275 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001276 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001277 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001278 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001279 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001280 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001281 default:
1282 return nullptr;
1283 }
1284 } else if (GetInput()->IsFloatConstant()) {
1285 float value = GetInput()->AsFloatConstant()->GetValue();
1286 switch (GetResultType()) {
1287 case Primitive::kPrimInt:
1288 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001289 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001290 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001291 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001292 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001293 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1294 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001295 case Primitive::kPrimLong:
1296 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001297 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001298 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001299 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001300 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001301 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1302 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001303 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001304 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001305 default:
1306 return nullptr;
1307 }
1308 } else if (GetInput()->IsDoubleConstant()) {
1309 double value = GetInput()->AsDoubleConstant()->GetValue();
1310 switch (GetResultType()) {
1311 case Primitive::kPrimInt:
1312 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001313 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001314 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001315 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001316 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001317 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1318 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001319 case Primitive::kPrimLong:
1320 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001321 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001322 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001323 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001324 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001325 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1326 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001327 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001328 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001329 default:
1330 return nullptr;
1331 }
1332 }
1333 return nullptr;
1334}
1335
Roland Levillain9240d6a2014-10-20 16:47:04 +01001336HConstant* HUnaryOperation::TryStaticEvaluation() const {
1337 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001338 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001339 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001340 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001341 } else if (kEnableFloatingPointStaticEvaluation) {
1342 if (GetInput()->IsFloatConstant()) {
1343 return Evaluate(GetInput()->AsFloatConstant());
1344 } else if (GetInput()->IsDoubleConstant()) {
1345 return Evaluate(GetInput()->AsDoubleConstant());
1346 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001347 }
1348 return nullptr;
1349}
1350
1351HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001352 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1353 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001354 } else if (GetLeft()->IsLongConstant()) {
1355 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001356 // The binop(long, int) case is only valid for shifts and rotations.
1357 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001358 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1359 } else if (GetRight()->IsLongConstant()) {
1360 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001361 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001362 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001363 // The binop(null, null) case is only valid for equal and not-equal conditions.
1364 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001365 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001366 } else if (kEnableFloatingPointStaticEvaluation) {
1367 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1368 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1369 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1370 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1371 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001372 }
1373 return nullptr;
1374}
Dave Allison20dfc792014-06-16 20:44:29 -07001375
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001376HConstant* HBinaryOperation::GetConstantRight() const {
1377 if (GetRight()->IsConstant()) {
1378 return GetRight()->AsConstant();
1379 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1380 return GetLeft()->AsConstant();
1381 } else {
1382 return nullptr;
1383 }
1384}
1385
1386// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001387// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001388HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1389 HInstruction* most_constant_right = GetConstantRight();
1390 if (most_constant_right == nullptr) {
1391 return nullptr;
1392 } else if (most_constant_right == GetLeft()) {
1393 return GetRight();
1394 } else {
1395 return GetLeft();
1396 }
1397}
1398
Roland Levillain31dd3d62016-02-16 12:21:02 +00001399std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1400 switch (rhs) {
1401 case ComparisonBias::kNoBias:
1402 return os << "no_bias";
1403 case ComparisonBias::kGtBias:
1404 return os << "gt_bias";
1405 case ComparisonBias::kLtBias:
1406 return os << "lt_bias";
1407 default:
1408 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1409 UNREACHABLE();
1410 }
1411}
1412
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001413bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1414 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001415}
1416
Vladimir Marko372f10e2016-05-17 16:30:10 +01001417bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001418 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001419 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001420 if (!InstructionDataEquals(other)) return false;
1421 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001422 HConstInputsRef inputs = GetInputs();
1423 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001424 if (inputs.size() != other_inputs.size()) return false;
1425 for (size_t i = 0; i != inputs.size(); ++i) {
1426 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001427 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001428
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001429 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001430 return true;
1431}
1432
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001433std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1434#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1435 switch (rhs) {
1436 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1437 default:
1438 os << "Unknown instruction kind " << static_cast<int>(rhs);
1439 break;
1440 }
1441#undef DECLARE_CASE
1442 return os;
1443}
1444
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001445void HInstruction::MoveBefore(HInstruction* cursor) {
David Brazdild6c205e2016-06-07 14:20:52 +01001446 DCHECK(!IsPhi());
1447 DCHECK(!IsControlFlow());
1448 DCHECK(CanBeMoved());
1449 DCHECK(!cursor->IsPhi());
1450
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001451 next_->previous_ = previous_;
1452 if (previous_ != nullptr) {
1453 previous_->next_ = next_;
1454 }
1455 if (block_->instructions_.first_instruction_ == this) {
1456 block_->instructions_.first_instruction_ = next_;
1457 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001458 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001459
1460 previous_ = cursor->previous_;
1461 if (previous_ != nullptr) {
1462 previous_->next_ = this;
1463 }
1464 next_ = cursor;
1465 cursor->previous_ = this;
1466 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001467
1468 if (block_->instructions_.first_instruction_ == cursor) {
1469 block_->instructions_.first_instruction_ = this;
1470 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001471}
1472
Vladimir Markofb337ea2015-11-25 15:25:10 +00001473void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1474 DCHECK(!CanThrow());
1475 DCHECK(!HasSideEffects());
1476 DCHECK(!HasEnvironmentUses());
1477 DCHECK(HasNonEnvironmentUses());
1478 DCHECK(!IsPhi()); // Makes no sense for Phi.
1479 DCHECK_EQ(InputCount(), 0u);
1480
1481 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001482 auto uses_it = GetUses().begin();
1483 auto uses_end = GetUses().end();
1484 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1485 ++uses_it;
1486 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1487 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001488 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001489 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001490 // This instruction has uses in two or more blocks. Find the common dominator.
1491 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001492 for (; uses_it != uses_end; ++uses_it) {
1493 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001494 }
1495 target_block = finder.Get();
1496 DCHECK(target_block != nullptr);
1497 }
1498 // Move to the first dominator not in a loop.
1499 while (target_block->IsInLoop()) {
1500 target_block = target_block->GetDominator();
1501 DCHECK(target_block != nullptr);
1502 }
1503
1504 // Find insertion position.
1505 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001506 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1507 if (use.GetUser()->GetBlock() == target_block &&
1508 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1509 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001510 }
1511 }
1512 if (insert_pos == nullptr) {
1513 // No user in `target_block`, insert before the control flow instruction.
1514 insert_pos = target_block->GetLastInstruction();
1515 DCHECK(insert_pos->IsControlFlow());
1516 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1517 if (insert_pos->IsIf()) {
1518 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1519 if (if_input == insert_pos->GetPrevious()) {
1520 insert_pos = if_input;
1521 }
1522 }
1523 }
1524 MoveBefore(insert_pos);
1525}
1526
David Brazdilfc6a86a2015-06-26 10:33:45 +00001527HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001528 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001529 DCHECK_EQ(cursor->GetBlock(), this);
1530
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001531 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1532 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001533 new_block->instructions_.first_instruction_ = cursor;
1534 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1535 instructions_.last_instruction_ = cursor->previous_;
1536 if (cursor->previous_ == nullptr) {
1537 instructions_.first_instruction_ = nullptr;
1538 } else {
1539 cursor->previous_->next_ = nullptr;
1540 cursor->previous_ = nullptr;
1541 }
1542
1543 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001544 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001545
Vladimir Marko60584552015-09-03 13:35:12 +00001546 for (HBasicBlock* successor : GetSuccessors()) {
1547 new_block->successors_.push_back(successor);
1548 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001549 }
Vladimir Marko60584552015-09-03 13:35:12 +00001550 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001551 AddSuccessor(new_block);
1552
David Brazdil56e1acc2015-06-30 15:41:36 +01001553 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001554 return new_block;
1555}
1556
David Brazdild7558da2015-09-22 13:04:14 +01001557HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001558 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001559 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1560
1561 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1562
1563 for (HBasicBlock* predecessor : GetPredecessors()) {
1564 new_block->predecessors_.push_back(predecessor);
1565 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1566 }
1567 predecessors_.clear();
1568 AddPredecessor(new_block);
1569
1570 GetGraph()->AddBlock(new_block);
1571 return new_block;
1572}
1573
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001574HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1575 DCHECK_EQ(cursor->GetBlock(), this);
1576
1577 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1578 cursor->GetDexPc());
1579 new_block->instructions_.first_instruction_ = cursor;
1580 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1581 instructions_.last_instruction_ = cursor->previous_;
1582 if (cursor->previous_ == nullptr) {
1583 instructions_.first_instruction_ = nullptr;
1584 } else {
1585 cursor->previous_->next_ = nullptr;
1586 cursor->previous_ = nullptr;
1587 }
1588
1589 new_block->instructions_.SetBlockOfInstructions(new_block);
1590
1591 for (HBasicBlock* successor : GetSuccessors()) {
1592 new_block->successors_.push_back(successor);
1593 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1594 }
1595 successors_.clear();
1596
1597 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1598 dominated->dominator_ = new_block;
1599 new_block->dominated_blocks_.push_back(dominated);
1600 }
1601 dominated_blocks_.clear();
1602 return new_block;
1603}
1604
1605HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001606 DCHECK(!cursor->IsControlFlow());
1607 DCHECK_NE(instructions_.last_instruction_, cursor);
1608 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001609
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001610 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1611 new_block->instructions_.first_instruction_ = cursor->GetNext();
1612 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1613 cursor->next_->previous_ = nullptr;
1614 cursor->next_ = nullptr;
1615 instructions_.last_instruction_ = cursor;
1616
1617 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001618 for (HBasicBlock* successor : GetSuccessors()) {
1619 new_block->successors_.push_back(successor);
1620 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001621 }
Vladimir Marko60584552015-09-03 13:35:12 +00001622 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001623
Vladimir Marko60584552015-09-03 13:35:12 +00001624 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001625 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001626 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001627 }
Vladimir Marko60584552015-09-03 13:35:12 +00001628 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001629 return new_block;
1630}
1631
David Brazdilec16f792015-08-19 15:04:01 +01001632const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001633 if (EndsWithTryBoundary()) {
1634 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1635 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001636 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001637 return try_boundary;
1638 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001639 DCHECK(IsTryBlock());
1640 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001641 return nullptr;
1642 }
David Brazdilec16f792015-08-19 15:04:01 +01001643 } else if (IsTryBlock()) {
1644 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001645 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001646 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001647 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001648}
1649
David Brazdild7558da2015-09-22 13:04:14 +01001650bool HBasicBlock::HasThrowingInstructions() const {
1651 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1652 if (it.Current()->CanThrow()) {
1653 return true;
1654 }
1655 }
1656 return false;
1657}
1658
David Brazdilfc6a86a2015-06-26 10:33:45 +00001659static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1660 return block.GetPhis().IsEmpty()
1661 && !block.GetInstructions().IsEmpty()
1662 && block.GetFirstInstruction() == block.GetLastInstruction();
1663}
1664
David Brazdil46e2a392015-03-16 17:31:52 +00001665bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001666 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1667}
1668
1669bool HBasicBlock::IsSingleTryBoundary() const {
1670 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001671}
1672
David Brazdil8d5b8b22015-03-24 10:51:52 +00001673bool HBasicBlock::EndsWithControlFlowInstruction() const {
1674 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1675}
1676
David Brazdilb2bd1c52015-03-25 11:17:37 +00001677bool HBasicBlock::EndsWithIf() const {
1678 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1679}
1680
David Brazdilffee3d32015-07-06 11:48:53 +01001681bool HBasicBlock::EndsWithTryBoundary() const {
1682 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1683}
1684
David Brazdilb2bd1c52015-03-25 11:17:37 +00001685bool HBasicBlock::HasSinglePhi() const {
1686 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1687}
1688
David Brazdild26a4112015-11-10 11:07:31 +00001689ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1690 if (EndsWithTryBoundary()) {
1691 // The normal-flow successor of HTryBoundary is always stored at index zero.
1692 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1693 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1694 } else {
1695 // All successors of blocks not ending with TryBoundary are normal.
1696 return ArrayRef<HBasicBlock* const>(successors_);
1697 }
1698}
1699
1700ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1701 if (EndsWithTryBoundary()) {
1702 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1703 } else {
1704 // Blocks not ending with TryBoundary do not have exceptional successors.
1705 return ArrayRef<HBasicBlock* const>();
1706 }
1707}
1708
David Brazdilffee3d32015-07-06 11:48:53 +01001709bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001710 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1711 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1712
1713 size_t length = handlers1.size();
1714 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001715 return false;
1716 }
1717
David Brazdilb618ade2015-07-29 10:31:29 +01001718 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001719 for (size_t i = 0; i < length; ++i) {
1720 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001721 return false;
1722 }
1723 }
1724 return true;
1725}
1726
David Brazdil2d7352b2015-04-20 14:52:42 +01001727size_t HInstructionList::CountSize() const {
1728 size_t size = 0;
1729 HInstruction* current = first_instruction_;
1730 for (; current != nullptr; current = current->GetNext()) {
1731 size++;
1732 }
1733 return size;
1734}
1735
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001736void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1737 for (HInstruction* current = first_instruction_;
1738 current != nullptr;
1739 current = current->GetNext()) {
1740 current->SetBlock(block);
1741 }
1742}
1743
1744void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1745 DCHECK(Contains(cursor));
1746 if (!instruction_list.IsEmpty()) {
1747 if (cursor == last_instruction_) {
1748 last_instruction_ = instruction_list.last_instruction_;
1749 } else {
1750 cursor->next_->previous_ = instruction_list.last_instruction_;
1751 }
1752 instruction_list.last_instruction_->next_ = cursor->next_;
1753 cursor->next_ = instruction_list.first_instruction_;
1754 instruction_list.first_instruction_->previous_ = cursor;
1755 }
1756}
1757
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001758void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1759 DCHECK(Contains(cursor));
1760 if (!instruction_list.IsEmpty()) {
1761 if (cursor == first_instruction_) {
1762 first_instruction_ = instruction_list.first_instruction_;
1763 } else {
1764 cursor->previous_->next_ = instruction_list.first_instruction_;
1765 }
1766 instruction_list.last_instruction_->next_ = cursor;
1767 instruction_list.first_instruction_->previous_ = cursor->previous_;
1768 cursor->previous_ = instruction_list.last_instruction_;
1769 }
1770}
1771
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001772void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001773 if (IsEmpty()) {
1774 first_instruction_ = instruction_list.first_instruction_;
1775 last_instruction_ = instruction_list.last_instruction_;
1776 } else {
1777 AddAfter(last_instruction_, instruction_list);
1778 }
1779}
1780
David Brazdil04ff4e82015-12-10 13:54:52 +00001781// Should be called on instructions in a dead block in post order. This method
1782// assumes `insn` has been removed from all users with the exception of catch
1783// phis because of missing exceptional edges in the graph. It removes the
1784// instruction from catch phi uses, together with inputs of other catch phis in
1785// the catch block at the same index, as these must be dead too.
1786static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1787 DCHECK(!insn->HasEnvironmentUses());
1788 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001789 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1790 size_t use_index = use.GetIndex();
1791 HBasicBlock* user_block = use.GetUser()->GetBlock();
1792 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001793 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1794 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1795 }
1796 }
1797}
1798
David Brazdil2d7352b2015-04-20 14:52:42 +01001799void HBasicBlock::DisconnectAndDelete() {
1800 // Dominators must be removed after all the blocks they dominate. This way
1801 // a loop header is removed last, a requirement for correct loop information
1802 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001803 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001804
David Brazdil9eeebf62016-03-24 11:18:15 +00001805 // The following steps gradually remove the block from all its dependants in
1806 // post order (b/27683071).
1807
1808 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1809 // We need to do this before step (4) which destroys the predecessor list.
1810 HBasicBlock* loop_update_start = this;
1811 if (IsLoopHeader()) {
1812 HLoopInformation* loop_info = GetLoopInformation();
1813 // All other blocks in this loop should have been removed because the header
1814 // was their dominator.
1815 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1816 DCHECK(!loop_info->IsIrreducible());
1817 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1818 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1819 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001820 }
1821
David Brazdil9eeebf62016-03-24 11:18:15 +00001822 // (2) Disconnect the block from its successors and update their phis.
1823 for (HBasicBlock* successor : successors_) {
1824 // Delete this block from the list of predecessors.
1825 size_t this_index = successor->GetPredecessorIndexOf(this);
1826 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1827
1828 // Check that `successor` has other predecessors, otherwise `this` is the
1829 // dominator of `successor` which violates the order DCHECKed at the top.
1830 DCHECK(!successor->predecessors_.empty());
1831
1832 // Remove this block's entries in the successor's phis. Skip exceptional
1833 // successors because catch phi inputs do not correspond to predecessor
1834 // blocks but throwing instructions. The inputs of the catch phis will be
1835 // updated in step (3).
1836 if (!successor->IsCatchBlock()) {
1837 if (successor->predecessors_.size() == 1u) {
1838 // The successor has just one predecessor left. Replace phis with the only
1839 // remaining input.
1840 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1841 HPhi* phi = phi_it.Current()->AsPhi();
1842 phi->ReplaceWith(phi->InputAt(1 - this_index));
1843 successor->RemovePhi(phi);
1844 }
1845 } else {
1846 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1847 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1848 }
1849 }
1850 }
1851 }
1852 successors_.clear();
1853
1854 // (3) Remove instructions and phis. Instructions should have no remaining uses
1855 // except in catch phis. If an instruction is used by a catch phi at `index`,
1856 // remove `index`-th input of all phis in the catch block since they are
1857 // guaranteed dead. Note that we may miss dead inputs this way but the
1858 // graph will always remain consistent.
1859 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1860 HInstruction* insn = it.Current();
1861 RemoveUsesOfDeadInstruction(insn);
1862 RemoveInstruction(insn);
1863 }
1864 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1865 HPhi* insn = it.Current()->AsPhi();
1866 RemoveUsesOfDeadInstruction(insn);
1867 RemovePhi(insn);
1868 }
1869
1870 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001871 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001872 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001873 // We should not see any back edges as they would have been removed by step (3).
1874 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1875
David Brazdil2d7352b2015-04-20 14:52:42 +01001876 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001877 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1878 // This block is the only normal-flow successor of the TryBoundary which
1879 // makes `predecessor` dead. Since DCE removes blocks in post order,
1880 // exception handlers of this TryBoundary were already visited and any
1881 // remaining handlers therefore must be live. We remove `predecessor` from
1882 // their list of predecessors.
1883 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1884 while (predecessor->GetSuccessors().size() > 1) {
1885 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1886 DCHECK(handler->IsCatchBlock());
1887 predecessor->RemoveSuccessor(handler);
1888 handler->RemovePredecessor(predecessor);
1889 }
1890 }
1891
David Brazdil2d7352b2015-04-20 14:52:42 +01001892 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001893 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1894 if (num_pred_successors == 1u) {
1895 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001896 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1897 // successor. Replace those with a HGoto.
1898 DCHECK(last_instruction->IsIf() ||
1899 last_instruction->IsPackedSwitch() ||
1900 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001901 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001902 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001903 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001904 // The predecessor has no remaining successors and therefore must be dead.
1905 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001906 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001907 predecessor->RemoveInstruction(last_instruction);
1908 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001909 // There are multiple successors left. The removed block might be a successor
1910 // of a PackedSwitch which will be completely removed (perhaps replaced with
1911 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1912 // case, leave `last_instruction` as is for now.
1913 DCHECK(last_instruction->IsPackedSwitch() ||
1914 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001915 }
David Brazdil46e2a392015-03-16 17:31:52 +00001916 }
Vladimir Marko60584552015-09-03 13:35:12 +00001917 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001918
David Brazdil9eeebf62016-03-24 11:18:15 +00001919 // (5) Remove the block from all loops it is included in. Skip the inner-most
1920 // loop if this is the loop header (see definition of `loop_update_start`)
1921 // because the loop header's predecessor list has been destroyed in step (4).
1922 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1923 HLoopInformation* loop_info = it.Current();
1924 loop_info->Remove(this);
1925 if (loop_info->IsBackEdge(*this)) {
1926 // If this was the last back edge of the loop, we deliberately leave the
1927 // loop in an inconsistent state and will fail GraphChecker unless the
1928 // entire loop is removed during the pass.
1929 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001930 }
1931 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001932
David Brazdil9eeebf62016-03-24 11:18:15 +00001933 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001934 dominator_->RemoveDominatedBlock(this);
1935 SetDominator(nullptr);
1936
David Brazdil9eeebf62016-03-24 11:18:15 +00001937 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001938 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001939 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001940}
1941
1942void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001943 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001944 DCHECK(ContainsElement(dominated_blocks_, other));
1945 DCHECK_EQ(GetSingleSuccessor(), other);
1946 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001947 DCHECK(other->GetPhis().IsEmpty());
1948
David Brazdil2d7352b2015-04-20 14:52:42 +01001949 // Move instructions from `other` to `this`.
1950 DCHECK(EndsWithControlFlowInstruction());
1951 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001952 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001953 other->instructions_.SetBlockOfInstructions(this);
1954 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001955
David Brazdil2d7352b2015-04-20 14:52:42 +01001956 // Remove `other` from the loops it is included in.
1957 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1958 HLoopInformation* loop_info = it.Current();
1959 loop_info->Remove(other);
1960 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001961 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001962 }
1963 }
1964
1965 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001966 successors_.clear();
1967 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001968 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001969 successor->ReplacePredecessor(other, this);
1970 }
1971
David Brazdil2d7352b2015-04-20 14:52:42 +01001972 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001973 RemoveDominatedBlock(other);
1974 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1975 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001976 dominated->SetDominator(this);
1977 }
Vladimir Marko60584552015-09-03 13:35:12 +00001978 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001979 other->dominator_ = nullptr;
1980
1981 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001982 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001983
1984 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001985 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001986 other->SetGraph(nullptr);
1987}
1988
1989void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1990 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001991 DCHECK(GetDominatedBlocks().empty());
1992 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001993 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001994 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001995 DCHECK(other->GetPhis().IsEmpty());
1996 DCHECK(!other->IsInLoop());
1997
1998 // Move instructions from `other` to `this`.
1999 instructions_.Add(other->GetInstructions());
2000 other->instructions_.SetBlockOfInstructions(this);
2001
2002 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002003 successors_.clear();
2004 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002005 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01002006 successor->ReplacePredecessor(other, this);
2007 }
2008
2009 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002010 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
2011 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002012 dominated->SetDominator(this);
2013 }
Vladimir Marko60584552015-09-03 13:35:12 +00002014 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002015 other->dominator_ = nullptr;
2016 other->graph_ = nullptr;
2017}
2018
2019void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002020 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002021 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002022 predecessor->ReplaceSuccessor(this, other);
2023 }
Vladimir Marko60584552015-09-03 13:35:12 +00002024 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002025 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002026 successor->ReplacePredecessor(this, other);
2027 }
Vladimir Marko60584552015-09-03 13:35:12 +00002028 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2029 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002030 }
2031 GetDominator()->ReplaceDominatedBlock(this, other);
2032 other->SetDominator(GetDominator());
2033 dominator_ = nullptr;
2034 graph_ = nullptr;
2035}
2036
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002037void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002038 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002039 DCHECK(block->GetSuccessors().empty());
2040 DCHECK(block->GetPredecessors().empty());
2041 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002042 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002043 DCHECK(block->GetInstructions().IsEmpty());
2044 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002045
David Brazdilc7af85d2015-05-26 12:05:55 +01002046 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002047 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002048 }
2049
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002050 RemoveElement(reverse_post_order_, block);
2051 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002052 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002053}
2054
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002055void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2056 HBasicBlock* reference,
2057 bool replace_if_back_edge) {
2058 if (block->IsLoopHeader()) {
2059 // Clear the information of which blocks are contained in that loop. Since the
2060 // information is stored as a bit vector based on block ids, we have to update
2061 // it, as those block ids were specific to the callee graph and we are now adding
2062 // these blocks to the caller graph.
2063 block->GetLoopInformation()->ClearAllBlocks();
2064 }
2065
2066 // If not already in a loop, update the loop information.
2067 if (!block->IsInLoop()) {
2068 block->SetLoopInformation(reference->GetLoopInformation());
2069 }
2070
2071 // If the block is in a loop, update all its outward loops.
2072 HLoopInformation* loop_info = block->GetLoopInformation();
2073 if (loop_info != nullptr) {
2074 for (HLoopInformationOutwardIterator loop_it(*block);
2075 !loop_it.Done();
2076 loop_it.Advance()) {
2077 loop_it.Current()->Add(block);
2078 }
2079 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2080 loop_info->ReplaceBackEdge(reference, block);
2081 }
2082 }
2083
2084 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2085 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2086 ? reference->GetTryCatchInformation()
2087 : nullptr;
2088 block->SetTryCatchInformation(try_catch_info);
2089}
2090
Calin Juravle2e768302015-07-28 14:41:11 +00002091HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002092 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002093 // Update the environments in this graph to have the invoke's environment
2094 // as parent.
2095 {
2096 HReversePostOrderIterator it(*this);
2097 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
2098 for (; !it.Done(); it.Advance()) {
2099 HBasicBlock* block = it.Current();
2100 for (HInstructionIterator instr_it(block->GetInstructions());
2101 !instr_it.Done();
2102 instr_it.Advance()) {
2103 HInstruction* current = instr_it.Current();
2104 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002105 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002106 current->GetEnvironment()->SetAndCopyParentChain(
2107 outer_graph->GetArena(), invoke->GetEnvironment());
2108 }
2109 }
2110 }
2111 }
2112 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
2113 if (HasBoundsChecks()) {
2114 outer_graph->SetHasBoundsChecks(true);
2115 }
2116
Calin Juravle2e768302015-07-28 14:41:11 +00002117 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002118 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002119 // Simple case of an entry block, a body block, and an exit block.
2120 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002121 HBasicBlock* body = GetBlocks()[1];
2122 DCHECK(GetBlocks()[0]->IsEntryBlock());
2123 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002124 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002125 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002126 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002127
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002128 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2129 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002130 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002131
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002132 // Replace the invoke with the return value of the inlined graph.
2133 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002134 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002135 } else {
2136 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002137 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002138
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002139 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002140 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002141 // Need to inline multiple blocks. We split `invoke`'s block
2142 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002143 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002144 // with the second half.
2145 ArenaAllocator* allocator = outer_graph->GetArena();
2146 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002147 // Note that we split before the invoke only to simplify polymorphic inlining.
2148 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002149
Vladimir Markoec7802a2015-10-01 20:57:57 +01002150 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002151 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002152 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002153 exit_block_->ReplaceWith(to);
2154
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002155 // Update the meta information surrounding blocks:
2156 // (1) the graph they are now in,
2157 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002158 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002159 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002160 // Note that we do not need to update catch phi inputs because they
2161 // correspond to the register file of the outer method which the inlinee
2162 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002163
2164 // We don't add the entry block, the exit block, and the first block, which
2165 // has been merged with `at`.
2166 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2167
2168 // We add the `to` block.
2169 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002170 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002171 + kNumberOfNewBlocksInCaller;
2172
2173 // Find the location of `at` in the outer graph's reverse post order. The new
2174 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002175 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002176 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2177
David Brazdil95177982015-10-30 12:56:58 -05002178 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2179 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002180 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2181 HBasicBlock* current = it.Current();
2182 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002183 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002184 DCHECK(current->GetGraph() == this);
2185 current->SetGraph(outer_graph);
2186 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002187 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002188 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002189 }
2190 }
2191
David Brazdil95177982015-10-30 12:56:58 -05002192 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002193 to->SetGraph(outer_graph);
2194 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002195 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002196 // Only `to` can become a back edge, as the inlined blocks
2197 // are predecessors of `to`.
2198 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002199
David Brazdil3f523062016-02-29 16:53:33 +00002200 // Update all predecessors of the exit block (now the `to` block)
2201 // to not `HReturn` but `HGoto` instead.
2202 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2203 if (to->GetPredecessors().size() == 1) {
2204 HBasicBlock* predecessor = to->GetPredecessors()[0];
2205 HInstruction* last = predecessor->GetLastInstruction();
2206 if (!returns_void) {
2207 return_value = last->InputAt(0);
2208 }
2209 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2210 predecessor->RemoveInstruction(last);
2211 } else {
2212 if (!returns_void) {
2213 // There will be multiple returns.
2214 return_value = new (allocator) HPhi(
2215 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2216 to->AddPhi(return_value->AsPhi());
2217 }
2218 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2219 HInstruction* last = predecessor->GetLastInstruction();
2220 if (!returns_void) {
2221 DCHECK(last->IsReturn());
2222 return_value->AsPhi()->AddInput(last->InputAt(0));
2223 }
2224 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2225 predecessor->RemoveInstruction(last);
2226 }
2227 }
2228 }
David Brazdil05144f42015-04-16 15:18:00 +01002229
2230 // Walk over the entry block and:
2231 // - Move constants from the entry block to the outer_graph's entry block,
2232 // - Replace HParameterValue instructions with their real value.
2233 // - Remove suspend checks, that hold an environment.
2234 // We must do this after the other blocks have been inlined, otherwise ids of
2235 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002236 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002237 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2238 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002239 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002240 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002241 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002242 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002243 replacement = outer_graph->GetIntConstant(
2244 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002245 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002246 replacement = outer_graph->GetLongConstant(
2247 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002248 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002249 replacement = outer_graph->GetFloatConstant(
2250 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002251 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002252 replacement = outer_graph->GetDoubleConstant(
2253 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002254 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002255 if (kIsDebugBuild
2256 && invoke->IsInvokeStaticOrDirect()
2257 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2258 // Ensure we do not use the last input of `invoke`, as it
2259 // contains a clinit check which is not an actual argument.
2260 size_t last_input_index = invoke->InputCount() - 1;
2261 DCHECK(parameter_index != last_input_index);
2262 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002263 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002264 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002265 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002266 } else {
2267 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2268 entry_block_->RemoveInstruction(current);
2269 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002270 if (replacement != nullptr) {
2271 current->ReplaceWith(replacement);
2272 // If the current is the return value then we need to update the latter.
2273 if (current == return_value) {
2274 DCHECK_EQ(entry_block_, return_value->GetBlock());
2275 return_value = replacement;
2276 }
2277 }
2278 }
2279
Calin Juravle2e768302015-07-28 14:41:11 +00002280 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002281}
2282
Mingyao Yang3584bce2015-05-19 16:01:59 -07002283/*
2284 * Loop will be transformed to:
2285 * old_pre_header
2286 * |
2287 * if_block
2288 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002289 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002290 * \ /
2291 * new_pre_header
2292 * |
2293 * header
2294 */
2295void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2296 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002297 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002298
Aart Bik3fc7f352015-11-20 22:03:03 -08002299 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002300 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002301 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2302 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002303 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2304 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002305 AddBlock(true_block);
2306 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002307 AddBlock(new_pre_header);
2308
Aart Bik3fc7f352015-11-20 22:03:03 -08002309 header->ReplacePredecessor(old_pre_header, new_pre_header);
2310 old_pre_header->successors_.clear();
2311 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002312
Aart Bik3fc7f352015-11-20 22:03:03 -08002313 old_pre_header->AddSuccessor(if_block);
2314 if_block->AddSuccessor(true_block); // True successor
2315 if_block->AddSuccessor(false_block); // False successor
2316 true_block->AddSuccessor(new_pre_header);
2317 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002318
Aart Bik3fc7f352015-11-20 22:03:03 -08002319 old_pre_header->dominated_blocks_.push_back(if_block);
2320 if_block->SetDominator(old_pre_header);
2321 if_block->dominated_blocks_.push_back(true_block);
2322 true_block->SetDominator(if_block);
2323 if_block->dominated_blocks_.push_back(false_block);
2324 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002325 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002326 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002327 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002328 header->SetDominator(new_pre_header);
2329
Aart Bik3fc7f352015-11-20 22:03:03 -08002330 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002331 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002332 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002333 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002334 reverse_post_order_[index_of_header++] = true_block;
2335 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002336 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002337
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002338 // The pre_header can never be a back edge of a loop.
2339 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2340 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2341 UpdateLoopAndTryInformationOfNewBlock(
2342 if_block, old_pre_header, /* replace_if_back_edge */ false);
2343 UpdateLoopAndTryInformationOfNewBlock(
2344 true_block, old_pre_header, /* replace_if_back_edge */ false);
2345 UpdateLoopAndTryInformationOfNewBlock(
2346 false_block, old_pre_header, /* replace_if_back_edge */ false);
2347 UpdateLoopAndTryInformationOfNewBlock(
2348 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002349}
2350
David Brazdilf5552582015-12-27 13:36:12 +00002351static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002352 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002353 if (rti.IsValid()) {
2354 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2355 << " upper_bound_rti: " << upper_bound_rti
2356 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002357 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2358 << " upper_bound_rti: " << upper_bound_rti
2359 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002360 }
2361}
2362
Calin Juravle2e768302015-07-28 14:41:11 +00002363void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2364 if (kIsDebugBuild) {
2365 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2366 ScopedObjectAccess soa(Thread::Current());
2367 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2368 if (IsBoundType()) {
2369 // Having the test here spares us from making the method virtual just for
2370 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002371 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002372 }
2373 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002374 reference_type_handle_ = rti.GetTypeHandle();
2375 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002376}
2377
David Brazdilf5552582015-12-27 13:36:12 +00002378void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2379 if (kIsDebugBuild) {
2380 ScopedObjectAccess soa(Thread::Current());
2381 DCHECK(upper_bound.IsValid());
2382 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2383 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2384 }
2385 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002386 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002387}
2388
Vladimir Markoa1de9182016-02-25 11:37:38 +00002389ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002390 if (kIsDebugBuild) {
2391 ScopedObjectAccess soa(Thread::Current());
2392 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002393 if (!is_exact) {
2394 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2395 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2396 }
Calin Juravle2e768302015-07-28 14:41:11 +00002397 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002398 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002399}
2400
Calin Juravleacf735c2015-02-12 15:25:22 +00002401std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2402 ScopedObjectAccess soa(Thread::Current());
2403 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002404 << " is_valid=" << rhs.IsValid()
2405 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002406 << " is_exact=" << rhs.IsExact()
2407 << " ]";
2408 return os;
2409}
2410
Mark Mendellc4701932015-04-10 13:18:51 -04002411bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2412 // For now, assume that instructions in different blocks may use the
2413 // environment.
2414 // TODO: Use the control flow to decide if this is true.
2415 if (GetBlock() != other->GetBlock()) {
2416 return true;
2417 }
2418
2419 // We know that we are in the same block. Walk from 'this' to 'other',
2420 // checking to see if there is any instruction with an environment.
2421 HInstruction* current = this;
2422 for (; current != other && current != nullptr; current = current->GetNext()) {
2423 // This is a conservative check, as the instruction result may not be in
2424 // the referenced environment.
2425 if (current->HasEnvironment()) {
2426 return true;
2427 }
2428 }
2429
2430 // We should have been called with 'this' before 'other' in the block.
2431 // Just confirm this.
2432 DCHECK(current != nullptr);
2433 return false;
2434}
2435
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002436void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002437 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2438 IntrinsicSideEffects side_effects,
2439 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002440 intrinsic_ = intrinsic;
2441 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002442
Aart Bik5d75afe2015-12-14 11:57:01 -08002443 // Adjust method's side effects from intrinsic table.
2444 switch (side_effects) {
2445 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2446 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2447 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2448 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2449 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002450
2451 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2452 opt.SetDoesNotNeedDexCache();
2453 opt.SetDoesNotNeedEnvironment();
2454 } else {
2455 // If we need an environment, that means there will be a call, which can trigger GC.
2456 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2457 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002458 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002459 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002460}
2461
David Brazdil6de19382016-01-08 17:37:10 +00002462bool HNewInstance::IsStringAlloc() const {
2463 ScopedObjectAccess soa(Thread::Current());
2464 return GetReferenceTypeInfo().IsStringClass();
2465}
2466
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002467bool HInvoke::NeedsEnvironment() const {
2468 if (!IsIntrinsic()) {
2469 return true;
2470 }
2471 IntrinsicOptimizations opt(*this);
2472 return !opt.GetDoesNotNeedEnvironment();
2473}
2474
Vladimir Markodc151b22015-10-15 18:02:30 +01002475bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2476 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002477 return false;
2478 }
2479 if (!IsIntrinsic()) {
2480 return true;
2481 }
2482 IntrinsicOptimizations opt(*this);
2483 return !opt.GetDoesNotNeedDexCache();
2484}
2485
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002486void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2487 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2488 input->AddUseAt(this, index);
2489 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002490 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
2491 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
2492 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002493 }
2494}
2495
Vladimir Markob554b5a2015-11-06 12:57:55 +00002496void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2497 RemoveAsUserOfInput(index);
2498 inputs_.erase(inputs_.begin() + index);
2499 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
Vladimir Marko372f10e2016-05-17 16:30:10 +01002500 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
2501 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
2502 inputs_[i].GetUseNode()->SetIndex(i);
Vladimir Markob554b5a2015-11-06 12:57:55 +00002503 }
2504}
2505
Vladimir Markof64242a2015-12-01 14:58:23 +00002506std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2507 switch (rhs) {
2508 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2509 return os << "string_init";
2510 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2511 return os << "recursive";
2512 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2513 return os << "direct";
2514 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2515 return os << "direct_fixup";
2516 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2517 return os << "dex_cache_pc_relative";
2518 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2519 return os << "dex_cache_via_method";
2520 default:
2521 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2522 UNREACHABLE();
2523 }
2524}
2525
Vladimir Markofbb184a2015-11-13 14:47:00 +00002526std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2527 switch (rhs) {
2528 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2529 return os << "explicit";
2530 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2531 return os << "implicit";
2532 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2533 return os << "none";
2534 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002535 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2536 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002537 }
2538}
2539
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002540bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2541 const HLoadClass* other_load_class = other->AsLoadClass();
2542 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2543 // names rather than type indexes. However, we shall also have to re-think the hash code.
2544 if (type_index_ != other_load_class->type_index_ ||
2545 GetPackedFields() != other_load_class->GetPackedFields()) {
2546 return false;
2547 }
2548 LoadKind load_kind = GetLoadKind();
2549 if (HasAddress(load_kind)) {
2550 return GetAddress() == other_load_class->GetAddress();
2551 } else if (HasTypeReference(load_kind)) {
2552 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
2553 } else {
2554 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2555 // If the type indexes and dex files are the same, dex cache element offsets
2556 // must also be the same, so we don't need to compare them.
2557 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
2558 }
2559}
2560
2561void HLoadClass::SetLoadKindInternal(LoadKind load_kind) {
2562 // Once sharpened, the load kind should not be changed again.
2563 // Also, kReferrersClass should never be overwritten.
2564 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2565 SetPackedField<LoadKindField>(load_kind);
2566
2567 if (load_kind != LoadKind::kDexCacheViaMethod) {
2568 RemoveAsUserOfInput(0u);
2569 SetRawInputAt(0u, nullptr);
2570 }
2571 if (!NeedsEnvironment()) {
2572 RemoveEnvironment();
2573 SetSideEffects(SideEffects::None());
2574 }
2575}
2576
2577std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2578 switch (rhs) {
2579 case HLoadClass::LoadKind::kReferrersClass:
2580 return os << "ReferrersClass";
2581 case HLoadClass::LoadKind::kBootImageLinkTimeAddress:
2582 return os << "BootImageLinkTimeAddress";
2583 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2584 return os << "BootImageLinkTimePcRelative";
2585 case HLoadClass::LoadKind::kBootImageAddress:
2586 return os << "BootImageAddress";
2587 case HLoadClass::LoadKind::kDexCacheAddress:
2588 return os << "DexCacheAddress";
2589 case HLoadClass::LoadKind::kDexCachePcRelative:
2590 return os << "DexCachePcRelative";
2591 case HLoadClass::LoadKind::kDexCacheViaMethod:
2592 return os << "DexCacheViaMethod";
2593 default:
2594 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2595 UNREACHABLE();
2596 }
2597}
2598
Vladimir Marko372f10e2016-05-17 16:30:10 +01002599bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2600 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002601 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2602 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002603 if (string_index_ != other_load_string->string_index_ ||
2604 GetPackedFields() != other_load_string->GetPackedFields()) {
2605 return false;
2606 }
2607 LoadKind load_kind = GetLoadKind();
2608 if (HasAddress(load_kind)) {
2609 return GetAddress() == other_load_string->GetAddress();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002610 } else {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002611 DCHECK(HasStringReference(load_kind)) << load_kind;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002612 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2613 }
2614}
2615
2616void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2617 // Once sharpened, the load kind should not be changed again.
2618 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2619 SetPackedField<LoadKindField>(load_kind);
2620
2621 if (load_kind != LoadKind::kDexCacheViaMethod) {
2622 RemoveAsUserOfInput(0u);
2623 SetRawInputAt(0u, nullptr);
2624 }
2625 if (!NeedsEnvironment()) {
2626 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002627 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002628 }
2629}
2630
2631std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2632 switch (rhs) {
2633 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2634 return os << "BootImageLinkTimeAddress";
2635 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2636 return os << "BootImageLinkTimePcRelative";
2637 case HLoadString::LoadKind::kBootImageAddress:
2638 return os << "BootImageAddress";
2639 case HLoadString::LoadKind::kDexCacheAddress:
2640 return os << "DexCacheAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002641 case HLoadString::LoadKind::kBssEntry:
2642 return os << "BssEntry";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002643 case HLoadString::LoadKind::kDexCacheViaMethod:
2644 return os << "DexCacheViaMethod";
2645 default:
2646 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2647 UNREACHABLE();
2648 }
2649}
2650
Mark Mendellc4701932015-04-10 13:18:51 -04002651void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002652 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2653 HEnvironment* user = use.GetUser();
2654 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002655 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002656 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002657}
2658
Roland Levillainc9b21f82016-03-23 16:36:59 +00002659// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002660HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2661 ArenaAllocator* allocator = GetArena();
2662
2663 if (cond->IsCondition() &&
2664 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2665 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2666 HInstruction* lhs = cond->InputAt(0);
2667 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002668 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002669 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2670 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2671 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2672 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2673 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2674 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2675 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2676 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2677 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2678 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2679 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002680 default:
2681 LOG(FATAL) << "Unexpected condition";
2682 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002683 }
2684 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2685 return replacement;
2686 } else if (cond->IsIntConstant()) {
2687 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002688 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002689 return GetIntConstant(1);
2690 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002691 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002692 return GetIntConstant(0);
2693 }
2694 } else {
2695 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2696 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2697 return replacement;
2698 }
2699}
2700
Roland Levillainc9285912015-12-18 10:38:42 +00002701std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2702 os << "["
2703 << " source=" << rhs.GetSource()
2704 << " destination=" << rhs.GetDestination()
2705 << " type=" << rhs.GetType()
2706 << " instruction=";
2707 if (rhs.GetInstruction() != nullptr) {
2708 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2709 } else {
2710 os << "null";
2711 }
2712 os << " ]";
2713 return os;
2714}
2715
Roland Levillain86503782016-02-11 19:07:30 +00002716std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2717 switch (rhs) {
2718 case TypeCheckKind::kUnresolvedCheck:
2719 return os << "unresolved_check";
2720 case TypeCheckKind::kExactCheck:
2721 return os << "exact_check";
2722 case TypeCheckKind::kClassHierarchyCheck:
2723 return os << "class_hierarchy_check";
2724 case TypeCheckKind::kAbstractClassCheck:
2725 return os << "abstract_class_check";
2726 case TypeCheckKind::kInterfaceCheck:
2727 return os << "interface_check";
2728 case TypeCheckKind::kArrayObjectCheck:
2729 return os << "array_object_check";
2730 case TypeCheckKind::kArrayCheck:
2731 return os << "array_check";
2732 default:
2733 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2734 UNREACHABLE();
2735 }
2736}
2737
Andreas Gampe26de38b2016-07-27 17:53:11 -07002738std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2739 switch (kind) {
2740 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002741 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002742 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002743 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002744 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002745 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002746 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002747 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002748 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002749 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002750
2751 default:
2752 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2753 UNREACHABLE();
2754 }
2755}
2756
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002757} // namespace art