blob: c636eda522db650b2d6ffc7cb26318925944ec25 [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
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Vladimir Markocac5a7e2016-02-22 10:39:50 +000093static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010094 for (HEnvironment* environment = instruction->GetEnvironment();
95 environment != nullptr;
96 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000097 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000098 if (environment->GetInstructionAt(i) != nullptr) {
99 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000100 }
101 }
102 }
103}
104
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000105static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100106 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000107 RemoveEnvironmentUses(instruction);
108}
109
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100113 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000114 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100115 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
117 RemoveAsUser(it.Current());
118 }
119 }
120 }
121}
122
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100123void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100124 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000125 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100126 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000127 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100128 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000129 for (HBasicBlock* successor : block->GetSuccessors()) {
130 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000131 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100132 // Remove the block from the list of blocks, so that further analyses
133 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100134 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600135 if (block->IsExitBlock()) {
136 SetExitBlock(nullptr);
137 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000138 // Mark the block as removed. This is used by the HGraphBuilder to discard
139 // the block as a branch target.
140 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 }
142 }
143}
144
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000145GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000146 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147
David Brazdil86ea7ee2016-02-16 09:26:07 +0000148 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000149 FindBackEdges(&visited);
150
David Brazdil86ea7ee2016-02-16 09:26:07 +0000151 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000152 // the initial DFS as users from other instructions, so that
153 // users can be safely removed before uses later.
154 RemoveInstructionsAsUsersFromDeadBlocks(visited);
155
David Brazdil86ea7ee2016-02-16 09:26:07 +0000156 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000158 // predecessors list of live blocks.
159 RemoveDeadBlocks(visited);
160
David Brazdil86ea7ee2016-02-16 09:26:07 +0000161 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 // dominators and the reverse post order.
163 SimplifyCFG();
164
David Brazdil86ea7ee2016-02-16 09:26:07 +0000165 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100166 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000169 // set the loop information on each block.
170 GraphAnalysisResult result = AnalyzeLoops();
171 if (result != kAnalysisSuccess) {
172 return result;
173 }
174
David Brazdil86ea7ee2016-02-16 09:26:07 +0000175 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000176 // which needs the information to build catch block phis from values of
177 // locals at throwing instructions inside try blocks.
178 ComputeTryBlockInformation();
179
180 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100181}
182
183void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100184 for (HBasicBlock* block : GetReversePostOrder()) {
185 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100186 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100187 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100188}
189
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000190void HGraph::ClearLoopInformation() {
191 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100192 for (HBasicBlock* block : GetReversePostOrder()) {
193 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000194 }
195}
196
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100197void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000198 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100199 dominator_ = nullptr;
200}
201
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000202HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
203 HInstruction* instruction = GetFirstInstruction();
204 while (instruction->IsParallelMove()) {
205 instruction = instruction->GetNext();
206 }
207 return instruction;
208}
209
David Brazdil3f4a5222016-05-06 12:46:21 +0100210static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
211 DCHECK(ContainsElement(block->GetSuccessors(), successor));
212
213 HBasicBlock* old_dominator = successor->GetDominator();
214 HBasicBlock* new_dominator =
215 (old_dominator == nullptr) ? block
216 : CommonDominator::ForPair(old_dominator, block);
217
218 if (old_dominator == new_dominator) {
219 return false;
220 } else {
221 successor->SetDominator(new_dominator);
222 return true;
223 }
224}
225
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 DCHECK(reverse_post_order_.empty());
228 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100229 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100230
231 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100232 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100233 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100234 ArenaVector<size_t> successors_visited(blocks_.size(),
235 0u,
236 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100238 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100239 constexpr size_t kDefaultWorklistSize = 8;
240 worklist.reserve(kDefaultWorklistSize);
241 worklist.push_back(entry_block_);
242
243 while (!worklist.empty()) {
244 HBasicBlock* current = worklist.back();
245 uint32_t current_id = current->GetBlockId();
246 if (successors_visited[current_id] == current->GetSuccessors().size()) {
247 worklist.pop_back();
248 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100249 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100250 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100251
252 // Once all the forward edges have been visited, we know the immediate
253 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100254 if (++visits[successor->GetBlockId()] ==
255 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100256 reverse_post_order_.push_back(successor);
257 worklist.push_back(successor);
258 }
259 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000260 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000261
David Brazdil3f4a5222016-05-06 12:46:21 +0100262 // Check if the graph has back edges not dominated by their respective headers.
263 // If so, we need to update the dominators of those headers and recursively of
264 // their successors. We do that with a fix-point iteration over all blocks.
265 // The algorithm is guaranteed to terminate because it loops only if the sum
266 // of all dominator chains has decreased in the current iteration.
267 bool must_run_fix_point = false;
268 for (HBasicBlock* block : blocks_) {
269 if (block != nullptr &&
270 block->IsLoopHeader() &&
271 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
272 must_run_fix_point = true;
273 break;
274 }
275 }
276 if (must_run_fix_point) {
277 bool update_occurred = true;
278 while (update_occurred) {
279 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100280 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100281 for (HBasicBlock* successor : block->GetSuccessors()) {
282 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
283 }
284 }
285 }
286 }
287
288 // Make sure that there are no remaining blocks whose dominator information
289 // needs to be updated.
290 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100291 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 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.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100300 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301 if (!block->IsEntryBlock()) {
302 block->GetDominator()->AddDominatedBlock(block);
303 }
304 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000305}
306
David Brazdilfc6a86a2015-06-26 10:33:45 +0000307HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000308 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
309 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000310 // Use `InsertBetween` to ensure the predecessor index and successor index of
311 // `block` and `successor` are preserved.
312 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000313 return new_block;
314}
315
316void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
317 // Insert a new node between `block` and `successor` to split the
318 // critical edge.
319 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600320 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100321 if (successor->IsLoopHeader()) {
322 // If we split at a back edge boundary, make the new block the back edge.
323 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000324 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 info->RemoveBackEdge(block);
326 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100327 }
328 }
329}
330
Artem Serovc73ee372017-07-31 15:08:40 +0100331// Reorder phi inputs to match reordering of the block's predecessors.
332static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
333 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
334 HPhi* phi = it.Current()->AsPhi();
335 HInstruction* first_instr = phi->InputAt(first);
336 HInstruction* second_instr = phi->InputAt(second);
337 phi->ReplaceInput(first_instr, second);
338 phi->ReplaceInput(second_instr, first);
339 }
340}
341
342// Make sure that the first predecessor of a loop header is the incoming block.
343void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
344 DCHECK(header->IsLoopHeader());
345 HLoopInformation* info = header->GetLoopInformation();
346 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
347 HBasicBlock* to_swap = header->GetPredecessors()[0];
348 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
349 HBasicBlock* predecessor = header->GetPredecessors()[pred];
350 if (!info->IsBackEdge(*predecessor)) {
351 header->predecessors_[pred] = to_swap;
352 header->predecessors_[0] = predecessor;
353 FixPhisAfterPredecessorsReodering(header, 0, pred);
354 break;
355 }
356 }
357 }
358}
359
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100360void HGraph::SimplifyLoop(HBasicBlock* header) {
361 HLoopInformation* info = header->GetLoopInformation();
362
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100363 // Make sure the loop has only one pre header. This simplifies SSA building by having
364 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000365 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
366 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000367 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000368 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100369 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100370 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600371 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100372
Vladimir Marko60584552015-09-03 13:35:12 +0000373 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100374 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100375 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100376 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100377 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100378 }
379 }
380 pre_header->AddSuccessor(header);
381 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100382
Artem Serovc73ee372017-07-31 15:08:40 +0100383 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100384
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100385 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000386 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
387 // Called from DeadBlockElimination. Update SuspendCheck pointer.
388 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100389 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100390}
391
David Brazdilffee3d32015-07-06 11:48:53 +0100392void HGraph::ComputeTryBlockInformation() {
393 // Iterate in reverse post order to propagate try membership information from
394 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100395 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100396 if (block->IsEntryBlock() || block->IsCatchBlock()) {
397 // Catch blocks after simplification have only exceptional predecessors
398 // and hence are never in tries.
399 continue;
400 }
401
402 // Infer try membership from the first predecessor. Having simplified loops,
403 // the first predecessor can never be a back edge and therefore it must have
404 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100405 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100406 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100407 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000408 if (try_entry != nullptr &&
409 (block->GetTryCatchInformation() == nullptr ||
410 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
411 // We are either setting try block membership for the first time or it
412 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100413 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
414 }
David Brazdilffee3d32015-07-06 11:48:53 +0100415 }
416}
417
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100418void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000419// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000421 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100422 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
423 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
424 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
425 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100426 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000427 if (block->GetSuccessors().size() > 1) {
428 // Only split normal-flow edges. We cannot split exceptional edges as they
429 // are synthesized (approximate real control flow), and we do not need to
430 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000431 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
432 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
433 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100434 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000435 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000436 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
437 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000438 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000439 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100440 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000441 // SplitCriticalEdge could have invalidated the `normal_successors`
442 // ArrayRef. We must re-acquire it.
443 normal_successors = block->GetNormalSuccessors();
444 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
445 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446 }
447 }
448 }
449 if (block->IsLoopHeader()) {
450 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000451 } else if (!block->IsEntryBlock() &&
452 block->GetFirstInstruction() != nullptr &&
453 block->GetFirstInstruction()->IsSuspendCheck()) {
454 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000455 // a loop got dismantled. Just remove the suspend check.
456 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100457 }
458 }
459}
460
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000461GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100462 // We iterate post order to ensure we visit inner loops before outer loops.
463 // `PopulateRecursive` needs this guarantee to know whether a natural loop
464 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100465 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100466 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100467 if (block->IsCatchBlock()) {
468 // TODO: Dealing with exceptional back edges could be tricky because
469 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000470 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100471 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000472 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100473 }
474 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000475 return kAnalysisSuccess;
476}
477
478void HLoopInformation::Dump(std::ostream& os) {
479 os << "header: " << header_->GetBlockId() << std::endl;
480 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
481 for (HBasicBlock* block : back_edges_) {
482 os << "back edge: " << block->GetBlockId() << std::endl;
483 }
484 for (HBasicBlock* block : header_->GetPredecessors()) {
485 os << "predecessor: " << block->GetBlockId() << std::endl;
486 }
487 for (uint32_t idx : blocks_.Indexes()) {
488 os << " in loop: " << idx << std::endl;
489 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100490}
491
David Brazdil8d5b8b22015-03-24 10:51:52 +0000492void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000493 // New constants are inserted before the SuspendCheck at the bottom of the
494 // entry block. Note that this method can be called from the graph builder and
495 // the entry block therefore may not end with SuspendCheck->Goto yet.
496 HInstruction* insert_before = nullptr;
497
498 HInstruction* gota = entry_block_->GetLastInstruction();
499 if (gota != nullptr && gota->IsGoto()) {
500 HInstruction* suspend_check = gota->GetPrevious();
501 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
502 insert_before = suspend_check;
503 } else {
504 insert_before = gota;
505 }
506 }
507
508 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000509 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000510 } else {
511 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000512 }
513}
514
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600515HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100516 // For simplicity, don't bother reviving the cached null constant if it is
517 // not null and not in a block. Otherwise, we need to clear the instruction
518 // id and/or any invariants the graph is assuming when adding new instructions.
519 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600520 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000521 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000522 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000523 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000524 if (kIsDebugBuild) {
525 ScopedObjectAccess soa(Thread::Current());
526 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
527 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000528 return cached_null_constant_;
529}
530
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100531HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100532 // For simplicity, don't bother reviving the cached current method if it is
533 // not null and not in a block. Otherwise, we need to clear the instruction
534 // id and/or any invariants the graph is assuming when adding new instructions.
535 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700536 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600537 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
538 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100539 if (entry_block_->GetFirstInstruction() == nullptr) {
540 entry_block_->AddInstruction(cached_current_method_);
541 } else {
542 entry_block_->InsertInstructionBefore(
543 cached_current_method_, entry_block_->GetFirstInstruction());
544 }
545 }
546 return cached_current_method_;
547}
548
Igor Murashkind01745e2017-04-05 16:40:31 -0700549const char* HGraph::GetMethodName() const {
550 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
551 return dex_file_.GetMethodName(method_id);
552}
553
554std::string HGraph::PrettyMethod(bool with_signature) const {
555 return dex_file_.PrettyMethod(method_idx_, with_signature);
556}
557
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600558HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000559 switch (type) {
560 case Primitive::Type::kPrimBoolean:
561 DCHECK(IsUint<1>(value));
562 FALLTHROUGH_INTENDED;
563 case Primitive::Type::kPrimByte:
564 case Primitive::Type::kPrimChar:
565 case Primitive::Type::kPrimShort:
566 case Primitive::Type::kPrimInt:
567 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600568 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000569
570 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600571 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000572
573 default:
574 LOG(FATAL) << "Unsupported constant type";
575 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000576 }
David Brazdil46e2a392015-03-16 17:31:52 +0000577}
578
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000579void HGraph::CacheFloatConstant(HFloatConstant* constant) {
580 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
581 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
582 cached_float_constants_.Overwrite(value, constant);
583}
584
585void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
586 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
587 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
588 cached_double_constants_.Overwrite(value, constant);
589}
590
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000591void HLoopInformation::Add(HBasicBlock* block) {
592 blocks_.SetBit(block->GetBlockId());
593}
594
David Brazdil46e2a392015-03-16 17:31:52 +0000595void HLoopInformation::Remove(HBasicBlock* block) {
596 blocks_.ClearBit(block->GetBlockId());
597}
598
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100599void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
600 if (blocks_.IsBitSet(block->GetBlockId())) {
601 return;
602 }
603
604 blocks_.SetBit(block->GetBlockId());
605 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100606 if (block->IsLoopHeader()) {
607 // We're visiting loops in post-order, so inner loops must have been
608 // populated already.
609 DCHECK(block->GetLoopInformation()->IsPopulated());
610 if (block->GetLoopInformation()->IsIrreducible()) {
611 contains_irreducible_loop_ = true;
612 }
613 }
Vladimir Marko60584552015-09-03 13:35:12 +0000614 for (HBasicBlock* predecessor : block->GetPredecessors()) {
615 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100616 }
617}
618
David Brazdilc2e8af92016-04-05 17:15:19 +0100619void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
620 size_t block_id = block->GetBlockId();
621
622 // If `block` is in `finalized`, we know its membership in the loop has been
623 // decided and it does not need to be revisited.
624 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000625 return;
626 }
627
David Brazdilc2e8af92016-04-05 17:15:19 +0100628 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000629 if (block->IsLoopHeader()) {
630 // If we hit a loop header in an irreducible loop, we first check if the
631 // pre header of that loop belongs to the currently analyzed loop. If it does,
632 // then we visit the back edges.
633 // Note that we cannot use GetPreHeader, as the loop may have not been populated
634 // yet.
635 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100636 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000638 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100639 blocks_.SetBit(block_id);
640 finalized->SetBit(block_id);
641 is_finalized = true;
642
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000643 HLoopInformation* info = block->GetLoopInformation();
644 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100645 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 }
647 }
648 } else {
649 // Visit all predecessors. If one predecessor is part of the loop, this
650 // block is also part of this loop.
651 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100652 PopulateIrreducibleRecursive(predecessor, finalized);
653 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000654 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100655 blocks_.SetBit(block_id);
656 finalized->SetBit(block_id);
657 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000658 }
659 }
660 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100661
662 // All predecessors have been recursively visited. Mark finalized if not marked yet.
663 if (!is_finalized) {
664 finalized->SetBit(block_id);
665 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000666}
667
668void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100669 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000670 // Populate this loop: starting with the back edge, recursively add predecessors
671 // that are not already part of that loop. Set the header as part of the loop
672 // to end the recursion.
673 // This is a recursive implementation of the algorithm described in
674 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100675 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000676 blocks_.SetBit(header_->GetBlockId());
677 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100678
David Brazdil3f4a5222016-05-06 12:46:21 +0100679 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100680
681 if (is_irreducible_loop) {
682 ArenaBitVector visited(graph->GetArena(),
683 graph->GetBlocks().size(),
684 /* expandable */ false,
685 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100686 // Stop marking blocks at the loop header.
687 visited.SetBit(header_->GetBlockId());
688
David Brazdilc2e8af92016-04-05 17:15:19 +0100689 for (HBasicBlock* back_edge : GetBackEdges()) {
690 PopulateIrreducibleRecursive(back_edge, &visited);
691 }
692 } else {
693 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000694 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100695 }
David Brazdila4b8c212015-05-07 09:59:30 +0100696 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100697
Vladimir Markofd66c502016-04-18 15:37:01 +0100698 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
699 // When compiling in OSR mode, all loops in the compiled method may be entered
700 // from the interpreter. We treat this OSR entry point just like an extra entry
701 // to an irreducible loop, so we need to mark the method's loops as irreducible.
702 // This does not apply to inlined loops which do not act as OSR entry points.
703 if (suspend_check_ == nullptr) {
704 // Just building the graph in OSR mode, this loop is not inlined. We never build an
705 // inner graph in OSR mode as we can do OSR transition only from the outer method.
706 is_irreducible_loop = true;
707 } else {
708 // Look at the suspend check's environment to determine if the loop was inlined.
709 DCHECK(suspend_check_->HasEnvironment());
710 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
711 is_irreducible_loop = true;
712 }
713 }
714 }
715 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100716 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100717 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100718 graph->SetHasIrreducibleLoops(true);
719 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800720 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100721}
722
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100723HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000724 HBasicBlock* block = header_->GetPredecessors()[0];
725 DCHECK(irreducible_ || (block == header_->GetDominator()));
726 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100727}
728
729bool HLoopInformation::Contains(const HBasicBlock& block) const {
730 return blocks_.IsBitSet(block.GetBlockId());
731}
732
733bool HLoopInformation::IsIn(const HLoopInformation& other) const {
734 return other.blocks_.IsBitSet(header_->GetBlockId());
735}
736
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800737bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
738 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700739}
740
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100741size_t HLoopInformation::GetLifetimeEnd() const {
742 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100743 for (HBasicBlock* back_edge : GetBackEdges()) {
744 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100745 }
746 return last_position;
747}
748
David Brazdil3f4a5222016-05-06 12:46:21 +0100749bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
750 for (HBasicBlock* back_edge : GetBackEdges()) {
751 DCHECK(back_edge->GetDominator() != nullptr);
752 if (!header_->Dominates(back_edge)) {
753 return true;
754 }
755 }
756 return false;
757}
758
Anton Shaminf89381f2016-05-16 16:44:13 +0600759bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
760 for (HBasicBlock* back_edge : GetBackEdges()) {
761 if (!block->Dominates(back_edge)) {
762 return false;
763 }
764 }
765 return true;
766}
767
David Sehrc757dec2016-11-04 15:48:34 -0700768
769bool HLoopInformation::HasExitEdge() const {
770 // Determine if this loop has at least one exit edge.
771 HBlocksInLoopReversePostOrderIterator it_loop(*this);
772 for (; !it_loop.Done(); it_loop.Advance()) {
773 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
774 if (!Contains(*successor)) {
775 return true;
776 }
777 }
778 }
779 return false;
780}
781
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100782bool HBasicBlock::Dominates(HBasicBlock* other) const {
783 // Walk up the dominator tree from `other`, to find out if `this`
784 // is an ancestor.
785 HBasicBlock* current = other;
786 while (current != nullptr) {
787 if (current == this) {
788 return true;
789 }
790 current = current->GetDominator();
791 }
792 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100793}
794
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100795static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100796 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100797 for (size_t i = 0; i < inputs.size(); ++i) {
798 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100799 }
800 // Environment should be created later.
801 DCHECK(!instruction->HasEnvironment());
802}
803
Roland Levillainccc07a92014-09-16 14:48:16 +0100804void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
805 HInstruction* replacement) {
806 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400807 if (initial->IsControlFlow()) {
808 // We can only replace a control flow instruction with another control flow instruction.
809 DCHECK(replacement->IsControlFlow());
810 DCHECK_EQ(replacement->GetId(), -1);
811 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
812 DCHECK_EQ(initial->GetBlock(), this);
813 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100814 DCHECK(initial->GetUses().empty());
815 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400816 replacement->SetBlock(this);
817 replacement->SetId(GetGraph()->GetNextInstructionId());
818 instructions_.InsertInstructionBefore(replacement, initial);
819 UpdateInputsUsers(replacement);
820 } else {
821 InsertInstructionBefore(replacement, initial);
822 initial->ReplaceWith(replacement);
823 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100824 RemoveInstruction(initial);
825}
826
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100827static void Add(HInstructionList* instruction_list,
828 HBasicBlock* block,
829 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000830 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000831 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100832 instruction->SetBlock(block);
833 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100834 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100835 instruction_list->AddInstruction(instruction);
836}
837
838void HBasicBlock::AddInstruction(HInstruction* instruction) {
839 Add(&instructions_, this, instruction);
840}
841
842void HBasicBlock::AddPhi(HPhi* phi) {
843 Add(&phis_, this, phi);
844}
845
David Brazdilc3d743f2015-04-22 13:40:50 +0100846void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
847 DCHECK(!cursor->IsPhi());
848 DCHECK(!instruction->IsPhi());
849 DCHECK_EQ(instruction->GetId(), -1);
850 DCHECK_NE(cursor->GetId(), -1);
851 DCHECK_EQ(cursor->GetBlock(), this);
852 DCHECK(!instruction->IsControlFlow());
853 instruction->SetBlock(this);
854 instruction->SetId(GetGraph()->GetNextInstructionId());
855 UpdateInputsUsers(instruction);
856 instructions_.InsertInstructionBefore(instruction, cursor);
857}
858
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100859void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
860 DCHECK(!cursor->IsPhi());
861 DCHECK(!instruction->IsPhi());
862 DCHECK_EQ(instruction->GetId(), -1);
863 DCHECK_NE(cursor->GetId(), -1);
864 DCHECK_EQ(cursor->GetBlock(), this);
865 DCHECK(!instruction->IsControlFlow());
866 DCHECK(!cursor->IsControlFlow());
867 instruction->SetBlock(this);
868 instruction->SetId(GetGraph()->GetNextInstructionId());
869 UpdateInputsUsers(instruction);
870 instructions_.InsertInstructionAfter(instruction, cursor);
871}
872
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100873void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
874 DCHECK_EQ(phi->GetId(), -1);
875 DCHECK_NE(cursor->GetId(), -1);
876 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100877 phi->SetBlock(this);
878 phi->SetId(GetGraph()->GetNextInstructionId());
879 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100880 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100881}
882
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883static void Remove(HInstructionList* instruction_list,
884 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000885 HInstruction* instruction,
886 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100887 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100888 instruction->SetBlock(nullptr);
889 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000890 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100891 DCHECK(instruction->GetUses().empty());
892 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000893 RemoveAsUser(instruction);
894 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895}
896
David Brazdil1abb4192015-02-17 18:33:36 +0000897void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100898 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000899 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100900}
901
David Brazdil1abb4192015-02-17 18:33:36 +0000902void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
903 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100904}
905
David Brazdilc7508e92015-04-27 13:28:57 +0100906void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
907 if (instruction->IsPhi()) {
908 RemovePhi(instruction->AsPhi(), ensure_safety);
909 } else {
910 RemoveInstruction(instruction, ensure_safety);
911 }
912}
913
Vladimir Marko71bf8092015-09-15 15:33:14 +0100914void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
915 for (size_t i = 0; i < locals.size(); i++) {
916 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100917 SetRawEnvAt(i, instruction);
918 if (instruction != nullptr) {
919 instruction->AddEnvUseAt(this, i);
920 }
921 }
922}
923
David Brazdiled596192015-01-23 10:39:45 +0000924void HEnvironment::CopyFrom(HEnvironment* env) {
925 for (size_t i = 0; i < env->Size(); i++) {
926 HInstruction* instruction = env->GetInstructionAt(i);
927 SetRawEnvAt(i, instruction);
928 if (instruction != nullptr) {
929 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100930 }
David Brazdiled596192015-01-23 10:39:45 +0000931 }
932}
933
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700934void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
935 HBasicBlock* loop_header) {
936 DCHECK(loop_header->IsLoopHeader());
937 for (size_t i = 0; i < env->Size(); i++) {
938 HInstruction* instruction = env->GetInstructionAt(i);
939 SetRawEnvAt(i, instruction);
940 if (instruction == nullptr) {
941 continue;
942 }
943 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
944 // At the end of the loop pre-header, the corresponding value for instruction
945 // is the first input of the phi.
946 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700947 SetRawEnvAt(i, initial);
948 initial->AddEnvUseAt(this, i);
949 } else {
950 instruction->AddEnvUseAt(this, i);
951 }
952 }
953}
954
David Brazdil1abb4192015-02-17 18:33:36 +0000955void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100956 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
957 HInstruction* user = env_use.GetInstruction();
958 auto before_env_use_node = env_use.GetBeforeUseNode();
959 user->env_uses_.erase_after(before_env_use_node);
960 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100961}
962
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000963HInstruction::InstructionKind HInstruction::GetKind() const {
964 return GetKindInternal();
965}
966
Calin Juravle77520bc2015-01-12 18:45:46 +0000967HInstruction* HInstruction::GetNextDisregardingMoves() const {
968 HInstruction* next = GetNext();
969 while (next != nullptr && next->IsParallelMove()) {
970 next = next->GetNext();
971 }
972 return next;
973}
974
975HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
976 HInstruction* previous = GetPrevious();
977 while (previous != nullptr && previous->IsParallelMove()) {
978 previous = previous->GetPrevious();
979 }
980 return previous;
981}
982
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100983void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000984 if (first_instruction_ == nullptr) {
985 DCHECK(last_instruction_ == nullptr);
986 first_instruction_ = last_instruction_ = instruction;
987 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -0700988 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000989 last_instruction_->next_ = instruction;
990 instruction->previous_ = last_instruction_;
991 last_instruction_ = instruction;
992 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000993}
994
David Brazdilc3d743f2015-04-22 13:40:50 +0100995void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
996 DCHECK(Contains(cursor));
997 if (cursor == first_instruction_) {
998 cursor->previous_ = instruction;
999 instruction->next_ = cursor;
1000 first_instruction_ = instruction;
1001 } else {
1002 instruction->previous_ = cursor->previous_;
1003 instruction->next_ = cursor;
1004 cursor->previous_ = instruction;
1005 instruction->previous_->next_ = instruction;
1006 }
1007}
1008
1009void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1010 DCHECK(Contains(cursor));
1011 if (cursor == last_instruction_) {
1012 cursor->next_ = instruction;
1013 instruction->previous_ = cursor;
1014 last_instruction_ = instruction;
1015 } else {
1016 instruction->next_ = cursor->next_;
1017 instruction->previous_ = cursor;
1018 cursor->next_ = instruction;
1019 instruction->next_->previous_ = instruction;
1020 }
1021}
1022
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001023void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1024 if (instruction->previous_ != nullptr) {
1025 instruction->previous_->next_ = instruction->next_;
1026 }
1027 if (instruction->next_ != nullptr) {
1028 instruction->next_->previous_ = instruction->previous_;
1029 }
1030 if (instruction == first_instruction_) {
1031 first_instruction_ = instruction->next_;
1032 }
1033 if (instruction == last_instruction_) {
1034 last_instruction_ = instruction->previous_;
1035 }
1036}
1037
Roland Levillain6b469232014-09-25 10:10:38 +01001038bool HInstructionList::Contains(HInstruction* instruction) const {
1039 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1040 if (it.Current() == instruction) {
1041 return true;
1042 }
1043 }
1044 return false;
1045}
1046
Roland Levillainccc07a92014-09-16 14:48:16 +01001047bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1048 const HInstruction* instruction2) const {
1049 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1050 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1051 if (it.Current() == instruction1) {
1052 return true;
1053 }
1054 if (it.Current() == instruction2) {
1055 return false;
1056 }
1057 }
1058 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1059 return true;
1060}
1061
Roland Levillain6c82d402014-10-13 16:10:27 +01001062bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1063 if (other_instruction == this) {
1064 // An instruction does not strictly dominate itself.
1065 return false;
1066 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001067 HBasicBlock* block = GetBlock();
1068 HBasicBlock* other_block = other_instruction->GetBlock();
1069 if (block != other_block) {
1070 return GetBlock()->Dominates(other_instruction->GetBlock());
1071 } else {
1072 // If both instructions are in the same block, ensure this
1073 // instruction comes before `other_instruction`.
1074 if (IsPhi()) {
1075 if (!other_instruction->IsPhi()) {
1076 // Phis appear before non phi-instructions so this instruction
1077 // dominates `other_instruction`.
1078 return true;
1079 } else {
1080 // There is no order among phis.
1081 LOG(FATAL) << "There is no dominance between phis of a same block.";
1082 return false;
1083 }
1084 } else {
1085 // `this` is not a phi.
1086 if (other_instruction->IsPhi()) {
1087 // Phis appear before non phi-instructions so this instruction
1088 // does not dominate `other_instruction`.
1089 return false;
1090 } else {
1091 // Check whether this instruction comes before
1092 // `other_instruction` in the instruction list.
1093 return block->GetInstructions().FoundBefore(this, other_instruction);
1094 }
1095 }
1096 }
1097}
1098
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001099void HInstruction::RemoveEnvironment() {
1100 RemoveEnvironmentUses(this);
1101 environment_ = nullptr;
1102}
1103
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001104void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001105 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001106 // Note: fixup_end remains valid across splice_after().
1107 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1108 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1109 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001110
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001111 // Note: env_fixup_end remains valid across splice_after().
1112 auto env_fixup_end =
1113 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1114 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1115 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001116
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001117 DCHECK(uses_.empty());
1118 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001119}
1120
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001121void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1122 const HUseList<HInstruction*>& uses = GetUses();
1123 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1124 HInstruction* user = it->GetUser();
1125 size_t index = it->GetIndex();
1126 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1127 ++it;
1128 if (dominator->StrictlyDominates(user)) {
1129 user->ReplaceInput(replacement, index);
1130 }
1131 }
1132}
1133
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001134void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001135 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001136 if (input_use.GetInstruction() == replacement) {
1137 // Nothing to do.
1138 return;
1139 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001140 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001141 // Note: fixup_end remains valid across splice_after().
1142 auto fixup_end =
1143 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1144 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1145 input_use.GetInstruction()->uses_,
1146 before_use_node);
1147 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1148 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001149}
1150
Nicolas Geoffray39468442014-09-02 15:17:15 +01001151size_t HInstruction::EnvironmentSize() const {
1152 return HasEnvironment() ? environment_->Size() : 0;
1153}
1154
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001155void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001156 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001157 inputs_.push_back(HUserRecord<HInstruction*>(input));
1158 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001159}
1160
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001161void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1162 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1163 input->AddUseAt(this, index);
1164 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1165 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1166 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1167 inputs_[i].GetUseNode()->SetIndex(i);
1168 }
1169}
1170
1171void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001172 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001173 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001174 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1175 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1176 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1177 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001178 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001179}
1180
Igor Murashkind01745e2017-04-05 16:40:31 -07001181void HVariableInputSizeInstruction::RemoveAllInputs() {
1182 RemoveAsUserOfAllInputs();
1183 DCHECK(!HasNonEnvironmentUses());
1184
1185 inputs_.clear();
1186 DCHECK_EQ(0u, InputCount());
1187}
1188
1189void HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
1190 DCHECK(instruction->GetBlock() != nullptr);
1191 // Removing constructor fences only makes sense for instructions with an object return type.
1192 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1193
1194 // Efficient implementation that simultaneously (in one pass):
1195 // * Scans the uses list for all constructor fences.
1196 // * Deletes that constructor fence from the uses list of `instruction`.
1197 // * Deletes `instruction` from the constructor fence's inputs.
1198 // * Deletes the constructor fence if it now has 0 inputs.
1199
1200 const HUseList<HInstruction*>& uses = instruction->GetUses();
1201 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1202 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1203 const HUseListNode<HInstruction*>& use_node = *it;
1204 HInstruction* const use_instruction = use_node.GetUser();
1205
1206 // Advance the iterator immediately once we fetch the use_node.
1207 // Warning: If the input is removed, the current iterator becomes invalid.
1208 ++it;
1209
1210 if (use_instruction->IsConstructorFence()) {
1211 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1212 size_t input_index = use_node.GetIndex();
1213
1214 // Process the candidate instruction for removal
1215 // from the graph.
1216
1217 // Constructor fence instructions are never
1218 // used by other instructions.
1219 //
1220 // If we wanted to make this more generic, it
1221 // could be a runtime if statement.
1222 DCHECK(!ctor_fence->HasUses());
1223
1224 // A constructor fence's return type is "kPrimVoid"
1225 // and therefore it can't have any environment uses.
1226 DCHECK(!ctor_fence->HasEnvironmentUses());
1227
1228 // Remove the inputs first, otherwise removing the instruction
1229 // will try to remove its uses while we are already removing uses
1230 // and this operation will fail.
1231 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1232
1233 // Removing the input will also remove the `use_node`.
1234 // (Do not look at `use_node` after this, it will be a dangling reference).
1235 ctor_fence->RemoveInputAt(input_index);
1236
1237 // Once all inputs are removed, the fence is considered dead and
1238 // is removed.
1239 if (ctor_fence->InputCount() == 0u) {
1240 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
1241 }
1242 }
1243 }
1244
1245 if (kIsDebugBuild) {
1246 // Post-condition checks:
1247 // * None of the uses of `instruction` are a constructor fence.
1248 // * The `instruction` itself did not get removed from a block.
1249 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1250 CHECK(!use_node.GetUser()->IsConstructorFence());
1251 }
1252 CHECK(instruction->GetBlock() != nullptr);
1253 }
1254}
1255
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001256HInstruction* HConstructorFence::GetAssociatedAllocation() {
1257 HInstruction* new_instance_inst = GetPrevious();
1258 // Check if the immediately preceding instruction is a new-instance/new-array.
1259 // Otherwise this fence is for protecting final fields.
1260 if (new_instance_inst != nullptr &&
1261 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1262 // TODO: Need to update this code to handle multiple inputs.
1263 DCHECK_EQ(InputCount(), 1u);
1264 return new_instance_inst;
1265 } else {
1266 return nullptr;
1267 }
1268}
1269
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001270#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001271void H##name::Accept(HGraphVisitor* visitor) { \
1272 visitor->Visit##name(this); \
1273}
1274
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001275FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001276
1277#undef DEFINE_ACCEPT
1278
1279void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001280 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1281 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001282 if (block != nullptr) {
1283 VisitBasicBlock(block);
1284 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001285 }
1286}
1287
Roland Levillain633021e2014-10-01 14:12:25 +01001288void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001289 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1290 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001291 }
1292}
1293
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001294void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001295 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001296 it.Current()->Accept(this);
1297 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001298 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001299 it.Current()->Accept(this);
1300 }
1301}
1302
Mark Mendelle82549b2015-05-06 10:55:34 -04001303HConstant* HTypeConversion::TryStaticEvaluation() const {
1304 HGraph* graph = GetBlock()->GetGraph();
1305 if (GetInput()->IsIntConstant()) {
1306 int32_t value = GetInput()->AsIntConstant()->GetValue();
1307 switch (GetResultType()) {
1308 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001309 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001310 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001311 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001312 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001313 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001314 default:
1315 return nullptr;
1316 }
1317 } else if (GetInput()->IsLongConstant()) {
1318 int64_t value = GetInput()->AsLongConstant()->GetValue();
1319 switch (GetResultType()) {
1320 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001321 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001322 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001323 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001324 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001325 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001326 default:
1327 return nullptr;
1328 }
1329 } else if (GetInput()->IsFloatConstant()) {
1330 float value = GetInput()->AsFloatConstant()->GetValue();
1331 switch (GetResultType()) {
1332 case Primitive::kPrimInt:
1333 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001334 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001335 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001336 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001337 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001338 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1339 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001340 case Primitive::kPrimLong:
1341 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001342 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001343 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001344 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001345 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001346 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1347 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001348 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001349 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001350 default:
1351 return nullptr;
1352 }
1353 } else if (GetInput()->IsDoubleConstant()) {
1354 double value = GetInput()->AsDoubleConstant()->GetValue();
1355 switch (GetResultType()) {
1356 case Primitive::kPrimInt:
1357 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001358 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001359 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001360 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001361 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001362 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1363 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001364 case Primitive::kPrimLong:
1365 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001366 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001367 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001368 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001369 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001370 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1371 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001372 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001373 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001374 default:
1375 return nullptr;
1376 }
1377 }
1378 return nullptr;
1379}
1380
Roland Levillain9240d6a2014-10-20 16:47:04 +01001381HConstant* HUnaryOperation::TryStaticEvaluation() const {
1382 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001383 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001384 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001385 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001386 } else if (kEnableFloatingPointStaticEvaluation) {
1387 if (GetInput()->IsFloatConstant()) {
1388 return Evaluate(GetInput()->AsFloatConstant());
1389 } else if (GetInput()->IsDoubleConstant()) {
1390 return Evaluate(GetInput()->AsDoubleConstant());
1391 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001392 }
1393 return nullptr;
1394}
1395
1396HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001397 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1398 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001399 } else if (GetLeft()->IsLongConstant()) {
1400 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001401 // The binop(long, int) case is only valid for shifts and rotations.
1402 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001403 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1404 } else if (GetRight()->IsLongConstant()) {
1405 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001406 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001407 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001408 // The binop(null, null) case is only valid for equal and not-equal conditions.
1409 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001410 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001411 } else if (kEnableFloatingPointStaticEvaluation) {
1412 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1413 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1414 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1415 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1416 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001417 }
1418 return nullptr;
1419}
Dave Allison20dfc792014-06-16 20:44:29 -07001420
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001421HConstant* HBinaryOperation::GetConstantRight() const {
1422 if (GetRight()->IsConstant()) {
1423 return GetRight()->AsConstant();
1424 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1425 return GetLeft()->AsConstant();
1426 } else {
1427 return nullptr;
1428 }
1429}
1430
1431// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001432// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001433HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1434 HInstruction* most_constant_right = GetConstantRight();
1435 if (most_constant_right == nullptr) {
1436 return nullptr;
1437 } else if (most_constant_right == GetLeft()) {
1438 return GetRight();
1439 } else {
1440 return GetLeft();
1441 }
1442}
1443
Roland Levillain31dd3d62016-02-16 12:21:02 +00001444std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1445 switch (rhs) {
1446 case ComparisonBias::kNoBias:
1447 return os << "no_bias";
1448 case ComparisonBias::kGtBias:
1449 return os << "gt_bias";
1450 case ComparisonBias::kLtBias:
1451 return os << "lt_bias";
1452 default:
1453 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1454 UNREACHABLE();
1455 }
1456}
1457
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001458bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1459 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001460}
1461
Vladimir Marko372f10e2016-05-17 16:30:10 +01001462bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001463 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001464 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001465 if (!InstructionDataEquals(other)) return false;
1466 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001467 HConstInputsRef inputs = GetInputs();
1468 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001469 if (inputs.size() != other_inputs.size()) return false;
1470 for (size_t i = 0; i != inputs.size(); ++i) {
1471 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001472 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001473
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001474 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001475 return true;
1476}
1477
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001478std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1479#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1480 switch (rhs) {
1481 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1482 default:
1483 os << "Unknown instruction kind " << static_cast<int>(rhs);
1484 break;
1485 }
1486#undef DECLARE_CASE
1487 return os;
1488}
1489
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001490void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1491 if (do_checks) {
1492 DCHECK(!IsPhi());
1493 DCHECK(!IsControlFlow());
1494 DCHECK(CanBeMoved() ||
1495 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1496 IsShouldDeoptimizeFlag());
1497 DCHECK(!cursor->IsPhi());
1498 }
David Brazdild6c205e2016-06-07 14:20:52 +01001499
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001500 next_->previous_ = previous_;
1501 if (previous_ != nullptr) {
1502 previous_->next_ = next_;
1503 }
1504 if (block_->instructions_.first_instruction_ == this) {
1505 block_->instructions_.first_instruction_ = next_;
1506 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001507 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001508
1509 previous_ = cursor->previous_;
1510 if (previous_ != nullptr) {
1511 previous_->next_ = this;
1512 }
1513 next_ = cursor;
1514 cursor->previous_ = this;
1515 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001516
1517 if (block_->instructions_.first_instruction_ == cursor) {
1518 block_->instructions_.first_instruction_ = this;
1519 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001520}
1521
Vladimir Markofb337ea2015-11-25 15:25:10 +00001522void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1523 DCHECK(!CanThrow());
1524 DCHECK(!HasSideEffects());
1525 DCHECK(!HasEnvironmentUses());
1526 DCHECK(HasNonEnvironmentUses());
1527 DCHECK(!IsPhi()); // Makes no sense for Phi.
1528 DCHECK_EQ(InputCount(), 0u);
1529
1530 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001531 auto uses_it = GetUses().begin();
1532 auto uses_end = GetUses().end();
1533 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1534 ++uses_it;
1535 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1536 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001537 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001538 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001539 // This instruction has uses in two or more blocks. Find the common dominator.
1540 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001541 for (; uses_it != uses_end; ++uses_it) {
1542 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001543 }
1544 target_block = finder.Get();
1545 DCHECK(target_block != nullptr);
1546 }
1547 // Move to the first dominator not in a loop.
1548 while (target_block->IsInLoop()) {
1549 target_block = target_block->GetDominator();
1550 DCHECK(target_block != nullptr);
1551 }
1552
1553 // Find insertion position.
1554 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001555 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1556 if (use.GetUser()->GetBlock() == target_block &&
1557 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1558 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001559 }
1560 }
1561 if (insert_pos == nullptr) {
1562 // No user in `target_block`, insert before the control flow instruction.
1563 insert_pos = target_block->GetLastInstruction();
1564 DCHECK(insert_pos->IsControlFlow());
1565 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1566 if (insert_pos->IsIf()) {
1567 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1568 if (if_input == insert_pos->GetPrevious()) {
1569 insert_pos = if_input;
1570 }
1571 }
1572 }
1573 MoveBefore(insert_pos);
1574}
1575
David Brazdilfc6a86a2015-06-26 10:33:45 +00001576HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001577 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001578 DCHECK_EQ(cursor->GetBlock(), this);
1579
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001580 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1581 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001582 new_block->instructions_.first_instruction_ = cursor;
1583 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1584 instructions_.last_instruction_ = cursor->previous_;
1585 if (cursor->previous_ == nullptr) {
1586 instructions_.first_instruction_ = nullptr;
1587 } else {
1588 cursor->previous_->next_ = nullptr;
1589 cursor->previous_ = nullptr;
1590 }
1591
1592 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001593 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001594
Vladimir Marko60584552015-09-03 13:35:12 +00001595 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001596 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001597 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001598 new_block->successors_.swap(successors_);
1599 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001600 AddSuccessor(new_block);
1601
David Brazdil56e1acc2015-06-30 15:41:36 +01001602 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001603 return new_block;
1604}
1605
David Brazdild7558da2015-09-22 13:04:14 +01001606HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001607 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001608 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1609
1610 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1611
1612 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001613 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1614 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001615 new_block->predecessors_.swap(predecessors_);
1616 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001617 AddPredecessor(new_block);
1618
1619 GetGraph()->AddBlock(new_block);
1620 return new_block;
1621}
1622
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001623HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1624 DCHECK_EQ(cursor->GetBlock(), this);
1625
1626 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1627 cursor->GetDexPc());
1628 new_block->instructions_.first_instruction_ = cursor;
1629 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1630 instructions_.last_instruction_ = cursor->previous_;
1631 if (cursor->previous_ == nullptr) {
1632 instructions_.first_instruction_ = nullptr;
1633 } else {
1634 cursor->previous_->next_ = nullptr;
1635 cursor->previous_ = nullptr;
1636 }
1637
1638 new_block->instructions_.SetBlockOfInstructions(new_block);
1639
1640 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001641 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1642 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001643 new_block->successors_.swap(successors_);
1644 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001645
1646 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1647 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001648 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001649 new_block->dominated_blocks_.swap(dominated_blocks_);
1650 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001651 return new_block;
1652}
1653
1654HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001655 DCHECK(!cursor->IsControlFlow());
1656 DCHECK_NE(instructions_.last_instruction_, cursor);
1657 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001658
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001659 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1660 new_block->instructions_.first_instruction_ = cursor->GetNext();
1661 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1662 cursor->next_->previous_ = nullptr;
1663 cursor->next_ = nullptr;
1664 instructions_.last_instruction_ = cursor;
1665
1666 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001667 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001668 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001669 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001670 new_block->successors_.swap(successors_);
1671 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001672
Vladimir Marko60584552015-09-03 13:35:12 +00001673 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001674 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001675 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001676 new_block->dominated_blocks_.swap(dominated_blocks_);
1677 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001678 return new_block;
1679}
1680
David Brazdilec16f792015-08-19 15:04:01 +01001681const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001682 if (EndsWithTryBoundary()) {
1683 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1684 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001685 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001686 return try_boundary;
1687 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001688 DCHECK(IsTryBlock());
1689 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001690 return nullptr;
1691 }
David Brazdilec16f792015-08-19 15:04:01 +01001692 } else if (IsTryBlock()) {
1693 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001694 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001695 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001696 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001697}
1698
David Brazdild7558da2015-09-22 13:04:14 +01001699bool HBasicBlock::HasThrowingInstructions() const {
1700 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1701 if (it.Current()->CanThrow()) {
1702 return true;
1703 }
1704 }
1705 return false;
1706}
1707
David Brazdilfc6a86a2015-06-26 10:33:45 +00001708static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1709 return block.GetPhis().IsEmpty()
1710 && !block.GetInstructions().IsEmpty()
1711 && block.GetFirstInstruction() == block.GetLastInstruction();
1712}
1713
David Brazdil46e2a392015-03-16 17:31:52 +00001714bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001715 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1716}
1717
1718bool HBasicBlock::IsSingleTryBoundary() const {
1719 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001720}
1721
David Brazdil8d5b8b22015-03-24 10:51:52 +00001722bool HBasicBlock::EndsWithControlFlowInstruction() const {
1723 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1724}
1725
David Brazdilb2bd1c52015-03-25 11:17:37 +00001726bool HBasicBlock::EndsWithIf() const {
1727 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1728}
1729
David Brazdilffee3d32015-07-06 11:48:53 +01001730bool HBasicBlock::EndsWithTryBoundary() const {
1731 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1732}
1733
David Brazdilb2bd1c52015-03-25 11:17:37 +00001734bool HBasicBlock::HasSinglePhi() const {
1735 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1736}
1737
David Brazdild26a4112015-11-10 11:07:31 +00001738ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1739 if (EndsWithTryBoundary()) {
1740 // The normal-flow successor of HTryBoundary is always stored at index zero.
1741 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1742 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1743 } else {
1744 // All successors of blocks not ending with TryBoundary are normal.
1745 return ArrayRef<HBasicBlock* const>(successors_);
1746 }
1747}
1748
1749ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1750 if (EndsWithTryBoundary()) {
1751 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1752 } else {
1753 // Blocks not ending with TryBoundary do not have exceptional successors.
1754 return ArrayRef<HBasicBlock* const>();
1755 }
1756}
1757
David Brazdilffee3d32015-07-06 11:48:53 +01001758bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001759 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1760 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1761
1762 size_t length = handlers1.size();
1763 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001764 return false;
1765 }
1766
David Brazdilb618ade2015-07-29 10:31:29 +01001767 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001768 for (size_t i = 0; i < length; ++i) {
1769 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001770 return false;
1771 }
1772 }
1773 return true;
1774}
1775
David Brazdil2d7352b2015-04-20 14:52:42 +01001776size_t HInstructionList::CountSize() const {
1777 size_t size = 0;
1778 HInstruction* current = first_instruction_;
1779 for (; current != nullptr; current = current->GetNext()) {
1780 size++;
1781 }
1782 return size;
1783}
1784
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001785void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1786 for (HInstruction* current = first_instruction_;
1787 current != nullptr;
1788 current = current->GetNext()) {
1789 current->SetBlock(block);
1790 }
1791}
1792
1793void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1794 DCHECK(Contains(cursor));
1795 if (!instruction_list.IsEmpty()) {
1796 if (cursor == last_instruction_) {
1797 last_instruction_ = instruction_list.last_instruction_;
1798 } else {
1799 cursor->next_->previous_ = instruction_list.last_instruction_;
1800 }
1801 instruction_list.last_instruction_->next_ = cursor->next_;
1802 cursor->next_ = instruction_list.first_instruction_;
1803 instruction_list.first_instruction_->previous_ = cursor;
1804 }
1805}
1806
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001807void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1808 DCHECK(Contains(cursor));
1809 if (!instruction_list.IsEmpty()) {
1810 if (cursor == first_instruction_) {
1811 first_instruction_ = instruction_list.first_instruction_;
1812 } else {
1813 cursor->previous_->next_ = instruction_list.first_instruction_;
1814 }
1815 instruction_list.last_instruction_->next_ = cursor;
1816 instruction_list.first_instruction_->previous_ = cursor->previous_;
1817 cursor->previous_ = instruction_list.last_instruction_;
1818 }
1819}
1820
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001821void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001822 if (IsEmpty()) {
1823 first_instruction_ = instruction_list.first_instruction_;
1824 last_instruction_ = instruction_list.last_instruction_;
1825 } else {
1826 AddAfter(last_instruction_, instruction_list);
1827 }
1828}
1829
David Brazdil04ff4e82015-12-10 13:54:52 +00001830// Should be called on instructions in a dead block in post order. This method
1831// assumes `insn` has been removed from all users with the exception of catch
1832// phis because of missing exceptional edges in the graph. It removes the
1833// instruction from catch phi uses, together with inputs of other catch phis in
1834// the catch block at the same index, as these must be dead too.
1835static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1836 DCHECK(!insn->HasEnvironmentUses());
1837 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001838 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1839 size_t use_index = use.GetIndex();
1840 HBasicBlock* user_block = use.GetUser()->GetBlock();
1841 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001842 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1843 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1844 }
1845 }
1846}
1847
David Brazdil2d7352b2015-04-20 14:52:42 +01001848void HBasicBlock::DisconnectAndDelete() {
1849 // Dominators must be removed after all the blocks they dominate. This way
1850 // a loop header is removed last, a requirement for correct loop information
1851 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001852 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001853
David Brazdil9eeebf62016-03-24 11:18:15 +00001854 // The following steps gradually remove the block from all its dependants in
1855 // post order (b/27683071).
1856
1857 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1858 // We need to do this before step (4) which destroys the predecessor list.
1859 HBasicBlock* loop_update_start = this;
1860 if (IsLoopHeader()) {
1861 HLoopInformation* loop_info = GetLoopInformation();
1862 // All other blocks in this loop should have been removed because the header
1863 // was their dominator.
1864 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1865 DCHECK(!loop_info->IsIrreducible());
1866 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1867 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1868 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001869 }
1870
David Brazdil9eeebf62016-03-24 11:18:15 +00001871 // (2) Disconnect the block from its successors and update their phis.
1872 for (HBasicBlock* successor : successors_) {
1873 // Delete this block from the list of predecessors.
1874 size_t this_index = successor->GetPredecessorIndexOf(this);
1875 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1876
1877 // Check that `successor` has other predecessors, otherwise `this` is the
1878 // dominator of `successor` which violates the order DCHECKed at the top.
1879 DCHECK(!successor->predecessors_.empty());
1880
1881 // Remove this block's entries in the successor's phis. Skip exceptional
1882 // successors because catch phi inputs do not correspond to predecessor
1883 // blocks but throwing instructions. The inputs of the catch phis will be
1884 // updated in step (3).
1885 if (!successor->IsCatchBlock()) {
1886 if (successor->predecessors_.size() == 1u) {
1887 // The successor has just one predecessor left. Replace phis with the only
1888 // remaining input.
1889 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1890 HPhi* phi = phi_it.Current()->AsPhi();
1891 phi->ReplaceWith(phi->InputAt(1 - this_index));
1892 successor->RemovePhi(phi);
1893 }
1894 } else {
1895 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1896 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1897 }
1898 }
1899 }
1900 }
1901 successors_.clear();
1902
1903 // (3) Remove instructions and phis. Instructions should have no remaining uses
1904 // except in catch phis. If an instruction is used by a catch phi at `index`,
1905 // remove `index`-th input of all phis in the catch block since they are
1906 // guaranteed dead. Note that we may miss dead inputs this way but the
1907 // graph will always remain consistent.
1908 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1909 HInstruction* insn = it.Current();
1910 RemoveUsesOfDeadInstruction(insn);
1911 RemoveInstruction(insn);
1912 }
1913 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1914 HPhi* insn = it.Current()->AsPhi();
1915 RemoveUsesOfDeadInstruction(insn);
1916 RemovePhi(insn);
1917 }
1918
1919 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001920 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001921 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001922 // We should not see any back edges as they would have been removed by step (3).
1923 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1924
David Brazdil2d7352b2015-04-20 14:52:42 +01001925 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001926 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1927 // This block is the only normal-flow successor of the TryBoundary which
1928 // makes `predecessor` dead. Since DCE removes blocks in post order,
1929 // exception handlers of this TryBoundary were already visited and any
1930 // remaining handlers therefore must be live. We remove `predecessor` from
1931 // their list of predecessors.
1932 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1933 while (predecessor->GetSuccessors().size() > 1) {
1934 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1935 DCHECK(handler->IsCatchBlock());
1936 predecessor->RemoveSuccessor(handler);
1937 handler->RemovePredecessor(predecessor);
1938 }
1939 }
1940
David Brazdil2d7352b2015-04-20 14:52:42 +01001941 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001942 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1943 if (num_pred_successors == 1u) {
1944 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001945 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1946 // successor. Replace those with a HGoto.
1947 DCHECK(last_instruction->IsIf() ||
1948 last_instruction->IsPackedSwitch() ||
1949 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001950 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001951 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001952 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001953 // The predecessor has no remaining successors and therefore must be dead.
1954 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001955 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001956 predecessor->RemoveInstruction(last_instruction);
1957 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001958 // There are multiple successors left. The removed block might be a successor
1959 // of a PackedSwitch which will be completely removed (perhaps replaced with
1960 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1961 // case, leave `last_instruction` as is for now.
1962 DCHECK(last_instruction->IsPackedSwitch() ||
1963 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001964 }
David Brazdil46e2a392015-03-16 17:31:52 +00001965 }
Vladimir Marko60584552015-09-03 13:35:12 +00001966 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001967
David Brazdil9eeebf62016-03-24 11:18:15 +00001968 // (5) Remove the block from all loops it is included in. Skip the inner-most
1969 // loop if this is the loop header (see definition of `loop_update_start`)
1970 // because the loop header's predecessor list has been destroyed in step (4).
1971 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1972 HLoopInformation* loop_info = it.Current();
1973 loop_info->Remove(this);
1974 if (loop_info->IsBackEdge(*this)) {
1975 // If this was the last back edge of the loop, we deliberately leave the
1976 // loop in an inconsistent state and will fail GraphChecker unless the
1977 // entire loop is removed during the pass.
1978 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001979 }
1980 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001981
David Brazdil9eeebf62016-03-24 11:18:15 +00001982 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001983 dominator_->RemoveDominatedBlock(this);
1984 SetDominator(nullptr);
1985
David Brazdil9eeebf62016-03-24 11:18:15 +00001986 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001987 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001988 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989}
1990
Aart Bik6b69e0a2017-01-11 10:20:43 -08001991void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
1992 DCHECK(EndsWithControlFlowInstruction());
1993 RemoveInstruction(GetLastInstruction());
1994 instructions_.Add(other->GetInstructions());
1995 other->instructions_.SetBlockOfInstructions(this);
1996 other->instructions_.Clear();
1997}
1998
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001999void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002000 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002001 DCHECK(ContainsElement(dominated_blocks_, other));
2002 DCHECK_EQ(GetSingleSuccessor(), other);
2003 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002004 DCHECK(other->GetPhis().IsEmpty());
2005
David Brazdil2d7352b2015-04-20 14:52:42 +01002006 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002007 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002008
David Brazdil2d7352b2015-04-20 14:52:42 +01002009 // Remove `other` from the loops it is included in.
2010 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2011 HLoopInformation* loop_info = it.Current();
2012 loop_info->Remove(other);
2013 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002014 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002015 }
2016 }
2017
2018 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002019 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002020 for (HBasicBlock* successor : other->GetSuccessors()) {
2021 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002022 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002023 successors_.swap(other->successors_);
2024 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002025
David Brazdil2d7352b2015-04-20 14:52:42 +01002026 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002027 RemoveDominatedBlock(other);
2028 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002029 dominated->SetDominator(this);
2030 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002031 dominated_blocks_.insert(
2032 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002033 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002034 other->dominator_ = nullptr;
2035
2036 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002037 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002038
2039 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002040 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002041 other->SetGraph(nullptr);
2042}
2043
2044void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2045 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002046 DCHECK(GetDominatedBlocks().empty());
2047 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002048 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002049 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002050 DCHECK(other->GetPhis().IsEmpty());
2051 DCHECK(!other->IsInLoop());
2052
2053 // Move instructions from `other` to `this`.
2054 instructions_.Add(other->GetInstructions());
2055 other->instructions_.SetBlockOfInstructions(this);
2056
2057 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002058 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002059 for (HBasicBlock* successor : other->GetSuccessors()) {
2060 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002061 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002062 successors_.swap(other->successors_);
2063 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002064
2065 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002066 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002067 dominated->SetDominator(this);
2068 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002069 dominated_blocks_.insert(
2070 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002071 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002072 other->dominator_ = nullptr;
2073 other->graph_ = nullptr;
2074}
2075
2076void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002077 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002078 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002079 predecessor->ReplaceSuccessor(this, other);
2080 }
Vladimir Marko60584552015-09-03 13:35:12 +00002081 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002082 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002083 successor->ReplacePredecessor(this, other);
2084 }
Vladimir Marko60584552015-09-03 13:35:12 +00002085 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2086 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002087 }
2088 GetDominator()->ReplaceDominatedBlock(this, other);
2089 other->SetDominator(GetDominator());
2090 dominator_ = nullptr;
2091 graph_ = nullptr;
2092}
2093
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002094void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002095 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002096 DCHECK(block->GetSuccessors().empty());
2097 DCHECK(block->GetPredecessors().empty());
2098 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002099 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002100 DCHECK(block->GetInstructions().IsEmpty());
2101 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002102
David Brazdilc7af85d2015-05-26 12:05:55 +01002103 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002104 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002105 }
2106
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002107 RemoveElement(reverse_post_order_, block);
2108 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002109 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002110}
2111
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002112void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2113 HBasicBlock* reference,
2114 bool replace_if_back_edge) {
2115 if (block->IsLoopHeader()) {
2116 // Clear the information of which blocks are contained in that loop. Since the
2117 // information is stored as a bit vector based on block ids, we have to update
2118 // it, as those block ids were specific to the callee graph and we are now adding
2119 // these blocks to the caller graph.
2120 block->GetLoopInformation()->ClearAllBlocks();
2121 }
2122
2123 // If not already in a loop, update the loop information.
2124 if (!block->IsInLoop()) {
2125 block->SetLoopInformation(reference->GetLoopInformation());
2126 }
2127
2128 // If the block is in a loop, update all its outward loops.
2129 HLoopInformation* loop_info = block->GetLoopInformation();
2130 if (loop_info != nullptr) {
2131 for (HLoopInformationOutwardIterator loop_it(*block);
2132 !loop_it.Done();
2133 loop_it.Advance()) {
2134 loop_it.Current()->Add(block);
2135 }
2136 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2137 loop_info->ReplaceBackEdge(reference, block);
2138 }
2139 }
2140
2141 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2142 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2143 ? reference->GetTryCatchInformation()
2144 : nullptr;
2145 block->SetTryCatchInformation(try_catch_info);
2146}
2147
Calin Juravle2e768302015-07-28 14:41:11 +00002148HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002149 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002150 // Update the environments in this graph to have the invoke's environment
2151 // as parent.
2152 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002153 // Skip the entry block, we do not need to update the entry's suspend check.
2154 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002155 for (HInstructionIterator instr_it(block->GetInstructions());
2156 !instr_it.Done();
2157 instr_it.Advance()) {
2158 HInstruction* current = instr_it.Current();
2159 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002160 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002161 current->GetEnvironment()->SetAndCopyParentChain(
2162 outer_graph->GetArena(), invoke->GetEnvironment());
2163 }
2164 }
2165 }
2166 }
2167 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002168
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002169 if (HasBoundsChecks()) {
2170 outer_graph->SetHasBoundsChecks(true);
2171 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002172 if (HasLoops()) {
2173 outer_graph->SetHasLoops(true);
2174 }
2175 if (HasIrreducibleLoops()) {
2176 outer_graph->SetHasIrreducibleLoops(true);
2177 }
2178 if (HasTryCatch()) {
2179 outer_graph->SetHasTryCatch(true);
2180 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002181 if (HasSIMD()) {
2182 outer_graph->SetHasSIMD(true);
2183 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002184
Calin Juravle2e768302015-07-28 14:41:11 +00002185 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002186 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002187 // Inliner already made sure we don't inline methods that always throw.
2188 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002189 // Simple case of an entry block, a body block, and an exit block.
2190 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002191 HBasicBlock* body = GetBlocks()[1];
2192 DCHECK(GetBlocks()[0]->IsEntryBlock());
2193 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002194 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002195 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002196 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002197
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002198 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2199 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002200 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002201
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002202 // Replace the invoke with the return value of the inlined graph.
2203 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002204 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002205 } else {
2206 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002207 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002208
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002209 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002210 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002211 // Need to inline multiple blocks. We split `invoke`'s block
2212 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002213 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002214 // with the second half.
2215 ArenaAllocator* allocator = outer_graph->GetArena();
2216 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002217 // Note that we split before the invoke only to simplify polymorphic inlining.
2218 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002219
Vladimir Markoec7802a2015-10-01 20:57:57 +01002220 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002221 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002222 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002223 exit_block_->ReplaceWith(to);
2224
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002225 // Update the meta information surrounding blocks:
2226 // (1) the graph they are now in,
2227 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002228 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002229 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002230 // Note that we do not need to update catch phi inputs because they
2231 // correspond to the register file of the outer method which the inlinee
2232 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002233
2234 // We don't add the entry block, the exit block, and the first block, which
2235 // has been merged with `at`.
2236 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2237
2238 // We add the `to` block.
2239 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002240 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002241 + kNumberOfNewBlocksInCaller;
2242
2243 // Find the location of `at` in the outer graph's reverse post order. The new
2244 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002245 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002246 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2247
David Brazdil95177982015-10-30 12:56:58 -05002248 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2249 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002250 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002251 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002252 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002253 DCHECK(current->GetGraph() == this);
2254 current->SetGraph(outer_graph);
2255 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002256 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002257 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002258 }
2259 }
2260
David Brazdil95177982015-10-30 12:56:58 -05002261 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002262 to->SetGraph(outer_graph);
2263 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002264 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002265 // Only `to` can become a back edge, as the inlined blocks
2266 // are predecessors of `to`.
2267 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002268
David Brazdil3f523062016-02-29 16:53:33 +00002269 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002270 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2271 // to now get the outer graph exit block as successor. Note that the inliner
2272 // currently doesn't support inlining methods with try/catch.
2273 HPhi* return_value_phi = nullptr;
2274 bool rerun_dominance = false;
2275 bool rerun_loop_analysis = false;
2276 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2277 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002278 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002279 if (last->IsThrow()) {
2280 DCHECK(!at->IsTryBlock());
2281 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2282 --pred;
2283 // We need to re-run dominance information, as the exit block now has
2284 // a new dominator.
2285 rerun_dominance = true;
2286 if (predecessor->GetLoopInformation() != nullptr) {
2287 // The exit block and blocks post dominated by the exit block do not belong
2288 // to any loop. Because we do not compute the post dominators, we need to re-run
2289 // loop analysis to get the loop information correct.
2290 rerun_loop_analysis = true;
2291 }
2292 } else {
2293 if (last->IsReturnVoid()) {
2294 DCHECK(return_value == nullptr);
2295 DCHECK(return_value_phi == nullptr);
2296 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002297 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002298 if (return_value_phi != nullptr) {
2299 return_value_phi->AddInput(last->InputAt(0));
2300 } else if (return_value == nullptr) {
2301 return_value = last->InputAt(0);
2302 } else {
2303 // There will be multiple returns.
2304 return_value_phi = new (allocator) HPhi(
2305 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2306 to->AddPhi(return_value_phi);
2307 return_value_phi->AddInput(return_value);
2308 return_value_phi->AddInput(last->InputAt(0));
2309 return_value = return_value_phi;
2310 }
David Brazdil3f523062016-02-29 16:53:33 +00002311 }
2312 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2313 predecessor->RemoveInstruction(last);
2314 }
2315 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002316 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002317 DCHECK(!outer_graph->HasIrreducibleLoops())
2318 << "Recomputing loop information in graphs with irreducible loops "
2319 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002320 outer_graph->ClearLoopInformation();
2321 outer_graph->ClearDominanceInformation();
2322 outer_graph->BuildDominatorTree();
2323 } else if (rerun_dominance) {
2324 outer_graph->ClearDominanceInformation();
2325 outer_graph->ComputeDominanceInformation();
2326 }
David Brazdil3f523062016-02-29 16:53:33 +00002327 }
David Brazdil05144f42015-04-16 15:18:00 +01002328
2329 // Walk over the entry block and:
2330 // - Move constants from the entry block to the outer_graph's entry block,
2331 // - Replace HParameterValue instructions with their real value.
2332 // - Remove suspend checks, that hold an environment.
2333 // We must do this after the other blocks have been inlined, otherwise ids of
2334 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002335 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002336 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2337 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002338 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002339 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002340 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002341 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002342 replacement = outer_graph->GetIntConstant(
2343 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002344 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002345 replacement = outer_graph->GetLongConstant(
2346 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002347 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002348 replacement = outer_graph->GetFloatConstant(
2349 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002350 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002351 replacement = outer_graph->GetDoubleConstant(
2352 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002353 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002354 if (kIsDebugBuild
2355 && invoke->IsInvokeStaticOrDirect()
2356 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2357 // Ensure we do not use the last input of `invoke`, as it
2358 // contains a clinit check which is not an actual argument.
2359 size_t last_input_index = invoke->InputCount() - 1;
2360 DCHECK(parameter_index != last_input_index);
2361 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002362 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002363 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002364 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002365 } else {
2366 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2367 entry_block_->RemoveInstruction(current);
2368 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002369 if (replacement != nullptr) {
2370 current->ReplaceWith(replacement);
2371 // If the current is the return value then we need to update the latter.
2372 if (current == return_value) {
2373 DCHECK_EQ(entry_block_, return_value->GetBlock());
2374 return_value = replacement;
2375 }
2376 }
2377 }
2378
Calin Juravle2e768302015-07-28 14:41:11 +00002379 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002380}
2381
Mingyao Yang3584bce2015-05-19 16:01:59 -07002382/*
2383 * Loop will be transformed to:
2384 * old_pre_header
2385 * |
2386 * if_block
2387 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002388 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002389 * \ /
2390 * new_pre_header
2391 * |
2392 * header
2393 */
2394void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2395 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002396 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002397
Aart Bik3fc7f352015-11-20 22:03:03 -08002398 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002399 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002400 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2401 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002402 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2403 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002404 AddBlock(true_block);
2405 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002406 AddBlock(new_pre_header);
2407
Aart Bik3fc7f352015-11-20 22:03:03 -08002408 header->ReplacePredecessor(old_pre_header, new_pre_header);
2409 old_pre_header->successors_.clear();
2410 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002411
Aart Bik3fc7f352015-11-20 22:03:03 -08002412 old_pre_header->AddSuccessor(if_block);
2413 if_block->AddSuccessor(true_block); // True successor
2414 if_block->AddSuccessor(false_block); // False successor
2415 true_block->AddSuccessor(new_pre_header);
2416 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002417
Aart Bik3fc7f352015-11-20 22:03:03 -08002418 old_pre_header->dominated_blocks_.push_back(if_block);
2419 if_block->SetDominator(old_pre_header);
2420 if_block->dominated_blocks_.push_back(true_block);
2421 true_block->SetDominator(if_block);
2422 if_block->dominated_blocks_.push_back(false_block);
2423 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002424 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002425 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002426 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002427 header->SetDominator(new_pre_header);
2428
Aart Bik3fc7f352015-11-20 22:03:03 -08002429 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002430 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002431 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002432 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002433 reverse_post_order_[index_of_header++] = true_block;
2434 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002435 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002436
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002437 // The pre_header can never be a back edge of a loop.
2438 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2439 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2440 UpdateLoopAndTryInformationOfNewBlock(
2441 if_block, old_pre_header, /* replace_if_back_edge */ false);
2442 UpdateLoopAndTryInformationOfNewBlock(
2443 true_block, old_pre_header, /* replace_if_back_edge */ false);
2444 UpdateLoopAndTryInformationOfNewBlock(
2445 false_block, old_pre_header, /* replace_if_back_edge */ false);
2446 UpdateLoopAndTryInformationOfNewBlock(
2447 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002448}
2449
Aart Bikf8f5a162017-02-06 15:35:29 -08002450HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2451 HBasicBlock* body,
2452 HBasicBlock* exit) {
2453 DCHECK(header->IsLoopHeader());
2454 HLoopInformation* loop = header->GetLoopInformation();
2455
2456 // Add new loop blocks.
2457 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2458 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2459 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2460 AddBlock(new_pre_header);
2461 AddBlock(new_header);
2462 AddBlock(new_body);
2463
2464 // Set up control flow.
2465 header->ReplaceSuccessor(exit, new_pre_header);
2466 new_pre_header->AddSuccessor(new_header);
2467 new_header->AddSuccessor(exit);
2468 new_header->AddSuccessor(new_body);
2469 new_body->AddSuccessor(new_header);
2470
2471 // Set up dominators.
2472 header->ReplaceDominatedBlock(exit, new_pre_header);
2473 new_pre_header->SetDominator(header);
2474 new_pre_header->dominated_blocks_.push_back(new_header);
2475 new_header->SetDominator(new_pre_header);
2476 new_header->dominated_blocks_.push_back(new_body);
2477 new_body->SetDominator(new_header);
2478 new_header->dominated_blocks_.push_back(exit);
2479 exit->SetDominator(new_header);
2480
2481 // Fix reverse post order.
2482 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2483 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2484 reverse_post_order_[++index_of_header] = new_pre_header;
2485 reverse_post_order_[++index_of_header] = new_header;
2486 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2487 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2488 reverse_post_order_[index_of_body] = new_body;
2489
Aart Bikb07d1bc2017-04-05 10:03:15 -07002490 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002491 new_pre_header->AddInstruction(new (arena_) HGoto());
2492 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2493 new_header->AddInstruction(suspend_check);
2494 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002495 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2496 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002497
2498 // Update loop information.
2499 new_header->AddBackEdge(new_body);
2500 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2501 new_header->GetLoopInformation()->Populate();
2502 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2503 HLoopInformationOutwardIterator it(*new_header);
2504 for (it.Advance(); !it.Done(); it.Advance()) {
2505 it.Current()->Add(new_pre_header);
2506 it.Current()->Add(new_header);
2507 it.Current()->Add(new_body);
2508 }
2509 return new_pre_header;
2510}
2511
David Brazdilf5552582015-12-27 13:36:12 +00002512static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002513 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002514 if (rti.IsValid()) {
2515 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2516 << " upper_bound_rti: " << upper_bound_rti
2517 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002518 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2519 << " upper_bound_rti: " << upper_bound_rti
2520 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002521 }
2522}
2523
Calin Juravle2e768302015-07-28 14:41:11 +00002524void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2525 if (kIsDebugBuild) {
2526 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2527 ScopedObjectAccess soa(Thread::Current());
2528 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2529 if (IsBoundType()) {
2530 // Having the test here spares us from making the method virtual just for
2531 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002532 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002533 }
2534 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002535 reference_type_handle_ = rti.GetTypeHandle();
2536 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002537}
2538
David Brazdilf5552582015-12-27 13:36:12 +00002539void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2540 if (kIsDebugBuild) {
2541 ScopedObjectAccess soa(Thread::Current());
2542 DCHECK(upper_bound.IsValid());
2543 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2544 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2545 }
2546 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002547 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002548}
2549
Vladimir Markoa1de9182016-02-25 11:37:38 +00002550ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002551 if (kIsDebugBuild) {
2552 ScopedObjectAccess soa(Thread::Current());
2553 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002554 if (!is_exact) {
2555 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2556 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2557 }
Calin Juravle2e768302015-07-28 14:41:11 +00002558 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002559 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002560}
2561
Calin Juravleacf735c2015-02-12 15:25:22 +00002562std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2563 ScopedObjectAccess soa(Thread::Current());
2564 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002565 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002566 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002567 << " is_exact=" << rhs.IsExact()
2568 << " ]";
2569 return os;
2570}
2571
Mark Mendellc4701932015-04-10 13:18:51 -04002572bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2573 // For now, assume that instructions in different blocks may use the
2574 // environment.
2575 // TODO: Use the control flow to decide if this is true.
2576 if (GetBlock() != other->GetBlock()) {
2577 return true;
2578 }
2579
2580 // We know that we are in the same block. Walk from 'this' to 'other',
2581 // checking to see if there is any instruction with an environment.
2582 HInstruction* current = this;
2583 for (; current != other && current != nullptr; current = current->GetNext()) {
2584 // This is a conservative check, as the instruction result may not be in
2585 // the referenced environment.
2586 if (current->HasEnvironment()) {
2587 return true;
2588 }
2589 }
2590
2591 // We should have been called with 'this' before 'other' in the block.
2592 // Just confirm this.
2593 DCHECK(current != nullptr);
2594 return false;
2595}
2596
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002597void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002598 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2599 IntrinsicSideEffects side_effects,
2600 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002601 intrinsic_ = intrinsic;
2602 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002603
Aart Bik5d75afe2015-12-14 11:57:01 -08002604 // Adjust method's side effects from intrinsic table.
2605 switch (side_effects) {
2606 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2607 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2608 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2609 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2610 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002611
2612 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2613 opt.SetDoesNotNeedDexCache();
2614 opt.SetDoesNotNeedEnvironment();
2615 } else {
2616 // If we need an environment, that means there will be a call, which can trigger GC.
2617 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2618 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002619 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002620 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002621}
2622
David Brazdil6de19382016-01-08 17:37:10 +00002623bool HNewInstance::IsStringAlloc() const {
2624 ScopedObjectAccess soa(Thread::Current());
2625 return GetReferenceTypeInfo().IsStringClass();
2626}
2627
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002628bool HInvoke::NeedsEnvironment() const {
2629 if (!IsIntrinsic()) {
2630 return true;
2631 }
2632 IntrinsicOptimizations opt(*this);
2633 return !opt.GetDoesNotNeedEnvironment();
2634}
2635
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002636const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2637 ArtMethod* caller = GetEnvironment()->GetMethod();
2638 ScopedObjectAccess soa(Thread::Current());
2639 // `caller` is null for a top-level graph representing a method whose declaring
2640 // class was not resolved.
2641 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2642}
2643
Vladimir Markodc151b22015-10-15 18:02:30 +01002644bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002645 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002646 return false;
2647 }
2648 if (!IsIntrinsic()) {
2649 return true;
2650 }
2651 IntrinsicOptimizations opt(*this);
2652 return !opt.GetDoesNotNeedDexCache();
2653}
2654
Vladimir Markof64242a2015-12-01 14:58:23 +00002655std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2656 switch (rhs) {
2657 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002658 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002659 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002660 return os << "Recursive";
2661 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2662 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002663 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002664 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002665 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2666 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002667 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2668 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002669 default:
2670 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2671 UNREACHABLE();
2672 }
2673}
2674
Vladimir Markofbb184a2015-11-13 14:47:00 +00002675std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2676 switch (rhs) {
2677 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2678 return os << "explicit";
2679 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2680 return os << "implicit";
2681 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2682 return os << "none";
2683 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002684 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2685 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002686 }
2687}
2688
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002689bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2690 const HLoadClass* other_load_class = other->AsLoadClass();
2691 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2692 // names rather than type indexes. However, we shall also have to re-think the hash code.
2693 if (type_index_ != other_load_class->type_index_ ||
2694 GetPackedFields() != other_load_class->GetPackedFields()) {
2695 return false;
2696 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002697 switch (GetLoadKind()) {
2698 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002699 case LoadKind::kJitTableAddress: {
2700 ScopedObjectAccess soa(Thread::Current());
2701 return GetClass().Get() == other_load_class->GetClass().Get();
2702 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002703 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002704 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002705 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002706 }
2707}
2708
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002709void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002710 SetPackedField<LoadKindField>(load_kind);
2711
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002712 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002713 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002714 RemoveAsUserOfInput(0u);
2715 SetRawInputAt(0u, nullptr);
2716 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002717
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002718 if (!NeedsEnvironment()) {
2719 RemoveEnvironment();
2720 SetSideEffects(SideEffects::None());
2721 }
2722}
2723
2724std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2725 switch (rhs) {
2726 case HLoadClass::LoadKind::kReferrersClass:
2727 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002728 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2729 return os << "BootImageLinkTimePcRelative";
2730 case HLoadClass::LoadKind::kBootImageAddress:
2731 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002732 case HLoadClass::LoadKind::kBssEntry:
2733 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002734 case HLoadClass::LoadKind::kJitTableAddress:
2735 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002736 case HLoadClass::LoadKind::kRuntimeCall:
2737 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002738 default:
2739 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2740 UNREACHABLE();
2741 }
2742}
2743
Vladimir Marko372f10e2016-05-17 16:30:10 +01002744bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2745 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002746 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2747 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002748 if (string_index_ != other_load_string->string_index_ ||
2749 GetPackedFields() != other_load_string->GetPackedFields()) {
2750 return false;
2751 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002752 switch (GetLoadKind()) {
2753 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002754 case LoadKind::kJitTableAddress: {
2755 ScopedObjectAccess soa(Thread::Current());
2756 return GetString().Get() == other_load_string->GetString().Get();
2757 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002758 default:
2759 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002760 }
2761}
2762
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002763void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002764 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002765 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002766 SetPackedField<LoadKindField>(load_kind);
2767
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002768 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002769 RemoveAsUserOfInput(0u);
2770 SetRawInputAt(0u, nullptr);
2771 }
2772 if (!NeedsEnvironment()) {
2773 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002774 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002775 }
2776}
2777
2778std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2779 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002780 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2781 return os << "BootImageLinkTimePcRelative";
2782 case HLoadString::LoadKind::kBootImageAddress:
2783 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002784 case HLoadString::LoadKind::kBssEntry:
2785 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002786 case HLoadString::LoadKind::kJitTableAddress:
2787 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002788 case HLoadString::LoadKind::kRuntimeCall:
2789 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002790 default:
2791 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2792 UNREACHABLE();
2793 }
2794}
2795
Mark Mendellc4701932015-04-10 13:18:51 -04002796void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002797 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2798 HEnvironment* user = use.GetUser();
2799 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002800 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002801 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002802}
2803
Roland Levillainc9b21f82016-03-23 16:36:59 +00002804// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002805HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2806 ArenaAllocator* allocator = GetArena();
2807
2808 if (cond->IsCondition() &&
2809 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2810 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2811 HInstruction* lhs = cond->InputAt(0);
2812 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002813 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002814 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2815 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2816 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2817 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2818 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2819 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2820 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2821 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2822 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2823 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2824 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002825 default:
2826 LOG(FATAL) << "Unexpected condition";
2827 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002828 }
2829 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2830 return replacement;
2831 } else if (cond->IsIntConstant()) {
2832 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002833 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002834 return GetIntConstant(1);
2835 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002836 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002837 return GetIntConstant(0);
2838 }
2839 } else {
2840 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2841 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2842 return replacement;
2843 }
2844}
2845
Roland Levillainc9285912015-12-18 10:38:42 +00002846std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2847 os << "["
2848 << " source=" << rhs.GetSource()
2849 << " destination=" << rhs.GetDestination()
2850 << " type=" << rhs.GetType()
2851 << " instruction=";
2852 if (rhs.GetInstruction() != nullptr) {
2853 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2854 } else {
2855 os << "null";
2856 }
2857 os << " ]";
2858 return os;
2859}
2860
Roland Levillain86503782016-02-11 19:07:30 +00002861std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2862 switch (rhs) {
2863 case TypeCheckKind::kUnresolvedCheck:
2864 return os << "unresolved_check";
2865 case TypeCheckKind::kExactCheck:
2866 return os << "exact_check";
2867 case TypeCheckKind::kClassHierarchyCheck:
2868 return os << "class_hierarchy_check";
2869 case TypeCheckKind::kAbstractClassCheck:
2870 return os << "abstract_class_check";
2871 case TypeCheckKind::kInterfaceCheck:
2872 return os << "interface_check";
2873 case TypeCheckKind::kArrayObjectCheck:
2874 return os << "array_object_check";
2875 case TypeCheckKind::kArrayCheck:
2876 return os << "array_check";
2877 default:
2878 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2879 UNREACHABLE();
2880 }
2881}
2882
Andreas Gampe26de38b2016-07-27 17:53:11 -07002883std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2884 switch (kind) {
2885 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002886 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002887 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002888 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002889 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002890 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002891 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002892 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002893 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002894 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002895
2896 default:
2897 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2898 UNREACHABLE();
2899 }
2900}
2901
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002902} // namespace art