blob: de4dc06251c649462aa0cca2ff7ca2137a6ae60c [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
Artem Serov21c7e6f2017-07-27 16:04:42 +010093// Remove the environment use records of the instruction for users.
94void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010095 for (HEnvironment* environment = instruction->GetEnvironment();
96 environment != nullptr;
97 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000099 if (environment->GetInstructionAt(i) != nullptr) {
100 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000101 }
102 }
103 }
104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Return whether the instruction has an environment and it's used by others.
107bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
112 HInstruction* user = environment->GetInstructionAt(i);
113 if (user != nullptr) {
114 return true;
115 }
116 }
117 }
118 return false;
119}
120
121// Reset environment records of the instruction itself.
122void ResetEnvironmentInputRecords(HInstruction* instruction) {
123 for (HEnvironment* environment = instruction->GetEnvironment();
124 environment != nullptr;
125 environment = environment->GetParent()) {
126 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
127 DCHECK(environment->GetHolder() == instruction);
128 if (environment->GetInstructionAt(i) != nullptr) {
129 environment->SetRawEnvAt(i, nullptr);
130 }
131 }
132 }
133}
134
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000135static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100136 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000137 RemoveEnvironmentUses(instruction);
138}
139
Roland Levillainfc600dc2014-12-02 17:16:31 +0000140void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100141 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000142 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100143 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100145 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
147 RemoveAsUser(it.Current());
148 }
149 }
150 }
151}
152
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100153void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000159 for (HBasicBlock* successor : block->GetSuccessors()) {
160 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000161 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // Remove the block from the list of blocks, so that further analyses
163 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600165 if (block->IsExitBlock()) {
166 SetExitBlock(nullptr);
167 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // Mark the block as removed. This is used by the HGraphBuilder to discard
169 // the block as a branch target.
170 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172 }
173}
174
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000176 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177
David Brazdil86ea7ee2016-02-16 09:26:07 +0000178 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 FindBackEdges(&visited);
180
David Brazdil86ea7ee2016-02-16 09:26:07 +0000181 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000182 // the initial DFS as users from other instructions, so that
183 // users can be safely removed before uses later.
184 RemoveInstructionsAsUsersFromDeadBlocks(visited);
185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 // predecessors list of live blocks.
189 RemoveDeadBlocks(visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 // dominators and the reverse post order.
193 SimplifyCFG();
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197
David Brazdil86ea7ee2016-02-16 09:26:07 +0000198 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000199 // set the loop information on each block.
200 GraphAnalysisResult result = AnalyzeLoops();
201 if (result != kAnalysisSuccess) {
202 return result;
203 }
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206 // which needs the information to build catch block phis from values of
207 // locals at throwing instructions inside try blocks.
208 ComputeTryBlockInformation();
209
210 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211}
212
213void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100214 for (HBasicBlock* block : GetReversePostOrder()) {
215 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100216 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100217 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100218}
219
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000220void HGraph::ClearLoopInformation() {
221 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000228 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229 dominator_ = nullptr;
230}
231
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000232HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
233 HInstruction* instruction = GetFirstInstruction();
234 while (instruction->IsParallelMove()) {
235 instruction = instruction->GetNext();
236 }
237 return instruction;
238}
239
David Brazdil3f4a5222016-05-06 12:46:21 +0100240static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
241 DCHECK(ContainsElement(block->GetSuccessors(), successor));
242
243 HBasicBlock* old_dominator = successor->GetDominator();
244 HBasicBlock* new_dominator =
245 (old_dominator == nullptr) ? block
246 : CommonDominator::ForPair(old_dominator, block);
247
248 if (old_dominator == new_dominator) {
249 return false;
250 } else {
251 successor->SetDominator(new_dominator);
252 return true;
253 }
254}
255
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100256void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100257 DCHECK(reverse_post_order_.empty());
258 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100259 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100260
261 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100262 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100263 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100264 ArenaVector<size_t> successors_visited(blocks_.size(),
265 0u,
266 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100267 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100268 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100269 constexpr size_t kDefaultWorklistSize = 8;
270 worklist.reserve(kDefaultWorklistSize);
271 worklist.push_back(entry_block_);
272
273 while (!worklist.empty()) {
274 HBasicBlock* current = worklist.back();
275 uint32_t current_id = current->GetBlockId();
276 if (successors_visited[current_id] == current->GetSuccessors().size()) {
277 worklist.pop_back();
278 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100280 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100281
282 // Once all the forward edges have been visited, we know the immediate
283 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100284 if (++visits[successor->GetBlockId()] ==
285 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100286 reverse_post_order_.push_back(successor);
287 worklist.push_back(successor);
288 }
289 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000290 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000291
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 // Check if the graph has back edges not dominated by their respective headers.
293 // If so, we need to update the dominators of those headers and recursively of
294 // their successors. We do that with a fix-point iteration over all blocks.
295 // The algorithm is guaranteed to terminate because it loops only if the sum
296 // of all dominator chains has decreased in the current iteration.
297 bool must_run_fix_point = false;
298 for (HBasicBlock* block : blocks_) {
299 if (block != nullptr &&
300 block->IsLoopHeader() &&
301 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
302 must_run_fix_point = true;
303 break;
304 }
305 }
306 if (must_run_fix_point) {
307 bool update_occurred = true;
308 while (update_occurred) {
309 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100310 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100311 for (HBasicBlock* successor : block->GetSuccessors()) {
312 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
313 }
314 }
315 }
316 }
317
318 // Make sure that there are no remaining blocks whose dominator information
319 // needs to be updated.
320 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100321 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100322 for (HBasicBlock* successor : block->GetSuccessors()) {
323 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
324 }
325 }
326 }
327
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000328 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000329 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100330 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000331 if (!block->IsEntryBlock()) {
332 block->GetDominator()->AddDominatedBlock(block);
333 }
334 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000335}
336
David Brazdilfc6a86a2015-06-26 10:33:45 +0000337HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000338 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
339 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000340 // Use `InsertBetween` to ensure the predecessor index and successor index of
341 // `block` and `successor` are preserved.
342 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000343 return new_block;
344}
345
346void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
347 // Insert a new node between `block` and `successor` to split the
348 // critical edge.
349 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600350 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100351 if (successor->IsLoopHeader()) {
352 // If we split at a back edge boundary, make the new block the back edge.
353 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000354 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355 info->RemoveBackEdge(block);
356 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100357 }
358 }
359}
360
Artem Serovc73ee372017-07-31 15:08:40 +0100361// Reorder phi inputs to match reordering of the block's predecessors.
362static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
363 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
364 HPhi* phi = it.Current()->AsPhi();
365 HInstruction* first_instr = phi->InputAt(first);
366 HInstruction* second_instr = phi->InputAt(second);
367 phi->ReplaceInput(first_instr, second);
368 phi->ReplaceInput(second_instr, first);
369 }
370}
371
372// Make sure that the first predecessor of a loop header is the incoming block.
373void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
374 DCHECK(header->IsLoopHeader());
375 HLoopInformation* info = header->GetLoopInformation();
376 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
377 HBasicBlock* to_swap = header->GetPredecessors()[0];
378 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
379 HBasicBlock* predecessor = header->GetPredecessors()[pred];
380 if (!info->IsBackEdge(*predecessor)) {
381 header->predecessors_[pred] = to_swap;
382 header->predecessors_[0] = predecessor;
383 FixPhisAfterPredecessorsReodering(header, 0, pred);
384 break;
385 }
386 }
387 }
388}
389
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100390void HGraph::SimplifyLoop(HBasicBlock* header) {
391 HLoopInformation* info = header->GetLoopInformation();
392
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100393 // Make sure the loop has only one pre header. This simplifies SSA building by having
394 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000395 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
396 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000397 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000398 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100399 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600401 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402
Vladimir Marko60584552015-09-03 13:35:12 +0000403 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100404 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100405 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100406 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100407 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100408 }
409 }
410 pre_header->AddSuccessor(header);
411 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100412
Artem Serovc73ee372017-07-31 15:08:40 +0100413 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100414
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100415 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000416 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
417 // Called from DeadBlockElimination. Update SuspendCheck pointer.
418 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100419 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420}
421
David Brazdilffee3d32015-07-06 11:48:53 +0100422void HGraph::ComputeTryBlockInformation() {
423 // Iterate in reverse post order to propagate try membership information from
424 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100425 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100426 if (block->IsEntryBlock() || block->IsCatchBlock()) {
427 // Catch blocks after simplification have only exceptional predecessors
428 // and hence are never in tries.
429 continue;
430 }
431
432 // Infer try membership from the first predecessor. Having simplified loops,
433 // the first predecessor can never be a back edge and therefore it must have
434 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100435 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100436 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100437 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000438 if (try_entry != nullptr &&
439 (block->GetTryCatchInformation() == nullptr ||
440 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
441 // We are either setting try block membership for the first time or it
442 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100443 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
444 }
David Brazdilffee3d32015-07-06 11:48:53 +0100445 }
446}
447
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000449// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100450 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000451 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100452 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
453 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
454 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
455 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100456 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000457 if (block->GetSuccessors().size() > 1) {
458 // Only split normal-flow edges. We cannot split exceptional edges as they
459 // are synthesized (approximate real control flow), and we do not need to
460 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000461 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
462 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
463 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100464 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000465 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000466 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
467 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000468 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000469 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000471 // SplitCriticalEdge could have invalidated the `normal_successors`
472 // ArrayRef. We must re-acquire it.
473 normal_successors = block->GetNormalSuccessors();
474 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
475 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100476 }
477 }
478 }
479 if (block->IsLoopHeader()) {
480 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000481 } else if (!block->IsEntryBlock() &&
482 block->GetFirstInstruction() != nullptr &&
483 block->GetFirstInstruction()->IsSuspendCheck()) {
484 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000485 // a loop got dismantled. Just remove the suspend check.
486 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100487 }
488 }
489}
490
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000491GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100492 // We iterate post order to ensure we visit inner loops before outer loops.
493 // `PopulateRecursive` needs this guarantee to know whether a natural loop
494 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100495 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100496 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100497 if (block->IsCatchBlock()) {
498 // TODO: Dealing with exceptional back edges could be tricky because
499 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000500 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100501 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000502 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100503 }
504 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000505 return kAnalysisSuccess;
506}
507
508void HLoopInformation::Dump(std::ostream& os) {
509 os << "header: " << header_->GetBlockId() << std::endl;
510 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
511 for (HBasicBlock* block : back_edges_) {
512 os << "back edge: " << block->GetBlockId() << std::endl;
513 }
514 for (HBasicBlock* block : header_->GetPredecessors()) {
515 os << "predecessor: " << block->GetBlockId() << std::endl;
516 }
517 for (uint32_t idx : blocks_.Indexes()) {
518 os << " in loop: " << idx << std::endl;
519 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100520}
521
David Brazdil8d5b8b22015-03-24 10:51:52 +0000522void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000523 // New constants are inserted before the SuspendCheck at the bottom of the
524 // entry block. Note that this method can be called from the graph builder and
525 // the entry block therefore may not end with SuspendCheck->Goto yet.
526 HInstruction* insert_before = nullptr;
527
528 HInstruction* gota = entry_block_->GetLastInstruction();
529 if (gota != nullptr && gota->IsGoto()) {
530 HInstruction* suspend_check = gota->GetPrevious();
531 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
532 insert_before = suspend_check;
533 } else {
534 insert_before = gota;
535 }
536 }
537
538 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000539 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000540 } else {
541 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000542 }
543}
544
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600545HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100546 // For simplicity, don't bother reviving the cached null constant if it is
547 // not null and not in a block. Otherwise, we need to clear the instruction
548 // id and/or any invariants the graph is assuming when adding new instructions.
549 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600550 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000551 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000553 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000554 if (kIsDebugBuild) {
555 ScopedObjectAccess soa(Thread::Current());
556 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
557 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000558 return cached_null_constant_;
559}
560
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100561HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100562 // For simplicity, don't bother reviving the cached current method if it is
563 // not null and not in a block. Otherwise, we need to clear the instruction
564 // id and/or any invariants the graph is assuming when adding new instructions.
565 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700566 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600567 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
568 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100569 if (entry_block_->GetFirstInstruction() == nullptr) {
570 entry_block_->AddInstruction(cached_current_method_);
571 } else {
572 entry_block_->InsertInstructionBefore(
573 cached_current_method_, entry_block_->GetFirstInstruction());
574 }
575 }
576 return cached_current_method_;
577}
578
Igor Murashkind01745e2017-04-05 16:40:31 -0700579const char* HGraph::GetMethodName() const {
580 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
581 return dex_file_.GetMethodName(method_id);
582}
583
584std::string HGraph::PrettyMethod(bool with_signature) const {
585 return dex_file_.PrettyMethod(method_idx_, with_signature);
586}
587
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600588HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000589 switch (type) {
590 case Primitive::Type::kPrimBoolean:
591 DCHECK(IsUint<1>(value));
592 FALLTHROUGH_INTENDED;
593 case Primitive::Type::kPrimByte:
594 case Primitive::Type::kPrimChar:
595 case Primitive::Type::kPrimShort:
596 case Primitive::Type::kPrimInt:
597 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600598 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000599
600 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600601 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000602
603 default:
604 LOG(FATAL) << "Unsupported constant type";
605 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000606 }
David Brazdil46e2a392015-03-16 17:31:52 +0000607}
608
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000609void HGraph::CacheFloatConstant(HFloatConstant* constant) {
610 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
611 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
612 cached_float_constants_.Overwrite(value, constant);
613}
614
615void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
616 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
617 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
618 cached_double_constants_.Overwrite(value, constant);
619}
620
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000621void HLoopInformation::Add(HBasicBlock* block) {
622 blocks_.SetBit(block->GetBlockId());
623}
624
David Brazdil46e2a392015-03-16 17:31:52 +0000625void HLoopInformation::Remove(HBasicBlock* block) {
626 blocks_.ClearBit(block->GetBlockId());
627}
628
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100629void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
630 if (blocks_.IsBitSet(block->GetBlockId())) {
631 return;
632 }
633
634 blocks_.SetBit(block->GetBlockId());
635 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100636 if (block->IsLoopHeader()) {
637 // We're visiting loops in post-order, so inner loops must have been
638 // populated already.
639 DCHECK(block->GetLoopInformation()->IsPopulated());
640 if (block->GetLoopInformation()->IsIrreducible()) {
641 contains_irreducible_loop_ = true;
642 }
643 }
Vladimir Marko60584552015-09-03 13:35:12 +0000644 for (HBasicBlock* predecessor : block->GetPredecessors()) {
645 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100646 }
647}
648
David Brazdilc2e8af92016-04-05 17:15:19 +0100649void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
650 size_t block_id = block->GetBlockId();
651
652 // If `block` is in `finalized`, we know its membership in the loop has been
653 // decided and it does not need to be revisited.
654 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 return;
656 }
657
David Brazdilc2e8af92016-04-05 17:15:19 +0100658 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000659 if (block->IsLoopHeader()) {
660 // If we hit a loop header in an irreducible loop, we first check if the
661 // pre header of that loop belongs to the currently analyzed loop. If it does,
662 // then we visit the back edges.
663 // Note that we cannot use GetPreHeader, as the loop may have not been populated
664 // yet.
665 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100666 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000667 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000668 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100669 blocks_.SetBit(block_id);
670 finalized->SetBit(block_id);
671 is_finalized = true;
672
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000673 HLoopInformation* info = block->GetLoopInformation();
674 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100675 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000676 }
677 }
678 } else {
679 // Visit all predecessors. If one predecessor is part of the loop, this
680 // block is also part of this loop.
681 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100682 PopulateIrreducibleRecursive(predecessor, finalized);
683 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000684 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100685 blocks_.SetBit(block_id);
686 finalized->SetBit(block_id);
687 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000688 }
689 }
690 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100691
692 // All predecessors have been recursively visited. Mark finalized if not marked yet.
693 if (!is_finalized) {
694 finalized->SetBit(block_id);
695 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000696}
697
698void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100699 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000700 // Populate this loop: starting with the back edge, recursively add predecessors
701 // that are not already part of that loop. Set the header as part of the loop
702 // to end the recursion.
703 // This is a recursive implementation of the algorithm described in
704 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100705 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000706 blocks_.SetBit(header_->GetBlockId());
707 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100708
David Brazdil3f4a5222016-05-06 12:46:21 +0100709 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100710
711 if (is_irreducible_loop) {
712 ArenaBitVector visited(graph->GetArena(),
713 graph->GetBlocks().size(),
714 /* expandable */ false,
715 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100716 // Stop marking blocks at the loop header.
717 visited.SetBit(header_->GetBlockId());
718
David Brazdilc2e8af92016-04-05 17:15:19 +0100719 for (HBasicBlock* back_edge : GetBackEdges()) {
720 PopulateIrreducibleRecursive(back_edge, &visited);
721 }
722 } else {
723 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000724 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100725 }
David Brazdila4b8c212015-05-07 09:59:30 +0100726 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100727
Vladimir Markofd66c502016-04-18 15:37:01 +0100728 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
729 // When compiling in OSR mode, all loops in the compiled method may be entered
730 // from the interpreter. We treat this OSR entry point just like an extra entry
731 // to an irreducible loop, so we need to mark the method's loops as irreducible.
732 // This does not apply to inlined loops which do not act as OSR entry points.
733 if (suspend_check_ == nullptr) {
734 // Just building the graph in OSR mode, this loop is not inlined. We never build an
735 // inner graph in OSR mode as we can do OSR transition only from the outer method.
736 is_irreducible_loop = true;
737 } else {
738 // Look at the suspend check's environment to determine if the loop was inlined.
739 DCHECK(suspend_check_->HasEnvironment());
740 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
741 is_irreducible_loop = true;
742 }
743 }
744 }
745 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100746 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100747 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100748 graph->SetHasIrreducibleLoops(true);
749 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800750 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100751}
752
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100753HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000754 HBasicBlock* block = header_->GetPredecessors()[0];
755 DCHECK(irreducible_ || (block == header_->GetDominator()));
756 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100757}
758
759bool HLoopInformation::Contains(const HBasicBlock& block) const {
760 return blocks_.IsBitSet(block.GetBlockId());
761}
762
763bool HLoopInformation::IsIn(const HLoopInformation& other) const {
764 return other.blocks_.IsBitSet(header_->GetBlockId());
765}
766
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800767bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
768 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700769}
770
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100771size_t HLoopInformation::GetLifetimeEnd() const {
772 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100773 for (HBasicBlock* back_edge : GetBackEdges()) {
774 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100775 }
776 return last_position;
777}
778
David Brazdil3f4a5222016-05-06 12:46:21 +0100779bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
780 for (HBasicBlock* back_edge : GetBackEdges()) {
781 DCHECK(back_edge->GetDominator() != nullptr);
782 if (!header_->Dominates(back_edge)) {
783 return true;
784 }
785 }
786 return false;
787}
788
Anton Shaminf89381f2016-05-16 16:44:13 +0600789bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
790 for (HBasicBlock* back_edge : GetBackEdges()) {
791 if (!block->Dominates(back_edge)) {
792 return false;
793 }
794 }
795 return true;
796}
797
David Sehrc757dec2016-11-04 15:48:34 -0700798
799bool HLoopInformation::HasExitEdge() const {
800 // Determine if this loop has at least one exit edge.
801 HBlocksInLoopReversePostOrderIterator it_loop(*this);
802 for (; !it_loop.Done(); it_loop.Advance()) {
803 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
804 if (!Contains(*successor)) {
805 return true;
806 }
807 }
808 }
809 return false;
810}
811
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100812bool HBasicBlock::Dominates(HBasicBlock* other) const {
813 // Walk up the dominator tree from `other`, to find out if `this`
814 // is an ancestor.
815 HBasicBlock* current = other;
816 while (current != nullptr) {
817 if (current == this) {
818 return true;
819 }
820 current = current->GetDominator();
821 }
822 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100823}
824
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100825static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100826 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100827 for (size_t i = 0; i < inputs.size(); ++i) {
828 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100829 }
830 // Environment should be created later.
831 DCHECK(!instruction->HasEnvironment());
832}
833
Roland Levillainccc07a92014-09-16 14:48:16 +0100834void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
835 HInstruction* replacement) {
836 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400837 if (initial->IsControlFlow()) {
838 // We can only replace a control flow instruction with another control flow instruction.
839 DCHECK(replacement->IsControlFlow());
840 DCHECK_EQ(replacement->GetId(), -1);
841 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
842 DCHECK_EQ(initial->GetBlock(), this);
843 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100844 DCHECK(initial->GetUses().empty());
845 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400846 replacement->SetBlock(this);
847 replacement->SetId(GetGraph()->GetNextInstructionId());
848 instructions_.InsertInstructionBefore(replacement, initial);
849 UpdateInputsUsers(replacement);
850 } else {
851 InsertInstructionBefore(replacement, initial);
852 initial->ReplaceWith(replacement);
853 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100854 RemoveInstruction(initial);
855}
856
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100857static void Add(HInstructionList* instruction_list,
858 HBasicBlock* block,
859 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000860 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000861 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100862 instruction->SetBlock(block);
863 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100864 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865 instruction_list->AddInstruction(instruction);
866}
867
868void HBasicBlock::AddInstruction(HInstruction* instruction) {
869 Add(&instructions_, this, instruction);
870}
871
872void HBasicBlock::AddPhi(HPhi* phi) {
873 Add(&phis_, this, phi);
874}
875
David Brazdilc3d743f2015-04-22 13:40:50 +0100876void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
877 DCHECK(!cursor->IsPhi());
878 DCHECK(!instruction->IsPhi());
879 DCHECK_EQ(instruction->GetId(), -1);
880 DCHECK_NE(cursor->GetId(), -1);
881 DCHECK_EQ(cursor->GetBlock(), this);
882 DCHECK(!instruction->IsControlFlow());
883 instruction->SetBlock(this);
884 instruction->SetId(GetGraph()->GetNextInstructionId());
885 UpdateInputsUsers(instruction);
886 instructions_.InsertInstructionBefore(instruction, cursor);
887}
888
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100889void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
890 DCHECK(!cursor->IsPhi());
891 DCHECK(!instruction->IsPhi());
892 DCHECK_EQ(instruction->GetId(), -1);
893 DCHECK_NE(cursor->GetId(), -1);
894 DCHECK_EQ(cursor->GetBlock(), this);
895 DCHECK(!instruction->IsControlFlow());
896 DCHECK(!cursor->IsControlFlow());
897 instruction->SetBlock(this);
898 instruction->SetId(GetGraph()->GetNextInstructionId());
899 UpdateInputsUsers(instruction);
900 instructions_.InsertInstructionAfter(instruction, cursor);
901}
902
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100903void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
904 DCHECK_EQ(phi->GetId(), -1);
905 DCHECK_NE(cursor->GetId(), -1);
906 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100907 phi->SetBlock(this);
908 phi->SetId(GetGraph()->GetNextInstructionId());
909 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100910 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100911}
912
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100913static void Remove(HInstructionList* instruction_list,
914 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000915 HInstruction* instruction,
916 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100917 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100918 instruction->SetBlock(nullptr);
919 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000920 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100921 DCHECK(instruction->GetUses().empty());
922 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000923 RemoveAsUser(instruction);
924 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100925}
926
David Brazdil1abb4192015-02-17 18:33:36 +0000927void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100928 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000929 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100930}
931
David Brazdil1abb4192015-02-17 18:33:36 +0000932void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
933 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934}
935
David Brazdilc7508e92015-04-27 13:28:57 +0100936void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
937 if (instruction->IsPhi()) {
938 RemovePhi(instruction->AsPhi(), ensure_safety);
939 } else {
940 RemoveInstruction(instruction, ensure_safety);
941 }
942}
943
Vladimir Marko71bf8092015-09-15 15:33:14 +0100944void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
945 for (size_t i = 0; i < locals.size(); i++) {
946 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100947 SetRawEnvAt(i, instruction);
948 if (instruction != nullptr) {
949 instruction->AddEnvUseAt(this, i);
950 }
951 }
952}
953
David Brazdiled596192015-01-23 10:39:45 +0000954void HEnvironment::CopyFrom(HEnvironment* env) {
955 for (size_t i = 0; i < env->Size(); i++) {
956 HInstruction* instruction = env->GetInstructionAt(i);
957 SetRawEnvAt(i, instruction);
958 if (instruction != nullptr) {
959 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100960 }
David Brazdiled596192015-01-23 10:39:45 +0000961 }
962}
963
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700964void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
965 HBasicBlock* loop_header) {
966 DCHECK(loop_header->IsLoopHeader());
967 for (size_t i = 0; i < env->Size(); i++) {
968 HInstruction* instruction = env->GetInstructionAt(i);
969 SetRawEnvAt(i, instruction);
970 if (instruction == nullptr) {
971 continue;
972 }
973 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
974 // At the end of the loop pre-header, the corresponding value for instruction
975 // is the first input of the phi.
976 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700977 SetRawEnvAt(i, initial);
978 initial->AddEnvUseAt(this, i);
979 } else {
980 instruction->AddEnvUseAt(this, i);
981 }
982 }
983}
984
David Brazdil1abb4192015-02-17 18:33:36 +0000985void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100986 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
987 HInstruction* user = env_use.GetInstruction();
988 auto before_env_use_node = env_use.GetBeforeUseNode();
989 user->env_uses_.erase_after(before_env_use_node);
990 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100991}
992
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000993HInstruction::InstructionKind HInstruction::GetKind() const {
994 return GetKindInternal();
995}
996
Calin Juravle77520bc2015-01-12 18:45:46 +0000997HInstruction* HInstruction::GetNextDisregardingMoves() const {
998 HInstruction* next = GetNext();
999 while (next != nullptr && next->IsParallelMove()) {
1000 next = next->GetNext();
1001 }
1002 return next;
1003}
1004
1005HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1006 HInstruction* previous = GetPrevious();
1007 while (previous != nullptr && previous->IsParallelMove()) {
1008 previous = previous->GetPrevious();
1009 }
1010 return previous;
1011}
1012
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001013void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001014 if (first_instruction_ == nullptr) {
1015 DCHECK(last_instruction_ == nullptr);
1016 first_instruction_ = last_instruction_ = instruction;
1017 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001018 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001019 last_instruction_->next_ = instruction;
1020 instruction->previous_ = last_instruction_;
1021 last_instruction_ = instruction;
1022 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001023}
1024
David Brazdilc3d743f2015-04-22 13:40:50 +01001025void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1026 DCHECK(Contains(cursor));
1027 if (cursor == first_instruction_) {
1028 cursor->previous_ = instruction;
1029 instruction->next_ = cursor;
1030 first_instruction_ = instruction;
1031 } else {
1032 instruction->previous_ = cursor->previous_;
1033 instruction->next_ = cursor;
1034 cursor->previous_ = instruction;
1035 instruction->previous_->next_ = instruction;
1036 }
1037}
1038
1039void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1040 DCHECK(Contains(cursor));
1041 if (cursor == last_instruction_) {
1042 cursor->next_ = instruction;
1043 instruction->previous_ = cursor;
1044 last_instruction_ = instruction;
1045 } else {
1046 instruction->next_ = cursor->next_;
1047 instruction->previous_ = cursor;
1048 cursor->next_ = instruction;
1049 instruction->next_->previous_ = instruction;
1050 }
1051}
1052
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001053void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1054 if (instruction->previous_ != nullptr) {
1055 instruction->previous_->next_ = instruction->next_;
1056 }
1057 if (instruction->next_ != nullptr) {
1058 instruction->next_->previous_ = instruction->previous_;
1059 }
1060 if (instruction == first_instruction_) {
1061 first_instruction_ = instruction->next_;
1062 }
1063 if (instruction == last_instruction_) {
1064 last_instruction_ = instruction->previous_;
1065 }
1066}
1067
Roland Levillain6b469232014-09-25 10:10:38 +01001068bool HInstructionList::Contains(HInstruction* instruction) const {
1069 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1070 if (it.Current() == instruction) {
1071 return true;
1072 }
1073 }
1074 return false;
1075}
1076
Roland Levillainccc07a92014-09-16 14:48:16 +01001077bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1078 const HInstruction* instruction2) const {
1079 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1080 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1081 if (it.Current() == instruction1) {
1082 return true;
1083 }
1084 if (it.Current() == instruction2) {
1085 return false;
1086 }
1087 }
1088 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1089 return true;
1090}
1091
Roland Levillain6c82d402014-10-13 16:10:27 +01001092bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1093 if (other_instruction == this) {
1094 // An instruction does not strictly dominate itself.
1095 return false;
1096 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001097 HBasicBlock* block = GetBlock();
1098 HBasicBlock* other_block = other_instruction->GetBlock();
1099 if (block != other_block) {
1100 return GetBlock()->Dominates(other_instruction->GetBlock());
1101 } else {
1102 // If both instructions are in the same block, ensure this
1103 // instruction comes before `other_instruction`.
1104 if (IsPhi()) {
1105 if (!other_instruction->IsPhi()) {
1106 // Phis appear before non phi-instructions so this instruction
1107 // dominates `other_instruction`.
1108 return true;
1109 } else {
1110 // There is no order among phis.
1111 LOG(FATAL) << "There is no dominance between phis of a same block.";
1112 return false;
1113 }
1114 } else {
1115 // `this` is not a phi.
1116 if (other_instruction->IsPhi()) {
1117 // Phis appear before non phi-instructions so this instruction
1118 // does not dominate `other_instruction`.
1119 return false;
1120 } else {
1121 // Check whether this instruction comes before
1122 // `other_instruction` in the instruction list.
1123 return block->GetInstructions().FoundBefore(this, other_instruction);
1124 }
1125 }
1126 }
1127}
1128
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001129void HInstruction::RemoveEnvironment() {
1130 RemoveEnvironmentUses(this);
1131 environment_ = nullptr;
1132}
1133
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001134void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001135 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001136 // Note: fixup_end remains valid across splice_after().
1137 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1138 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1139 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001140
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001141 // Note: env_fixup_end remains valid across splice_after().
1142 auto env_fixup_end =
1143 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1144 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1145 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001146
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001147 DCHECK(uses_.empty());
1148 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001149}
1150
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001151void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1152 const HUseList<HInstruction*>& uses = GetUses();
1153 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1154 HInstruction* user = it->GetUser();
1155 size_t index = it->GetIndex();
1156 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1157 ++it;
1158 if (dominator->StrictlyDominates(user)) {
1159 user->ReplaceInput(replacement, index);
1160 }
1161 }
1162}
1163
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001164void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001165 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001166 if (input_use.GetInstruction() == replacement) {
1167 // Nothing to do.
1168 return;
1169 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001170 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001171 // Note: fixup_end remains valid across splice_after().
1172 auto fixup_end =
1173 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1174 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1175 input_use.GetInstruction()->uses_,
1176 before_use_node);
1177 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1178 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001179}
1180
Nicolas Geoffray39468442014-09-02 15:17:15 +01001181size_t HInstruction::EnvironmentSize() const {
1182 return HasEnvironment() ? environment_->Size() : 0;
1183}
1184
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001185void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001186 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001187 inputs_.push_back(HUserRecord<HInstruction*>(input));
1188 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001189}
1190
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001191void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1192 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1193 input->AddUseAt(this, index);
1194 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1195 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1196 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1197 inputs_[i].GetUseNode()->SetIndex(i);
1198 }
1199}
1200
1201void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001202 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001203 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001204 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1205 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1206 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1207 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001208 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001209}
1210
Igor Murashkind01745e2017-04-05 16:40:31 -07001211void HVariableInputSizeInstruction::RemoveAllInputs() {
1212 RemoveAsUserOfAllInputs();
1213 DCHECK(!HasNonEnvironmentUses());
1214
1215 inputs_.clear();
1216 DCHECK_EQ(0u, InputCount());
1217}
1218
1219void HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
1220 DCHECK(instruction->GetBlock() != nullptr);
1221 // Removing constructor fences only makes sense for instructions with an object return type.
1222 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1223
1224 // Efficient implementation that simultaneously (in one pass):
1225 // * Scans the uses list for all constructor fences.
1226 // * Deletes that constructor fence from the uses list of `instruction`.
1227 // * Deletes `instruction` from the constructor fence's inputs.
1228 // * Deletes the constructor fence if it now has 0 inputs.
1229
1230 const HUseList<HInstruction*>& uses = instruction->GetUses();
1231 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1232 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1233 const HUseListNode<HInstruction*>& use_node = *it;
1234 HInstruction* const use_instruction = use_node.GetUser();
1235
1236 // Advance the iterator immediately once we fetch the use_node.
1237 // Warning: If the input is removed, the current iterator becomes invalid.
1238 ++it;
1239
1240 if (use_instruction->IsConstructorFence()) {
1241 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1242 size_t input_index = use_node.GetIndex();
1243
1244 // Process the candidate instruction for removal
1245 // from the graph.
1246
1247 // Constructor fence instructions are never
1248 // used by other instructions.
1249 //
1250 // If we wanted to make this more generic, it
1251 // could be a runtime if statement.
1252 DCHECK(!ctor_fence->HasUses());
1253
1254 // A constructor fence's return type is "kPrimVoid"
1255 // and therefore it can't have any environment uses.
1256 DCHECK(!ctor_fence->HasEnvironmentUses());
1257
1258 // Remove the inputs first, otherwise removing the instruction
1259 // will try to remove its uses while we are already removing uses
1260 // and this operation will fail.
1261 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1262
1263 // Removing the input will also remove the `use_node`.
1264 // (Do not look at `use_node` after this, it will be a dangling reference).
1265 ctor_fence->RemoveInputAt(input_index);
1266
1267 // Once all inputs are removed, the fence is considered dead and
1268 // is removed.
1269 if (ctor_fence->InputCount() == 0u) {
1270 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
1271 }
1272 }
1273 }
1274
1275 if (kIsDebugBuild) {
1276 // Post-condition checks:
1277 // * None of the uses of `instruction` are a constructor fence.
1278 // * The `instruction` itself did not get removed from a block.
1279 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1280 CHECK(!use_node.GetUser()->IsConstructorFence());
1281 }
1282 CHECK(instruction->GetBlock() != nullptr);
1283 }
1284}
1285
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001286HInstruction* HConstructorFence::GetAssociatedAllocation() {
1287 HInstruction* new_instance_inst = GetPrevious();
1288 // Check if the immediately preceding instruction is a new-instance/new-array.
1289 // Otherwise this fence is for protecting final fields.
1290 if (new_instance_inst != nullptr &&
1291 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1292 // TODO: Need to update this code to handle multiple inputs.
1293 DCHECK_EQ(InputCount(), 1u);
1294 return new_instance_inst;
1295 } else {
1296 return nullptr;
1297 }
1298}
1299
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001300#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001301void H##name::Accept(HGraphVisitor* visitor) { \
1302 visitor->Visit##name(this); \
1303}
1304
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001305FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001306
1307#undef DEFINE_ACCEPT
1308
1309void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001310 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1311 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001312 if (block != nullptr) {
1313 VisitBasicBlock(block);
1314 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001315 }
1316}
1317
Roland Levillain633021e2014-10-01 14:12:25 +01001318void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001319 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1320 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001321 }
1322}
1323
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001324void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001325 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001326 it.Current()->Accept(this);
1327 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001328 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001329 it.Current()->Accept(this);
1330 }
1331}
1332
Mark Mendelle82549b2015-05-06 10:55:34 -04001333HConstant* HTypeConversion::TryStaticEvaluation() const {
1334 HGraph* graph = GetBlock()->GetGraph();
1335 if (GetInput()->IsIntConstant()) {
1336 int32_t value = GetInput()->AsIntConstant()->GetValue();
1337 switch (GetResultType()) {
1338 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001339 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001340 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001341 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001342 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001343 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001344 default:
1345 return nullptr;
1346 }
1347 } else if (GetInput()->IsLongConstant()) {
1348 int64_t value = GetInput()->AsLongConstant()->GetValue();
1349 switch (GetResultType()) {
1350 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001351 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001352 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001353 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001354 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001355 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001356 default:
1357 return nullptr;
1358 }
1359 } else if (GetInput()->IsFloatConstant()) {
1360 float value = GetInput()->AsFloatConstant()->GetValue();
1361 switch (GetResultType()) {
1362 case Primitive::kPrimInt:
1363 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001364 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001365 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001366 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001367 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001368 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1369 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001370 case Primitive::kPrimLong:
1371 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001372 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001373 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001374 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001375 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001376 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1377 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001378 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001379 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001380 default:
1381 return nullptr;
1382 }
1383 } else if (GetInput()->IsDoubleConstant()) {
1384 double value = GetInput()->AsDoubleConstant()->GetValue();
1385 switch (GetResultType()) {
1386 case Primitive::kPrimInt:
1387 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001388 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001389 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001390 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001391 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001392 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1393 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001394 case Primitive::kPrimLong:
1395 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001396 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001397 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001398 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001399 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001400 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1401 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001402 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001403 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001404 default:
1405 return nullptr;
1406 }
1407 }
1408 return nullptr;
1409}
1410
Roland Levillain9240d6a2014-10-20 16:47:04 +01001411HConstant* HUnaryOperation::TryStaticEvaluation() const {
1412 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001413 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001414 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001415 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001416 } else if (kEnableFloatingPointStaticEvaluation) {
1417 if (GetInput()->IsFloatConstant()) {
1418 return Evaluate(GetInput()->AsFloatConstant());
1419 } else if (GetInput()->IsDoubleConstant()) {
1420 return Evaluate(GetInput()->AsDoubleConstant());
1421 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001422 }
1423 return nullptr;
1424}
1425
1426HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001427 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1428 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001429 } else if (GetLeft()->IsLongConstant()) {
1430 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001431 // The binop(long, int) case is only valid for shifts and rotations.
1432 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001433 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1434 } else if (GetRight()->IsLongConstant()) {
1435 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001436 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001437 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001438 // The binop(null, null) case is only valid for equal and not-equal conditions.
1439 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001440 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001441 } else if (kEnableFloatingPointStaticEvaluation) {
1442 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1443 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1444 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1445 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1446 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001447 }
1448 return nullptr;
1449}
Dave Allison20dfc792014-06-16 20:44:29 -07001450
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001451HConstant* HBinaryOperation::GetConstantRight() const {
1452 if (GetRight()->IsConstant()) {
1453 return GetRight()->AsConstant();
1454 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1455 return GetLeft()->AsConstant();
1456 } else {
1457 return nullptr;
1458 }
1459}
1460
1461// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001462// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001463HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1464 HInstruction* most_constant_right = GetConstantRight();
1465 if (most_constant_right == nullptr) {
1466 return nullptr;
1467 } else if (most_constant_right == GetLeft()) {
1468 return GetRight();
1469 } else {
1470 return GetLeft();
1471 }
1472}
1473
Roland Levillain31dd3d62016-02-16 12:21:02 +00001474std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1475 switch (rhs) {
1476 case ComparisonBias::kNoBias:
1477 return os << "no_bias";
1478 case ComparisonBias::kGtBias:
1479 return os << "gt_bias";
1480 case ComparisonBias::kLtBias:
1481 return os << "lt_bias";
1482 default:
1483 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1484 UNREACHABLE();
1485 }
1486}
1487
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001488bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1489 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001490}
1491
Vladimir Marko372f10e2016-05-17 16:30:10 +01001492bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001493 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001494 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001495 if (!InstructionDataEquals(other)) return false;
1496 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001497 HConstInputsRef inputs = GetInputs();
1498 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001499 if (inputs.size() != other_inputs.size()) return false;
1500 for (size_t i = 0; i != inputs.size(); ++i) {
1501 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001502 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001503
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001504 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001505 return true;
1506}
1507
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001508std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1509#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1510 switch (rhs) {
1511 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1512 default:
1513 os << "Unknown instruction kind " << static_cast<int>(rhs);
1514 break;
1515 }
1516#undef DECLARE_CASE
1517 return os;
1518}
1519
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001520void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1521 if (do_checks) {
1522 DCHECK(!IsPhi());
1523 DCHECK(!IsControlFlow());
1524 DCHECK(CanBeMoved() ||
1525 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1526 IsShouldDeoptimizeFlag());
1527 DCHECK(!cursor->IsPhi());
1528 }
David Brazdild6c205e2016-06-07 14:20:52 +01001529
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001530 next_->previous_ = previous_;
1531 if (previous_ != nullptr) {
1532 previous_->next_ = next_;
1533 }
1534 if (block_->instructions_.first_instruction_ == this) {
1535 block_->instructions_.first_instruction_ = next_;
1536 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001537 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001538
1539 previous_ = cursor->previous_;
1540 if (previous_ != nullptr) {
1541 previous_->next_ = this;
1542 }
1543 next_ = cursor;
1544 cursor->previous_ = this;
1545 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001546
1547 if (block_->instructions_.first_instruction_ == cursor) {
1548 block_->instructions_.first_instruction_ = this;
1549 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001550}
1551
Vladimir Markofb337ea2015-11-25 15:25:10 +00001552void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1553 DCHECK(!CanThrow());
1554 DCHECK(!HasSideEffects());
1555 DCHECK(!HasEnvironmentUses());
1556 DCHECK(HasNonEnvironmentUses());
1557 DCHECK(!IsPhi()); // Makes no sense for Phi.
1558 DCHECK_EQ(InputCount(), 0u);
1559
1560 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001561 auto uses_it = GetUses().begin();
1562 auto uses_end = GetUses().end();
1563 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1564 ++uses_it;
1565 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1566 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001567 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001568 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001569 // This instruction has uses in two or more blocks. Find the common dominator.
1570 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001571 for (; uses_it != uses_end; ++uses_it) {
1572 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001573 }
1574 target_block = finder.Get();
1575 DCHECK(target_block != nullptr);
1576 }
1577 // Move to the first dominator not in a loop.
1578 while (target_block->IsInLoop()) {
1579 target_block = target_block->GetDominator();
1580 DCHECK(target_block != nullptr);
1581 }
1582
1583 // Find insertion position.
1584 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001585 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1586 if (use.GetUser()->GetBlock() == target_block &&
1587 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1588 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001589 }
1590 }
1591 if (insert_pos == nullptr) {
1592 // No user in `target_block`, insert before the control flow instruction.
1593 insert_pos = target_block->GetLastInstruction();
1594 DCHECK(insert_pos->IsControlFlow());
1595 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1596 if (insert_pos->IsIf()) {
1597 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1598 if (if_input == insert_pos->GetPrevious()) {
1599 insert_pos = if_input;
1600 }
1601 }
1602 }
1603 MoveBefore(insert_pos);
1604}
1605
David Brazdilfc6a86a2015-06-26 10:33:45 +00001606HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001607 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001608 DCHECK_EQ(cursor->GetBlock(), this);
1609
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001610 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1611 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001612 new_block->instructions_.first_instruction_ = cursor;
1613 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1614 instructions_.last_instruction_ = cursor->previous_;
1615 if (cursor->previous_ == nullptr) {
1616 instructions_.first_instruction_ = nullptr;
1617 } else {
1618 cursor->previous_->next_ = nullptr;
1619 cursor->previous_ = nullptr;
1620 }
1621
1622 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001623 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001624
Vladimir Marko60584552015-09-03 13:35:12 +00001625 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001626 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001627 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001628 new_block->successors_.swap(successors_);
1629 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001630 AddSuccessor(new_block);
1631
David Brazdil56e1acc2015-06-30 15:41:36 +01001632 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001633 return new_block;
1634}
1635
David Brazdild7558da2015-09-22 13:04:14 +01001636HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001637 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001638 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1639
1640 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1641
1642 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001643 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1644 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001645 new_block->predecessors_.swap(predecessors_);
1646 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001647 AddPredecessor(new_block);
1648
1649 GetGraph()->AddBlock(new_block);
1650 return new_block;
1651}
1652
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001653HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1654 DCHECK_EQ(cursor->GetBlock(), this);
1655
1656 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1657 cursor->GetDexPc());
1658 new_block->instructions_.first_instruction_ = cursor;
1659 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1660 instructions_.last_instruction_ = cursor->previous_;
1661 if (cursor->previous_ == nullptr) {
1662 instructions_.first_instruction_ = nullptr;
1663 } else {
1664 cursor->previous_->next_ = nullptr;
1665 cursor->previous_ = nullptr;
1666 }
1667
1668 new_block->instructions_.SetBlockOfInstructions(new_block);
1669
1670 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001671 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1672 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001673 new_block->successors_.swap(successors_);
1674 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001675
1676 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1677 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001678 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001679 new_block->dominated_blocks_.swap(dominated_blocks_);
1680 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001681 return new_block;
1682}
1683
1684HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001685 DCHECK(!cursor->IsControlFlow());
1686 DCHECK_NE(instructions_.last_instruction_, cursor);
1687 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001688
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001689 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1690 new_block->instructions_.first_instruction_ = cursor->GetNext();
1691 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1692 cursor->next_->previous_ = nullptr;
1693 cursor->next_ = nullptr;
1694 instructions_.last_instruction_ = cursor;
1695
1696 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001697 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001698 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001699 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001700 new_block->successors_.swap(successors_);
1701 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001702
Vladimir Marko60584552015-09-03 13:35:12 +00001703 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001704 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001705 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001706 new_block->dominated_blocks_.swap(dominated_blocks_);
1707 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001708 return new_block;
1709}
1710
David Brazdilec16f792015-08-19 15:04:01 +01001711const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001712 if (EndsWithTryBoundary()) {
1713 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1714 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001715 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001716 return try_boundary;
1717 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001718 DCHECK(IsTryBlock());
1719 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001720 return nullptr;
1721 }
David Brazdilec16f792015-08-19 15:04:01 +01001722 } else if (IsTryBlock()) {
1723 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001724 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001725 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001726 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001727}
1728
David Brazdild7558da2015-09-22 13:04:14 +01001729bool HBasicBlock::HasThrowingInstructions() const {
1730 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1731 if (it.Current()->CanThrow()) {
1732 return true;
1733 }
1734 }
1735 return false;
1736}
1737
David Brazdilfc6a86a2015-06-26 10:33:45 +00001738static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1739 return block.GetPhis().IsEmpty()
1740 && !block.GetInstructions().IsEmpty()
1741 && block.GetFirstInstruction() == block.GetLastInstruction();
1742}
1743
David Brazdil46e2a392015-03-16 17:31:52 +00001744bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001745 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1746}
1747
Mads Ager16e52892017-07-14 13:11:37 +02001748bool HBasicBlock::IsSingleReturn() const {
1749 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1750}
1751
David Brazdilfc6a86a2015-06-26 10:33:45 +00001752bool HBasicBlock::IsSingleTryBoundary() const {
1753 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001754}
1755
David Brazdil8d5b8b22015-03-24 10:51:52 +00001756bool HBasicBlock::EndsWithControlFlowInstruction() const {
1757 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1758}
1759
David Brazdilb2bd1c52015-03-25 11:17:37 +00001760bool HBasicBlock::EndsWithIf() const {
1761 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1762}
1763
David Brazdilffee3d32015-07-06 11:48:53 +01001764bool HBasicBlock::EndsWithTryBoundary() const {
1765 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1766}
1767
David Brazdilb2bd1c52015-03-25 11:17:37 +00001768bool HBasicBlock::HasSinglePhi() const {
1769 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1770}
1771
David Brazdild26a4112015-11-10 11:07:31 +00001772ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1773 if (EndsWithTryBoundary()) {
1774 // The normal-flow successor of HTryBoundary is always stored at index zero.
1775 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1776 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1777 } else {
1778 // All successors of blocks not ending with TryBoundary are normal.
1779 return ArrayRef<HBasicBlock* const>(successors_);
1780 }
1781}
1782
1783ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1784 if (EndsWithTryBoundary()) {
1785 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1786 } else {
1787 // Blocks not ending with TryBoundary do not have exceptional successors.
1788 return ArrayRef<HBasicBlock* const>();
1789 }
1790}
1791
David Brazdilffee3d32015-07-06 11:48:53 +01001792bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001793 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1794 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1795
1796 size_t length = handlers1.size();
1797 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001798 return false;
1799 }
1800
David Brazdilb618ade2015-07-29 10:31:29 +01001801 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001802 for (size_t i = 0; i < length; ++i) {
1803 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001804 return false;
1805 }
1806 }
1807 return true;
1808}
1809
David Brazdil2d7352b2015-04-20 14:52:42 +01001810size_t HInstructionList::CountSize() const {
1811 size_t size = 0;
1812 HInstruction* current = first_instruction_;
1813 for (; current != nullptr; current = current->GetNext()) {
1814 size++;
1815 }
1816 return size;
1817}
1818
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001819void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1820 for (HInstruction* current = first_instruction_;
1821 current != nullptr;
1822 current = current->GetNext()) {
1823 current->SetBlock(block);
1824 }
1825}
1826
1827void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1828 DCHECK(Contains(cursor));
1829 if (!instruction_list.IsEmpty()) {
1830 if (cursor == last_instruction_) {
1831 last_instruction_ = instruction_list.last_instruction_;
1832 } else {
1833 cursor->next_->previous_ = instruction_list.last_instruction_;
1834 }
1835 instruction_list.last_instruction_->next_ = cursor->next_;
1836 cursor->next_ = instruction_list.first_instruction_;
1837 instruction_list.first_instruction_->previous_ = cursor;
1838 }
1839}
1840
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001841void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1842 DCHECK(Contains(cursor));
1843 if (!instruction_list.IsEmpty()) {
1844 if (cursor == first_instruction_) {
1845 first_instruction_ = instruction_list.first_instruction_;
1846 } else {
1847 cursor->previous_->next_ = instruction_list.first_instruction_;
1848 }
1849 instruction_list.last_instruction_->next_ = cursor;
1850 instruction_list.first_instruction_->previous_ = cursor->previous_;
1851 cursor->previous_ = instruction_list.last_instruction_;
1852 }
1853}
1854
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001855void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001856 if (IsEmpty()) {
1857 first_instruction_ = instruction_list.first_instruction_;
1858 last_instruction_ = instruction_list.last_instruction_;
1859 } else {
1860 AddAfter(last_instruction_, instruction_list);
1861 }
1862}
1863
David Brazdil04ff4e82015-12-10 13:54:52 +00001864// Should be called on instructions in a dead block in post order. This method
1865// assumes `insn` has been removed from all users with the exception of catch
1866// phis because of missing exceptional edges in the graph. It removes the
1867// instruction from catch phi uses, together with inputs of other catch phis in
1868// the catch block at the same index, as these must be dead too.
1869static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1870 DCHECK(!insn->HasEnvironmentUses());
1871 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001872 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1873 size_t use_index = use.GetIndex();
1874 HBasicBlock* user_block = use.GetUser()->GetBlock();
1875 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001876 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1877 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1878 }
1879 }
1880}
1881
David Brazdil2d7352b2015-04-20 14:52:42 +01001882void HBasicBlock::DisconnectAndDelete() {
1883 // Dominators must be removed after all the blocks they dominate. This way
1884 // a loop header is removed last, a requirement for correct loop information
1885 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001886 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001887
David Brazdil9eeebf62016-03-24 11:18:15 +00001888 // The following steps gradually remove the block from all its dependants in
1889 // post order (b/27683071).
1890
1891 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1892 // We need to do this before step (4) which destroys the predecessor list.
1893 HBasicBlock* loop_update_start = this;
1894 if (IsLoopHeader()) {
1895 HLoopInformation* loop_info = GetLoopInformation();
1896 // All other blocks in this loop should have been removed because the header
1897 // was their dominator.
1898 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1899 DCHECK(!loop_info->IsIrreducible());
1900 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1901 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1902 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001903 }
1904
David Brazdil9eeebf62016-03-24 11:18:15 +00001905 // (2) Disconnect the block from its successors and update their phis.
1906 for (HBasicBlock* successor : successors_) {
1907 // Delete this block from the list of predecessors.
1908 size_t this_index = successor->GetPredecessorIndexOf(this);
1909 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1910
1911 // Check that `successor` has other predecessors, otherwise `this` is the
1912 // dominator of `successor` which violates the order DCHECKed at the top.
1913 DCHECK(!successor->predecessors_.empty());
1914
1915 // Remove this block's entries in the successor's phis. Skip exceptional
1916 // successors because catch phi inputs do not correspond to predecessor
1917 // blocks but throwing instructions. The inputs of the catch phis will be
1918 // updated in step (3).
1919 if (!successor->IsCatchBlock()) {
1920 if (successor->predecessors_.size() == 1u) {
1921 // The successor has just one predecessor left. Replace phis with the only
1922 // remaining input.
1923 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1924 HPhi* phi = phi_it.Current()->AsPhi();
1925 phi->ReplaceWith(phi->InputAt(1 - this_index));
1926 successor->RemovePhi(phi);
1927 }
1928 } else {
1929 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1930 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1931 }
1932 }
1933 }
1934 }
1935 successors_.clear();
1936
1937 // (3) Remove instructions and phis. Instructions should have no remaining uses
1938 // except in catch phis. If an instruction is used by a catch phi at `index`,
1939 // remove `index`-th input of all phis in the catch block since they are
1940 // guaranteed dead. Note that we may miss dead inputs this way but the
1941 // graph will always remain consistent.
1942 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1943 HInstruction* insn = it.Current();
1944 RemoveUsesOfDeadInstruction(insn);
1945 RemoveInstruction(insn);
1946 }
1947 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1948 HPhi* insn = it.Current()->AsPhi();
1949 RemoveUsesOfDeadInstruction(insn);
1950 RemovePhi(insn);
1951 }
1952
1953 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001954 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001955 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001956 // We should not see any back edges as they would have been removed by step (3).
1957 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1958
David Brazdil2d7352b2015-04-20 14:52:42 +01001959 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001960 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1961 // This block is the only normal-flow successor of the TryBoundary which
1962 // makes `predecessor` dead. Since DCE removes blocks in post order,
1963 // exception handlers of this TryBoundary were already visited and any
1964 // remaining handlers therefore must be live. We remove `predecessor` from
1965 // their list of predecessors.
1966 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1967 while (predecessor->GetSuccessors().size() > 1) {
1968 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1969 DCHECK(handler->IsCatchBlock());
1970 predecessor->RemoveSuccessor(handler);
1971 handler->RemovePredecessor(predecessor);
1972 }
1973 }
1974
David Brazdil2d7352b2015-04-20 14:52:42 +01001975 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001976 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1977 if (num_pred_successors == 1u) {
1978 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001979 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1980 // successor. Replace those with a HGoto.
1981 DCHECK(last_instruction->IsIf() ||
1982 last_instruction->IsPackedSwitch() ||
1983 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001984 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001985 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001986 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001987 // The predecessor has no remaining successors and therefore must be dead.
1988 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001989 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001990 predecessor->RemoveInstruction(last_instruction);
1991 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001992 // There are multiple successors left. The removed block might be a successor
1993 // of a PackedSwitch which will be completely removed (perhaps replaced with
1994 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1995 // case, leave `last_instruction` as is for now.
1996 DCHECK(last_instruction->IsPackedSwitch() ||
1997 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001998 }
David Brazdil46e2a392015-03-16 17:31:52 +00001999 }
Vladimir Marko60584552015-09-03 13:35:12 +00002000 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002001
David Brazdil9eeebf62016-03-24 11:18:15 +00002002 // (5) Remove the block from all loops it is included in. Skip the inner-most
2003 // loop if this is the loop header (see definition of `loop_update_start`)
2004 // because the loop header's predecessor list has been destroyed in step (4).
2005 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2006 HLoopInformation* loop_info = it.Current();
2007 loop_info->Remove(this);
2008 if (loop_info->IsBackEdge(*this)) {
2009 // If this was the last back edge of the loop, we deliberately leave the
2010 // loop in an inconsistent state and will fail GraphChecker unless the
2011 // entire loop is removed during the pass.
2012 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002013 }
2014 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002015
David Brazdil9eeebf62016-03-24 11:18:15 +00002016 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002017 dominator_->RemoveDominatedBlock(this);
2018 SetDominator(nullptr);
2019
David Brazdil9eeebf62016-03-24 11:18:15 +00002020 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002021 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002022 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002023}
2024
Aart Bik6b69e0a2017-01-11 10:20:43 -08002025void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2026 DCHECK(EndsWithControlFlowInstruction());
2027 RemoveInstruction(GetLastInstruction());
2028 instructions_.Add(other->GetInstructions());
2029 other->instructions_.SetBlockOfInstructions(this);
2030 other->instructions_.Clear();
2031}
2032
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002033void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002034 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002035 DCHECK(ContainsElement(dominated_blocks_, other));
2036 DCHECK_EQ(GetSingleSuccessor(), other);
2037 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002038 DCHECK(other->GetPhis().IsEmpty());
2039
David Brazdil2d7352b2015-04-20 14:52:42 +01002040 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002041 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002042
David Brazdil2d7352b2015-04-20 14:52:42 +01002043 // Remove `other` from the loops it is included in.
2044 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2045 HLoopInformation* loop_info = it.Current();
2046 loop_info->Remove(other);
2047 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002048 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002049 }
2050 }
2051
2052 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002053 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002054 for (HBasicBlock* successor : other->GetSuccessors()) {
2055 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002056 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002057 successors_.swap(other->successors_);
2058 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002059
David Brazdil2d7352b2015-04-20 14:52:42 +01002060 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002061 RemoveDominatedBlock(other);
2062 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002063 dominated->SetDominator(this);
2064 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002065 dominated_blocks_.insert(
2066 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002067 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002068 other->dominator_ = nullptr;
2069
2070 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002071 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002072
2073 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002074 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002075 other->SetGraph(nullptr);
2076}
2077
2078void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2079 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002080 DCHECK(GetDominatedBlocks().empty());
2081 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002082 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002083 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002084 DCHECK(other->GetPhis().IsEmpty());
2085 DCHECK(!other->IsInLoop());
2086
2087 // Move instructions from `other` to `this`.
2088 instructions_.Add(other->GetInstructions());
2089 other->instructions_.SetBlockOfInstructions(this);
2090
2091 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002092 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002093 for (HBasicBlock* successor : other->GetSuccessors()) {
2094 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002095 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002096 successors_.swap(other->successors_);
2097 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002098
2099 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002100 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002101 dominated->SetDominator(this);
2102 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002103 dominated_blocks_.insert(
2104 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002105 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002106 other->dominator_ = nullptr;
2107 other->graph_ = nullptr;
2108}
2109
2110void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002111 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002112 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002113 predecessor->ReplaceSuccessor(this, other);
2114 }
Vladimir Marko60584552015-09-03 13:35:12 +00002115 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002116 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002117 successor->ReplacePredecessor(this, other);
2118 }
Vladimir Marko60584552015-09-03 13:35:12 +00002119 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2120 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002121 }
2122 GetDominator()->ReplaceDominatedBlock(this, other);
2123 other->SetDominator(GetDominator());
2124 dominator_ = nullptr;
2125 graph_ = nullptr;
2126}
2127
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002128void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002129 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002130 DCHECK(block->GetSuccessors().empty());
2131 DCHECK(block->GetPredecessors().empty());
2132 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002133 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002134 DCHECK(block->GetInstructions().IsEmpty());
2135 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002136
David Brazdilc7af85d2015-05-26 12:05:55 +01002137 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002138 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002139 }
2140
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002141 RemoveElement(reverse_post_order_, block);
2142 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002143 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002144}
2145
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002146void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2147 HBasicBlock* reference,
2148 bool replace_if_back_edge) {
2149 if (block->IsLoopHeader()) {
2150 // Clear the information of which blocks are contained in that loop. Since the
2151 // information is stored as a bit vector based on block ids, we have to update
2152 // it, as those block ids were specific to the callee graph and we are now adding
2153 // these blocks to the caller graph.
2154 block->GetLoopInformation()->ClearAllBlocks();
2155 }
2156
2157 // If not already in a loop, update the loop information.
2158 if (!block->IsInLoop()) {
2159 block->SetLoopInformation(reference->GetLoopInformation());
2160 }
2161
2162 // If the block is in a loop, update all its outward loops.
2163 HLoopInformation* loop_info = block->GetLoopInformation();
2164 if (loop_info != nullptr) {
2165 for (HLoopInformationOutwardIterator loop_it(*block);
2166 !loop_it.Done();
2167 loop_it.Advance()) {
2168 loop_it.Current()->Add(block);
2169 }
2170 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2171 loop_info->ReplaceBackEdge(reference, block);
2172 }
2173 }
2174
2175 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2176 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2177 ? reference->GetTryCatchInformation()
2178 : nullptr;
2179 block->SetTryCatchInformation(try_catch_info);
2180}
2181
Calin Juravle2e768302015-07-28 14:41:11 +00002182HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002183 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002184 // Update the environments in this graph to have the invoke's environment
2185 // as parent.
2186 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002187 // Skip the entry block, we do not need to update the entry's suspend check.
2188 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002189 for (HInstructionIterator instr_it(block->GetInstructions());
2190 !instr_it.Done();
2191 instr_it.Advance()) {
2192 HInstruction* current = instr_it.Current();
2193 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002194 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002195 current->GetEnvironment()->SetAndCopyParentChain(
2196 outer_graph->GetArena(), invoke->GetEnvironment());
2197 }
2198 }
2199 }
2200 }
2201 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002202
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002203 if (HasBoundsChecks()) {
2204 outer_graph->SetHasBoundsChecks(true);
2205 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002206 if (HasLoops()) {
2207 outer_graph->SetHasLoops(true);
2208 }
2209 if (HasIrreducibleLoops()) {
2210 outer_graph->SetHasIrreducibleLoops(true);
2211 }
2212 if (HasTryCatch()) {
2213 outer_graph->SetHasTryCatch(true);
2214 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002215 if (HasSIMD()) {
2216 outer_graph->SetHasSIMD(true);
2217 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002218
Calin Juravle2e768302015-07-28 14:41:11 +00002219 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002220 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002221 // Inliner already made sure we don't inline methods that always throw.
2222 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002223 // Simple case of an entry block, a body block, and an exit block.
2224 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002225 HBasicBlock* body = GetBlocks()[1];
2226 DCHECK(GetBlocks()[0]->IsEntryBlock());
2227 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002228 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002229 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002230 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002231
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002232 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2233 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002234 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002235
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002236 // Replace the invoke with the return value of the inlined graph.
2237 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002238 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002239 } else {
2240 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002241 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002242
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002243 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002244 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002245 // Need to inline multiple blocks. We split `invoke`'s block
2246 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002247 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002248 // with the second half.
2249 ArenaAllocator* allocator = outer_graph->GetArena();
2250 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002251 // Note that we split before the invoke only to simplify polymorphic inlining.
2252 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002253
Vladimir Markoec7802a2015-10-01 20:57:57 +01002254 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002255 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002256 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002257 exit_block_->ReplaceWith(to);
2258
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259 // Update the meta information surrounding blocks:
2260 // (1) the graph they are now in,
2261 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002262 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002263 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002264 // Note that we do not need to update catch phi inputs because they
2265 // correspond to the register file of the outer method which the inlinee
2266 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002267
2268 // We don't add the entry block, the exit block, and the first block, which
2269 // has been merged with `at`.
2270 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2271
2272 // We add the `to` block.
2273 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002274 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002275 + kNumberOfNewBlocksInCaller;
2276
2277 // Find the location of `at` in the outer graph's reverse post order. The new
2278 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002279 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002280 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2281
David Brazdil95177982015-10-30 12:56:58 -05002282 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2283 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002284 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002285 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002286 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002287 DCHECK(current->GetGraph() == this);
2288 current->SetGraph(outer_graph);
2289 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002290 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002291 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002292 }
2293 }
2294
David Brazdil95177982015-10-30 12:56:58 -05002295 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002296 to->SetGraph(outer_graph);
2297 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002298 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002299 // Only `to` can become a back edge, as the inlined blocks
2300 // are predecessors of `to`.
2301 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002302
David Brazdil3f523062016-02-29 16:53:33 +00002303 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002304 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2305 // to now get the outer graph exit block as successor. Note that the inliner
2306 // currently doesn't support inlining methods with try/catch.
2307 HPhi* return_value_phi = nullptr;
2308 bool rerun_dominance = false;
2309 bool rerun_loop_analysis = false;
2310 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2311 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002312 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002313 if (last->IsThrow()) {
2314 DCHECK(!at->IsTryBlock());
2315 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2316 --pred;
2317 // We need to re-run dominance information, as the exit block now has
2318 // a new dominator.
2319 rerun_dominance = true;
2320 if (predecessor->GetLoopInformation() != nullptr) {
2321 // The exit block and blocks post dominated by the exit block do not belong
2322 // to any loop. Because we do not compute the post dominators, we need to re-run
2323 // loop analysis to get the loop information correct.
2324 rerun_loop_analysis = true;
2325 }
2326 } else {
2327 if (last->IsReturnVoid()) {
2328 DCHECK(return_value == nullptr);
2329 DCHECK(return_value_phi == nullptr);
2330 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002331 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002332 if (return_value_phi != nullptr) {
2333 return_value_phi->AddInput(last->InputAt(0));
2334 } else if (return_value == nullptr) {
2335 return_value = last->InputAt(0);
2336 } else {
2337 // There will be multiple returns.
2338 return_value_phi = new (allocator) HPhi(
2339 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2340 to->AddPhi(return_value_phi);
2341 return_value_phi->AddInput(return_value);
2342 return_value_phi->AddInput(last->InputAt(0));
2343 return_value = return_value_phi;
2344 }
David Brazdil3f523062016-02-29 16:53:33 +00002345 }
2346 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2347 predecessor->RemoveInstruction(last);
2348 }
2349 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002350 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002351 DCHECK(!outer_graph->HasIrreducibleLoops())
2352 << "Recomputing loop information in graphs with irreducible loops "
2353 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002354 outer_graph->ClearLoopInformation();
2355 outer_graph->ClearDominanceInformation();
2356 outer_graph->BuildDominatorTree();
2357 } else if (rerun_dominance) {
2358 outer_graph->ClearDominanceInformation();
2359 outer_graph->ComputeDominanceInformation();
2360 }
David Brazdil3f523062016-02-29 16:53:33 +00002361 }
David Brazdil05144f42015-04-16 15:18:00 +01002362
2363 // Walk over the entry block and:
2364 // - Move constants from the entry block to the outer_graph's entry block,
2365 // - Replace HParameterValue instructions with their real value.
2366 // - Remove suspend checks, that hold an environment.
2367 // We must do this after the other blocks have been inlined, otherwise ids of
2368 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002369 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002370 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2371 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002372 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002373 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002374 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002375 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002376 replacement = outer_graph->GetIntConstant(
2377 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002378 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002379 replacement = outer_graph->GetLongConstant(
2380 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002381 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002382 replacement = outer_graph->GetFloatConstant(
2383 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002384 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002385 replacement = outer_graph->GetDoubleConstant(
2386 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002387 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002388 if (kIsDebugBuild
2389 && invoke->IsInvokeStaticOrDirect()
2390 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2391 // Ensure we do not use the last input of `invoke`, as it
2392 // contains a clinit check which is not an actual argument.
2393 size_t last_input_index = invoke->InputCount() - 1;
2394 DCHECK(parameter_index != last_input_index);
2395 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002396 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002397 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002398 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002399 } else {
2400 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2401 entry_block_->RemoveInstruction(current);
2402 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002403 if (replacement != nullptr) {
2404 current->ReplaceWith(replacement);
2405 // If the current is the return value then we need to update the latter.
2406 if (current == return_value) {
2407 DCHECK_EQ(entry_block_, return_value->GetBlock());
2408 return_value = replacement;
2409 }
2410 }
2411 }
2412
Calin Juravle2e768302015-07-28 14:41:11 +00002413 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002414}
2415
Mingyao Yang3584bce2015-05-19 16:01:59 -07002416/*
2417 * Loop will be transformed to:
2418 * old_pre_header
2419 * |
2420 * if_block
2421 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002422 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002423 * \ /
2424 * new_pre_header
2425 * |
2426 * header
2427 */
2428void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2429 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002430 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002431
Aart Bik3fc7f352015-11-20 22:03:03 -08002432 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002433 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002434 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2435 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002436 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2437 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002438 AddBlock(true_block);
2439 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002440 AddBlock(new_pre_header);
2441
Aart Bik3fc7f352015-11-20 22:03:03 -08002442 header->ReplacePredecessor(old_pre_header, new_pre_header);
2443 old_pre_header->successors_.clear();
2444 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002445
Aart Bik3fc7f352015-11-20 22:03:03 -08002446 old_pre_header->AddSuccessor(if_block);
2447 if_block->AddSuccessor(true_block); // True successor
2448 if_block->AddSuccessor(false_block); // False successor
2449 true_block->AddSuccessor(new_pre_header);
2450 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002451
Aart Bik3fc7f352015-11-20 22:03:03 -08002452 old_pre_header->dominated_blocks_.push_back(if_block);
2453 if_block->SetDominator(old_pre_header);
2454 if_block->dominated_blocks_.push_back(true_block);
2455 true_block->SetDominator(if_block);
2456 if_block->dominated_blocks_.push_back(false_block);
2457 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002458 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002459 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002460 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002461 header->SetDominator(new_pre_header);
2462
Aart Bik3fc7f352015-11-20 22:03:03 -08002463 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002464 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002465 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002466 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002467 reverse_post_order_[index_of_header++] = true_block;
2468 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002469 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002470
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002471 // The pre_header can never be a back edge of a loop.
2472 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2473 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2474 UpdateLoopAndTryInformationOfNewBlock(
2475 if_block, old_pre_header, /* replace_if_back_edge */ false);
2476 UpdateLoopAndTryInformationOfNewBlock(
2477 true_block, old_pre_header, /* replace_if_back_edge */ false);
2478 UpdateLoopAndTryInformationOfNewBlock(
2479 false_block, old_pre_header, /* replace_if_back_edge */ false);
2480 UpdateLoopAndTryInformationOfNewBlock(
2481 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002482}
2483
Aart Bikf8f5a162017-02-06 15:35:29 -08002484HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2485 HBasicBlock* body,
2486 HBasicBlock* exit) {
2487 DCHECK(header->IsLoopHeader());
2488 HLoopInformation* loop = header->GetLoopInformation();
2489
2490 // Add new loop blocks.
2491 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2492 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2493 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2494 AddBlock(new_pre_header);
2495 AddBlock(new_header);
2496 AddBlock(new_body);
2497
2498 // Set up control flow.
2499 header->ReplaceSuccessor(exit, new_pre_header);
2500 new_pre_header->AddSuccessor(new_header);
2501 new_header->AddSuccessor(exit);
2502 new_header->AddSuccessor(new_body);
2503 new_body->AddSuccessor(new_header);
2504
2505 // Set up dominators.
2506 header->ReplaceDominatedBlock(exit, new_pre_header);
2507 new_pre_header->SetDominator(header);
2508 new_pre_header->dominated_blocks_.push_back(new_header);
2509 new_header->SetDominator(new_pre_header);
2510 new_header->dominated_blocks_.push_back(new_body);
2511 new_body->SetDominator(new_header);
2512 new_header->dominated_blocks_.push_back(exit);
2513 exit->SetDominator(new_header);
2514
2515 // Fix reverse post order.
2516 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2517 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2518 reverse_post_order_[++index_of_header] = new_pre_header;
2519 reverse_post_order_[++index_of_header] = new_header;
2520 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2521 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2522 reverse_post_order_[index_of_body] = new_body;
2523
Aart Bikb07d1bc2017-04-05 10:03:15 -07002524 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002525 new_pre_header->AddInstruction(new (arena_) HGoto());
2526 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2527 new_header->AddInstruction(suspend_check);
2528 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002529 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2530 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002531
2532 // Update loop information.
2533 new_header->AddBackEdge(new_body);
2534 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2535 new_header->GetLoopInformation()->Populate();
2536 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2537 HLoopInformationOutwardIterator it(*new_header);
2538 for (it.Advance(); !it.Done(); it.Advance()) {
2539 it.Current()->Add(new_pre_header);
2540 it.Current()->Add(new_header);
2541 it.Current()->Add(new_body);
2542 }
2543 return new_pre_header;
2544}
2545
David Brazdilf5552582015-12-27 13:36:12 +00002546static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002547 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002548 if (rti.IsValid()) {
2549 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2550 << " upper_bound_rti: " << upper_bound_rti
2551 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002552 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2553 << " upper_bound_rti: " << upper_bound_rti
2554 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002555 }
2556}
2557
Calin Juravle2e768302015-07-28 14:41:11 +00002558void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2559 if (kIsDebugBuild) {
2560 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2561 ScopedObjectAccess soa(Thread::Current());
2562 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2563 if (IsBoundType()) {
2564 // Having the test here spares us from making the method virtual just for
2565 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002566 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002567 }
2568 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002569 reference_type_handle_ = rti.GetTypeHandle();
2570 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002571}
2572
David Brazdilf5552582015-12-27 13:36:12 +00002573void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2574 if (kIsDebugBuild) {
2575 ScopedObjectAccess soa(Thread::Current());
2576 DCHECK(upper_bound.IsValid());
2577 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2578 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2579 }
2580 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002581 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002582}
2583
Vladimir Markoa1de9182016-02-25 11:37:38 +00002584ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002585 if (kIsDebugBuild) {
2586 ScopedObjectAccess soa(Thread::Current());
2587 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002588 if (!is_exact) {
2589 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2590 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2591 }
Calin Juravle2e768302015-07-28 14:41:11 +00002592 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002593 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002594}
2595
Calin Juravleacf735c2015-02-12 15:25:22 +00002596std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2597 ScopedObjectAccess soa(Thread::Current());
2598 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002599 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002600 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002601 << " is_exact=" << rhs.IsExact()
2602 << " ]";
2603 return os;
2604}
2605
Mark Mendellc4701932015-04-10 13:18:51 -04002606bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2607 // For now, assume that instructions in different blocks may use the
2608 // environment.
2609 // TODO: Use the control flow to decide if this is true.
2610 if (GetBlock() != other->GetBlock()) {
2611 return true;
2612 }
2613
2614 // We know that we are in the same block. Walk from 'this' to 'other',
2615 // checking to see if there is any instruction with an environment.
2616 HInstruction* current = this;
2617 for (; current != other && current != nullptr; current = current->GetNext()) {
2618 // This is a conservative check, as the instruction result may not be in
2619 // the referenced environment.
2620 if (current->HasEnvironment()) {
2621 return true;
2622 }
2623 }
2624
2625 // We should have been called with 'this' before 'other' in the block.
2626 // Just confirm this.
2627 DCHECK(current != nullptr);
2628 return false;
2629}
2630
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002631void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002632 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2633 IntrinsicSideEffects side_effects,
2634 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002635 intrinsic_ = intrinsic;
2636 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002637
Aart Bik5d75afe2015-12-14 11:57:01 -08002638 // Adjust method's side effects from intrinsic table.
2639 switch (side_effects) {
2640 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2641 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2642 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2643 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2644 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002645
2646 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2647 opt.SetDoesNotNeedDexCache();
2648 opt.SetDoesNotNeedEnvironment();
2649 } else {
2650 // If we need an environment, that means there will be a call, which can trigger GC.
2651 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2652 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002653 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002654 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002655}
2656
David Brazdil6de19382016-01-08 17:37:10 +00002657bool HNewInstance::IsStringAlloc() const {
2658 ScopedObjectAccess soa(Thread::Current());
2659 return GetReferenceTypeInfo().IsStringClass();
2660}
2661
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002662bool HInvoke::NeedsEnvironment() const {
2663 if (!IsIntrinsic()) {
2664 return true;
2665 }
2666 IntrinsicOptimizations opt(*this);
2667 return !opt.GetDoesNotNeedEnvironment();
2668}
2669
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002670const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2671 ArtMethod* caller = GetEnvironment()->GetMethod();
2672 ScopedObjectAccess soa(Thread::Current());
2673 // `caller` is null for a top-level graph representing a method whose declaring
2674 // class was not resolved.
2675 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2676}
2677
Vladimir Markodc151b22015-10-15 18:02:30 +01002678bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002679 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002680 return false;
2681 }
2682 if (!IsIntrinsic()) {
2683 return true;
2684 }
2685 IntrinsicOptimizations opt(*this);
2686 return !opt.GetDoesNotNeedDexCache();
2687}
2688
Vladimir Markof64242a2015-12-01 14:58:23 +00002689std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2690 switch (rhs) {
2691 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002692 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002693 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002694 return os << "Recursive";
2695 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2696 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002697 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002698 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002699 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2700 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002701 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2702 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002703 default:
2704 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2705 UNREACHABLE();
2706 }
2707}
2708
Vladimir Markofbb184a2015-11-13 14:47:00 +00002709std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2710 switch (rhs) {
2711 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2712 return os << "explicit";
2713 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2714 return os << "implicit";
2715 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2716 return os << "none";
2717 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002718 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2719 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002720 }
2721}
2722
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002723bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2724 const HLoadClass* other_load_class = other->AsLoadClass();
2725 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2726 // names rather than type indexes. However, we shall also have to re-think the hash code.
2727 if (type_index_ != other_load_class->type_index_ ||
2728 GetPackedFields() != other_load_class->GetPackedFields()) {
2729 return false;
2730 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002731 switch (GetLoadKind()) {
2732 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002733 case LoadKind::kJitTableAddress: {
2734 ScopedObjectAccess soa(Thread::Current());
2735 return GetClass().Get() == other_load_class->GetClass().Get();
2736 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002737 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002738 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002739 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002740 }
2741}
2742
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002743void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002744 SetPackedField<LoadKindField>(load_kind);
2745
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002746 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002747 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002748 RemoveAsUserOfInput(0u);
2749 SetRawInputAt(0u, nullptr);
2750 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002751
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002752 if (!NeedsEnvironment()) {
2753 RemoveEnvironment();
2754 SetSideEffects(SideEffects::None());
2755 }
2756}
2757
2758std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2759 switch (rhs) {
2760 case HLoadClass::LoadKind::kReferrersClass:
2761 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002762 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2763 return os << "BootImageLinkTimePcRelative";
2764 case HLoadClass::LoadKind::kBootImageAddress:
2765 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002766 case HLoadClass::LoadKind::kBssEntry:
2767 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002768 case HLoadClass::LoadKind::kJitTableAddress:
2769 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002770 case HLoadClass::LoadKind::kRuntimeCall:
2771 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002772 default:
2773 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2774 UNREACHABLE();
2775 }
2776}
2777
Vladimir Marko372f10e2016-05-17 16:30:10 +01002778bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2779 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002780 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2781 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002782 if (string_index_ != other_load_string->string_index_ ||
2783 GetPackedFields() != other_load_string->GetPackedFields()) {
2784 return false;
2785 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002786 switch (GetLoadKind()) {
2787 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002788 case LoadKind::kJitTableAddress: {
2789 ScopedObjectAccess soa(Thread::Current());
2790 return GetString().Get() == other_load_string->GetString().Get();
2791 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002792 default:
2793 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002794 }
2795}
2796
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002797void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002798 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002799 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002800 SetPackedField<LoadKindField>(load_kind);
2801
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002802 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002803 RemoveAsUserOfInput(0u);
2804 SetRawInputAt(0u, nullptr);
2805 }
2806 if (!NeedsEnvironment()) {
2807 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002808 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002809 }
2810}
2811
2812std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2813 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002814 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2815 return os << "BootImageLinkTimePcRelative";
2816 case HLoadString::LoadKind::kBootImageAddress:
2817 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002818 case HLoadString::LoadKind::kBssEntry:
2819 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002820 case HLoadString::LoadKind::kJitTableAddress:
2821 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002822 case HLoadString::LoadKind::kRuntimeCall:
2823 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002824 default:
2825 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2826 UNREACHABLE();
2827 }
2828}
2829
Mark Mendellc4701932015-04-10 13:18:51 -04002830void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002831 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2832 HEnvironment* user = use.GetUser();
2833 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002834 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002835 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002836}
2837
Roland Levillainc9b21f82016-03-23 16:36:59 +00002838// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002839HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2840 ArenaAllocator* allocator = GetArena();
2841
2842 if (cond->IsCondition() &&
2843 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2844 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2845 HInstruction* lhs = cond->InputAt(0);
2846 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002847 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002848 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2849 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2850 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2851 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2852 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2853 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2854 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2855 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2856 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2857 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2858 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002859 default:
2860 LOG(FATAL) << "Unexpected condition";
2861 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002862 }
2863 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2864 return replacement;
2865 } else if (cond->IsIntConstant()) {
2866 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002867 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002868 return GetIntConstant(1);
2869 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002870 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002871 return GetIntConstant(0);
2872 }
2873 } else {
2874 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2875 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2876 return replacement;
2877 }
2878}
2879
Roland Levillainc9285912015-12-18 10:38:42 +00002880std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2881 os << "["
2882 << " source=" << rhs.GetSource()
2883 << " destination=" << rhs.GetDestination()
2884 << " type=" << rhs.GetType()
2885 << " instruction=";
2886 if (rhs.GetInstruction() != nullptr) {
2887 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2888 } else {
2889 os << "null";
2890 }
2891 os << " ]";
2892 return os;
2893}
2894
Roland Levillain86503782016-02-11 19:07:30 +00002895std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2896 switch (rhs) {
2897 case TypeCheckKind::kUnresolvedCheck:
2898 return os << "unresolved_check";
2899 case TypeCheckKind::kExactCheck:
2900 return os << "exact_check";
2901 case TypeCheckKind::kClassHierarchyCheck:
2902 return os << "class_hierarchy_check";
2903 case TypeCheckKind::kAbstractClassCheck:
2904 return os << "abstract_class_check";
2905 case TypeCheckKind::kInterfaceCheck:
2906 return os << "interface_check";
2907 case TypeCheckKind::kArrayObjectCheck:
2908 return os << "array_object_check";
2909 case TypeCheckKind::kArrayCheck:
2910 return os << "array_check";
2911 default:
2912 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2913 UNREACHABLE();
2914 }
2915}
2916
Andreas Gampe26de38b2016-07-27 17:53:11 -07002917std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2918 switch (kind) {
2919 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002920 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002921 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002922 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002923 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002924 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002925 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002926 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002927 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002928 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002929
2930 default:
2931 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2932 UNREACHABLE();
2933 }
2934}
2935
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002936} // namespace art