blob: 41ea998a8c6159499ccdc106c6bea90da75ce724 [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(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100567 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600568 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
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100588HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000589 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100590 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000591 DCHECK(IsUint<1>(value));
592 FALLTHROUGH_INTENDED;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100593 case DataType::Type::kInt8:
594 case DataType::Type::kUint16:
595 case DataType::Type::kInt16:
596 case DataType::Type::kInt32:
597 DCHECK(IsInt(DataType::Size(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
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100600 case DataType::Type::kInt64:
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);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100841 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400842 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100843 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
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
Igor Murashkin6ef45672017-08-08 13:59:55 -07001219size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001220 DCHECK(instruction->GetBlock() != nullptr);
1221 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001222 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001223
Igor Murashkin6ef45672017-08-08 13:59:55 -07001224 // Return how many instructions were removed for statistic purposes.
1225 size_t remove_count = 0;
1226
Igor Murashkind01745e2017-04-05 16:40:31 -07001227 // Efficient implementation that simultaneously (in one pass):
1228 // * Scans the uses list for all constructor fences.
1229 // * Deletes that constructor fence from the uses list of `instruction`.
1230 // * Deletes `instruction` from the constructor fence's inputs.
1231 // * Deletes the constructor fence if it now has 0 inputs.
1232
1233 const HUseList<HInstruction*>& uses = instruction->GetUses();
1234 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1235 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1236 const HUseListNode<HInstruction*>& use_node = *it;
1237 HInstruction* const use_instruction = use_node.GetUser();
1238
1239 // Advance the iterator immediately once we fetch the use_node.
1240 // Warning: If the input is removed, the current iterator becomes invalid.
1241 ++it;
1242
1243 if (use_instruction->IsConstructorFence()) {
1244 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1245 size_t input_index = use_node.GetIndex();
1246
1247 // Process the candidate instruction for removal
1248 // from the graph.
1249
1250 // Constructor fence instructions are never
1251 // used by other instructions.
1252 //
1253 // If we wanted to make this more generic, it
1254 // could be a runtime if statement.
1255 DCHECK(!ctor_fence->HasUses());
1256
1257 // A constructor fence's return type is "kPrimVoid"
1258 // and therefore it can't have any environment uses.
1259 DCHECK(!ctor_fence->HasEnvironmentUses());
1260
1261 // Remove the inputs first, otherwise removing the instruction
1262 // will try to remove its uses while we are already removing uses
1263 // and this operation will fail.
1264 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1265
1266 // Removing the input will also remove the `use_node`.
1267 // (Do not look at `use_node` after this, it will be a dangling reference).
1268 ctor_fence->RemoveInputAt(input_index);
1269
1270 // Once all inputs are removed, the fence is considered dead and
1271 // is removed.
1272 if (ctor_fence->InputCount() == 0u) {
1273 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001274 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001275 }
1276 }
1277 }
1278
1279 if (kIsDebugBuild) {
1280 // Post-condition checks:
1281 // * None of the uses of `instruction` are a constructor fence.
1282 // * The `instruction` itself did not get removed from a block.
1283 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1284 CHECK(!use_node.GetUser()->IsConstructorFence());
1285 }
1286 CHECK(instruction->GetBlock() != nullptr);
1287 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001288
1289 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001290}
1291
Igor Murashkindd018df2017-08-09 10:38:31 -07001292void HConstructorFence::Merge(HConstructorFence* other) {
1293 // Do not delete yourself from the graph.
1294 DCHECK(this != other);
1295 // Don't try to merge with an instruction not associated with a block.
1296 DCHECK(other->GetBlock() != nullptr);
1297 // A constructor fence's return type is "kPrimVoid"
1298 // and therefore it cannot have any environment uses.
1299 DCHECK(!other->HasEnvironmentUses());
1300
1301 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1302 // Check if `haystack` has `needle` as any of its inputs.
1303 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1304 if (haystack->InputAt(input_count) == needle) {
1305 return true;
1306 }
1307 }
1308 return false;
1309 };
1310
1311 // Add any inputs from `other` into `this` if it wasn't already an input.
1312 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1313 HInstruction* other_input = other->InputAt(input_count);
1314 if (!has_input(this, other_input)) {
1315 AddInput(other_input);
1316 }
1317 }
1318
1319 other->GetBlock()->RemoveInstruction(other);
1320}
1321
1322HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001323 HInstruction* new_instance_inst = GetPrevious();
1324 // Check if the immediately preceding instruction is a new-instance/new-array.
1325 // Otherwise this fence is for protecting final fields.
1326 if (new_instance_inst != nullptr &&
1327 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001328 if (ignore_inputs) {
1329 // If inputs are ignored, simply check if the predecessor is
1330 // *any* HNewInstance/HNewArray.
1331 //
1332 // Inputs are normally only ignored for prepare_for_register_allocation,
1333 // at which point *any* prior HNewInstance/Array can be considered
1334 // associated.
1335 return new_instance_inst;
1336 } else {
1337 // Normal case: There must be exactly 1 input and the previous instruction
1338 // must be that input.
1339 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1340 return new_instance_inst;
1341 }
1342 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001343 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001344 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001345}
1346
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001347#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001348void H##name::Accept(HGraphVisitor* visitor) { \
1349 visitor->Visit##name(this); \
1350}
1351
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001352FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001353
1354#undef DEFINE_ACCEPT
1355
1356void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001357 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1358 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001359 if (block != nullptr) {
1360 VisitBasicBlock(block);
1361 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001362 }
1363}
1364
Roland Levillain633021e2014-10-01 14:12:25 +01001365void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001366 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1367 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001368 }
1369}
1370
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001371void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001372 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001373 it.Current()->Accept(this);
1374 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001375 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001376 it.Current()->Accept(this);
1377 }
1378}
1379
Mark Mendelle82549b2015-05-06 10:55:34 -04001380HConstant* HTypeConversion::TryStaticEvaluation() const {
1381 HGraph* graph = GetBlock()->GetGraph();
1382 if (GetInput()->IsIntConstant()) {
1383 int32_t value = GetInput()->AsIntConstant()->GetValue();
1384 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001385 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001386 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001387 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001388 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001389 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001390 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001391 default:
1392 return nullptr;
1393 }
1394 } else if (GetInput()->IsLongConstant()) {
1395 int64_t value = GetInput()->AsLongConstant()->GetValue();
1396 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001397 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001398 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001399 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001400 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001402 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001403 default:
1404 return nullptr;
1405 }
1406 } else if (GetInput()->IsFloatConstant()) {
1407 float value = GetInput()->AsFloatConstant()->GetValue();
1408 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001409 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001410 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001411 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001412 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001413 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001414 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001415 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1416 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001417 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001418 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001419 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001420 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001421 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001422 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001423 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1424 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001426 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001427 default:
1428 return nullptr;
1429 }
1430 } else if (GetInput()->IsDoubleConstant()) {
1431 double value = GetInput()->AsDoubleConstant()->GetValue();
1432 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001433 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001434 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001435 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001436 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001437 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001438 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001439 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1440 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001441 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001442 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001443 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001444 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001445 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001446 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001447 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1448 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001449 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001450 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001451 default:
1452 return nullptr;
1453 }
1454 }
1455 return nullptr;
1456}
1457
Roland Levillain9240d6a2014-10-20 16:47:04 +01001458HConstant* HUnaryOperation::TryStaticEvaluation() const {
1459 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001460 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001461 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001462 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001463 } else if (kEnableFloatingPointStaticEvaluation) {
1464 if (GetInput()->IsFloatConstant()) {
1465 return Evaluate(GetInput()->AsFloatConstant());
1466 } else if (GetInput()->IsDoubleConstant()) {
1467 return Evaluate(GetInput()->AsDoubleConstant());
1468 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001469 }
1470 return nullptr;
1471}
1472
1473HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001474 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1475 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001476 } else if (GetLeft()->IsLongConstant()) {
1477 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001478 // The binop(long, int) case is only valid for shifts and rotations.
1479 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001480 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1481 } else if (GetRight()->IsLongConstant()) {
1482 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001483 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001484 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001485 // The binop(null, null) case is only valid for equal and not-equal conditions.
1486 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001487 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001488 } else if (kEnableFloatingPointStaticEvaluation) {
1489 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1490 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1491 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1492 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1493 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001494 }
1495 return nullptr;
1496}
Dave Allison20dfc792014-06-16 20:44:29 -07001497
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001498HConstant* HBinaryOperation::GetConstantRight() const {
1499 if (GetRight()->IsConstant()) {
1500 return GetRight()->AsConstant();
1501 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1502 return GetLeft()->AsConstant();
1503 } else {
1504 return nullptr;
1505 }
1506}
1507
1508// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001509// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001510HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1511 HInstruction* most_constant_right = GetConstantRight();
1512 if (most_constant_right == nullptr) {
1513 return nullptr;
1514 } else if (most_constant_right == GetLeft()) {
1515 return GetRight();
1516 } else {
1517 return GetLeft();
1518 }
1519}
1520
Roland Levillain31dd3d62016-02-16 12:21:02 +00001521std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1522 switch (rhs) {
1523 case ComparisonBias::kNoBias:
1524 return os << "no_bias";
1525 case ComparisonBias::kGtBias:
1526 return os << "gt_bias";
1527 case ComparisonBias::kLtBias:
1528 return os << "lt_bias";
1529 default:
1530 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1531 UNREACHABLE();
1532 }
1533}
1534
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001535bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1536 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001537}
1538
Vladimir Marko372f10e2016-05-17 16:30:10 +01001539bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001540 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001541 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001542 if (!InstructionDataEquals(other)) return false;
1543 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001544 HConstInputsRef inputs = GetInputs();
1545 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001546 if (inputs.size() != other_inputs.size()) return false;
1547 for (size_t i = 0; i != inputs.size(); ++i) {
1548 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001549 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001550
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001551 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001552 return true;
1553}
1554
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001555std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1556#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1557 switch (rhs) {
1558 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1559 default:
1560 os << "Unknown instruction kind " << static_cast<int>(rhs);
1561 break;
1562 }
1563#undef DECLARE_CASE
1564 return os;
1565}
1566
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001567void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1568 if (do_checks) {
1569 DCHECK(!IsPhi());
1570 DCHECK(!IsControlFlow());
1571 DCHECK(CanBeMoved() ||
1572 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1573 IsShouldDeoptimizeFlag());
1574 DCHECK(!cursor->IsPhi());
1575 }
David Brazdild6c205e2016-06-07 14:20:52 +01001576
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001577 next_->previous_ = previous_;
1578 if (previous_ != nullptr) {
1579 previous_->next_ = next_;
1580 }
1581 if (block_->instructions_.first_instruction_ == this) {
1582 block_->instructions_.first_instruction_ = next_;
1583 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001584 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001585
1586 previous_ = cursor->previous_;
1587 if (previous_ != nullptr) {
1588 previous_->next_ = this;
1589 }
1590 next_ = cursor;
1591 cursor->previous_ = this;
1592 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001593
1594 if (block_->instructions_.first_instruction_ == cursor) {
1595 block_->instructions_.first_instruction_ = this;
1596 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001597}
1598
Vladimir Markofb337ea2015-11-25 15:25:10 +00001599void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1600 DCHECK(!CanThrow());
1601 DCHECK(!HasSideEffects());
1602 DCHECK(!HasEnvironmentUses());
1603 DCHECK(HasNonEnvironmentUses());
1604 DCHECK(!IsPhi()); // Makes no sense for Phi.
1605 DCHECK_EQ(InputCount(), 0u);
1606
1607 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001608 auto uses_it = GetUses().begin();
1609 auto uses_end = GetUses().end();
1610 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1611 ++uses_it;
1612 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1613 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001614 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001615 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001616 // This instruction has uses in two or more blocks. Find the common dominator.
1617 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001618 for (; uses_it != uses_end; ++uses_it) {
1619 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001620 }
1621 target_block = finder.Get();
1622 DCHECK(target_block != nullptr);
1623 }
1624 // Move to the first dominator not in a loop.
1625 while (target_block->IsInLoop()) {
1626 target_block = target_block->GetDominator();
1627 DCHECK(target_block != nullptr);
1628 }
1629
1630 // Find insertion position.
1631 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001632 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1633 if (use.GetUser()->GetBlock() == target_block &&
1634 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1635 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001636 }
1637 }
1638 if (insert_pos == nullptr) {
1639 // No user in `target_block`, insert before the control flow instruction.
1640 insert_pos = target_block->GetLastInstruction();
1641 DCHECK(insert_pos->IsControlFlow());
1642 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1643 if (insert_pos->IsIf()) {
1644 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1645 if (if_input == insert_pos->GetPrevious()) {
1646 insert_pos = if_input;
1647 }
1648 }
1649 }
1650 MoveBefore(insert_pos);
1651}
1652
David Brazdilfc6a86a2015-06-26 10:33:45 +00001653HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001654 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001655 DCHECK_EQ(cursor->GetBlock(), this);
1656
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001657 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1658 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001659 new_block->instructions_.first_instruction_ = cursor;
1660 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1661 instructions_.last_instruction_ = cursor->previous_;
1662 if (cursor->previous_ == nullptr) {
1663 instructions_.first_instruction_ = nullptr;
1664 } else {
1665 cursor->previous_->next_ = nullptr;
1666 cursor->previous_ = nullptr;
1667 }
1668
1669 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001670 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001671
Vladimir Marko60584552015-09-03 13:35:12 +00001672 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001673 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001674 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001675 new_block->successors_.swap(successors_);
1676 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001677 AddSuccessor(new_block);
1678
David Brazdil56e1acc2015-06-30 15:41:36 +01001679 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001680 return new_block;
1681}
1682
David Brazdild7558da2015-09-22 13:04:14 +01001683HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001684 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001685 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1686
1687 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1688
1689 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001690 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1691 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001692 new_block->predecessors_.swap(predecessors_);
1693 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001694 AddPredecessor(new_block);
1695
1696 GetGraph()->AddBlock(new_block);
1697 return new_block;
1698}
1699
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001700HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1701 DCHECK_EQ(cursor->GetBlock(), this);
1702
1703 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1704 cursor->GetDexPc());
1705 new_block->instructions_.first_instruction_ = cursor;
1706 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1707 instructions_.last_instruction_ = cursor->previous_;
1708 if (cursor->previous_ == nullptr) {
1709 instructions_.first_instruction_ = nullptr;
1710 } else {
1711 cursor->previous_->next_ = nullptr;
1712 cursor->previous_ = nullptr;
1713 }
1714
1715 new_block->instructions_.SetBlockOfInstructions(new_block);
1716
1717 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001718 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1719 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001720 new_block->successors_.swap(successors_);
1721 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001722
1723 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1724 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001725 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001726 new_block->dominated_blocks_.swap(dominated_blocks_);
1727 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001728 return new_block;
1729}
1730
1731HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001732 DCHECK(!cursor->IsControlFlow());
1733 DCHECK_NE(instructions_.last_instruction_, cursor);
1734 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001735
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001736 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1737 new_block->instructions_.first_instruction_ = cursor->GetNext();
1738 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1739 cursor->next_->previous_ = nullptr;
1740 cursor->next_ = nullptr;
1741 instructions_.last_instruction_ = cursor;
1742
1743 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001744 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001745 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001746 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001747 new_block->successors_.swap(successors_);
1748 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001749
Vladimir Marko60584552015-09-03 13:35:12 +00001750 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001751 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001752 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001753 new_block->dominated_blocks_.swap(dominated_blocks_);
1754 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001755 return new_block;
1756}
1757
David Brazdilec16f792015-08-19 15:04:01 +01001758const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001759 if (EndsWithTryBoundary()) {
1760 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1761 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001762 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001763 return try_boundary;
1764 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001765 DCHECK(IsTryBlock());
1766 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001767 return nullptr;
1768 }
David Brazdilec16f792015-08-19 15:04:01 +01001769 } else if (IsTryBlock()) {
1770 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001771 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001772 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001773 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001774}
1775
David Brazdild7558da2015-09-22 13:04:14 +01001776bool HBasicBlock::HasThrowingInstructions() const {
1777 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1778 if (it.Current()->CanThrow()) {
1779 return true;
1780 }
1781 }
1782 return false;
1783}
1784
David Brazdilfc6a86a2015-06-26 10:33:45 +00001785static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1786 return block.GetPhis().IsEmpty()
1787 && !block.GetInstructions().IsEmpty()
1788 && block.GetFirstInstruction() == block.GetLastInstruction();
1789}
1790
David Brazdil46e2a392015-03-16 17:31:52 +00001791bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001792 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1793}
1794
Mads Ager16e52892017-07-14 13:11:37 +02001795bool HBasicBlock::IsSingleReturn() const {
1796 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1797}
1798
David Brazdilfc6a86a2015-06-26 10:33:45 +00001799bool HBasicBlock::IsSingleTryBoundary() const {
1800 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001801}
1802
David Brazdil8d5b8b22015-03-24 10:51:52 +00001803bool HBasicBlock::EndsWithControlFlowInstruction() const {
1804 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1805}
1806
David Brazdilb2bd1c52015-03-25 11:17:37 +00001807bool HBasicBlock::EndsWithIf() const {
1808 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1809}
1810
David Brazdilffee3d32015-07-06 11:48:53 +01001811bool HBasicBlock::EndsWithTryBoundary() const {
1812 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1813}
1814
David Brazdilb2bd1c52015-03-25 11:17:37 +00001815bool HBasicBlock::HasSinglePhi() const {
1816 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1817}
1818
David Brazdild26a4112015-11-10 11:07:31 +00001819ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1820 if (EndsWithTryBoundary()) {
1821 // The normal-flow successor of HTryBoundary is always stored at index zero.
1822 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1823 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1824 } else {
1825 // All successors of blocks not ending with TryBoundary are normal.
1826 return ArrayRef<HBasicBlock* const>(successors_);
1827 }
1828}
1829
1830ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1831 if (EndsWithTryBoundary()) {
1832 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1833 } else {
1834 // Blocks not ending with TryBoundary do not have exceptional successors.
1835 return ArrayRef<HBasicBlock* const>();
1836 }
1837}
1838
David Brazdilffee3d32015-07-06 11:48:53 +01001839bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001840 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1841 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1842
1843 size_t length = handlers1.size();
1844 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001845 return false;
1846 }
1847
David Brazdilb618ade2015-07-29 10:31:29 +01001848 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001849 for (size_t i = 0; i < length; ++i) {
1850 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001851 return false;
1852 }
1853 }
1854 return true;
1855}
1856
David Brazdil2d7352b2015-04-20 14:52:42 +01001857size_t HInstructionList::CountSize() const {
1858 size_t size = 0;
1859 HInstruction* current = first_instruction_;
1860 for (; current != nullptr; current = current->GetNext()) {
1861 size++;
1862 }
1863 return size;
1864}
1865
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001866void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1867 for (HInstruction* current = first_instruction_;
1868 current != nullptr;
1869 current = current->GetNext()) {
1870 current->SetBlock(block);
1871 }
1872}
1873
1874void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1875 DCHECK(Contains(cursor));
1876 if (!instruction_list.IsEmpty()) {
1877 if (cursor == last_instruction_) {
1878 last_instruction_ = instruction_list.last_instruction_;
1879 } else {
1880 cursor->next_->previous_ = instruction_list.last_instruction_;
1881 }
1882 instruction_list.last_instruction_->next_ = cursor->next_;
1883 cursor->next_ = instruction_list.first_instruction_;
1884 instruction_list.first_instruction_->previous_ = cursor;
1885 }
1886}
1887
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001888void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1889 DCHECK(Contains(cursor));
1890 if (!instruction_list.IsEmpty()) {
1891 if (cursor == first_instruction_) {
1892 first_instruction_ = instruction_list.first_instruction_;
1893 } else {
1894 cursor->previous_->next_ = instruction_list.first_instruction_;
1895 }
1896 instruction_list.last_instruction_->next_ = cursor;
1897 instruction_list.first_instruction_->previous_ = cursor->previous_;
1898 cursor->previous_ = instruction_list.last_instruction_;
1899 }
1900}
1901
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001902void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001903 if (IsEmpty()) {
1904 first_instruction_ = instruction_list.first_instruction_;
1905 last_instruction_ = instruction_list.last_instruction_;
1906 } else {
1907 AddAfter(last_instruction_, instruction_list);
1908 }
1909}
1910
David Brazdil04ff4e82015-12-10 13:54:52 +00001911// Should be called on instructions in a dead block in post order. This method
1912// assumes `insn` has been removed from all users with the exception of catch
1913// phis because of missing exceptional edges in the graph. It removes the
1914// instruction from catch phi uses, together with inputs of other catch phis in
1915// the catch block at the same index, as these must be dead too.
1916static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1917 DCHECK(!insn->HasEnvironmentUses());
1918 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001919 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1920 size_t use_index = use.GetIndex();
1921 HBasicBlock* user_block = use.GetUser()->GetBlock();
1922 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001923 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1924 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1925 }
1926 }
1927}
1928
David Brazdil2d7352b2015-04-20 14:52:42 +01001929void HBasicBlock::DisconnectAndDelete() {
1930 // Dominators must be removed after all the blocks they dominate. This way
1931 // a loop header is removed last, a requirement for correct loop information
1932 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001933 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001934
David Brazdil9eeebf62016-03-24 11:18:15 +00001935 // The following steps gradually remove the block from all its dependants in
1936 // post order (b/27683071).
1937
1938 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1939 // We need to do this before step (4) which destroys the predecessor list.
1940 HBasicBlock* loop_update_start = this;
1941 if (IsLoopHeader()) {
1942 HLoopInformation* loop_info = GetLoopInformation();
1943 // All other blocks in this loop should have been removed because the header
1944 // was their dominator.
1945 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1946 DCHECK(!loop_info->IsIrreducible());
1947 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1948 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1949 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001950 }
1951
David Brazdil9eeebf62016-03-24 11:18:15 +00001952 // (2) Disconnect the block from its successors and update their phis.
1953 for (HBasicBlock* successor : successors_) {
1954 // Delete this block from the list of predecessors.
1955 size_t this_index = successor->GetPredecessorIndexOf(this);
1956 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1957
1958 // Check that `successor` has other predecessors, otherwise `this` is the
1959 // dominator of `successor` which violates the order DCHECKed at the top.
1960 DCHECK(!successor->predecessors_.empty());
1961
1962 // Remove this block's entries in the successor's phis. Skip exceptional
1963 // successors because catch phi inputs do not correspond to predecessor
1964 // blocks but throwing instructions. The inputs of the catch phis will be
1965 // updated in step (3).
1966 if (!successor->IsCatchBlock()) {
1967 if (successor->predecessors_.size() == 1u) {
1968 // The successor has just one predecessor left. Replace phis with the only
1969 // remaining input.
1970 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1971 HPhi* phi = phi_it.Current()->AsPhi();
1972 phi->ReplaceWith(phi->InputAt(1 - this_index));
1973 successor->RemovePhi(phi);
1974 }
1975 } else {
1976 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1977 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1978 }
1979 }
1980 }
1981 }
1982 successors_.clear();
1983
1984 // (3) Remove instructions and phis. Instructions should have no remaining uses
1985 // except in catch phis. If an instruction is used by a catch phi at `index`,
1986 // remove `index`-th input of all phis in the catch block since they are
1987 // guaranteed dead. Note that we may miss dead inputs this way but the
1988 // graph will always remain consistent.
1989 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1990 HInstruction* insn = it.Current();
1991 RemoveUsesOfDeadInstruction(insn);
1992 RemoveInstruction(insn);
1993 }
1994 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1995 HPhi* insn = it.Current()->AsPhi();
1996 RemoveUsesOfDeadInstruction(insn);
1997 RemovePhi(insn);
1998 }
1999
2000 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002001 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002002 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002003 // We should not see any back edges as they would have been removed by step (3).
2004 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2005
David Brazdil2d7352b2015-04-20 14:52:42 +01002006 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002007 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2008 // This block is the only normal-flow successor of the TryBoundary which
2009 // makes `predecessor` dead. Since DCE removes blocks in post order,
2010 // exception handlers of this TryBoundary were already visited and any
2011 // remaining handlers therefore must be live. We remove `predecessor` from
2012 // their list of predecessors.
2013 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2014 while (predecessor->GetSuccessors().size() > 1) {
2015 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2016 DCHECK(handler->IsCatchBlock());
2017 predecessor->RemoveSuccessor(handler);
2018 handler->RemovePredecessor(predecessor);
2019 }
2020 }
2021
David Brazdil2d7352b2015-04-20 14:52:42 +01002022 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002023 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2024 if (num_pred_successors == 1u) {
2025 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002026 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2027 // successor. Replace those with a HGoto.
2028 DCHECK(last_instruction->IsIf() ||
2029 last_instruction->IsPackedSwitch() ||
2030 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002031 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06002032 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002033 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002034 // The predecessor has no remaining successors and therefore must be dead.
2035 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002036 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002037 predecessor->RemoveInstruction(last_instruction);
2038 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002039 // There are multiple successors left. The removed block might be a successor
2040 // of a PackedSwitch which will be completely removed (perhaps replaced with
2041 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2042 // case, leave `last_instruction` as is for now.
2043 DCHECK(last_instruction->IsPackedSwitch() ||
2044 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002045 }
David Brazdil46e2a392015-03-16 17:31:52 +00002046 }
Vladimir Marko60584552015-09-03 13:35:12 +00002047 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002048
David Brazdil9eeebf62016-03-24 11:18:15 +00002049 // (5) Remove the block from all loops it is included in. Skip the inner-most
2050 // loop if this is the loop header (see definition of `loop_update_start`)
2051 // because the loop header's predecessor list has been destroyed in step (4).
2052 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2053 HLoopInformation* loop_info = it.Current();
2054 loop_info->Remove(this);
2055 if (loop_info->IsBackEdge(*this)) {
2056 // If this was the last back edge of the loop, we deliberately leave the
2057 // loop in an inconsistent state and will fail GraphChecker unless the
2058 // entire loop is removed during the pass.
2059 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002060 }
2061 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002062
David Brazdil9eeebf62016-03-24 11:18:15 +00002063 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002064 dominator_->RemoveDominatedBlock(this);
2065 SetDominator(nullptr);
2066
David Brazdil9eeebf62016-03-24 11:18:15 +00002067 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002068 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002069 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002070}
2071
Aart Bik6b69e0a2017-01-11 10:20:43 -08002072void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2073 DCHECK(EndsWithControlFlowInstruction());
2074 RemoveInstruction(GetLastInstruction());
2075 instructions_.Add(other->GetInstructions());
2076 other->instructions_.SetBlockOfInstructions(this);
2077 other->instructions_.Clear();
2078}
2079
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002080void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002081 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002082 DCHECK(ContainsElement(dominated_blocks_, other));
2083 DCHECK_EQ(GetSingleSuccessor(), other);
2084 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002085 DCHECK(other->GetPhis().IsEmpty());
2086
David Brazdil2d7352b2015-04-20 14:52:42 +01002087 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002088 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002089
David Brazdil2d7352b2015-04-20 14:52:42 +01002090 // Remove `other` from the loops it is included in.
2091 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2092 HLoopInformation* loop_info = it.Current();
2093 loop_info->Remove(other);
2094 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002095 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002096 }
2097 }
2098
2099 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002100 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002101 for (HBasicBlock* successor : other->GetSuccessors()) {
2102 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002103 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002104 successors_.swap(other->successors_);
2105 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002106
David Brazdil2d7352b2015-04-20 14:52:42 +01002107 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002108 RemoveDominatedBlock(other);
2109 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002110 dominated->SetDominator(this);
2111 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002112 dominated_blocks_.insert(
2113 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002114 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002115 other->dominator_ = nullptr;
2116
2117 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002118 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002119
2120 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002121 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002122 other->SetGraph(nullptr);
2123}
2124
2125void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2126 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002127 DCHECK(GetDominatedBlocks().empty());
2128 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002129 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002130 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002131 DCHECK(other->GetPhis().IsEmpty());
2132 DCHECK(!other->IsInLoop());
2133
2134 // Move instructions from `other` to `this`.
2135 instructions_.Add(other->GetInstructions());
2136 other->instructions_.SetBlockOfInstructions(this);
2137
2138 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002139 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002140 for (HBasicBlock* successor : other->GetSuccessors()) {
2141 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002142 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002143 successors_.swap(other->successors_);
2144 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002145
2146 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002147 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002148 dominated->SetDominator(this);
2149 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002150 dominated_blocks_.insert(
2151 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002152 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002153 other->dominator_ = nullptr;
2154 other->graph_ = nullptr;
2155}
2156
2157void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002158 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002159 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002160 predecessor->ReplaceSuccessor(this, other);
2161 }
Vladimir Marko60584552015-09-03 13:35:12 +00002162 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002163 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002164 successor->ReplacePredecessor(this, other);
2165 }
Vladimir Marko60584552015-09-03 13:35:12 +00002166 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2167 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002168 }
2169 GetDominator()->ReplaceDominatedBlock(this, other);
2170 other->SetDominator(GetDominator());
2171 dominator_ = nullptr;
2172 graph_ = nullptr;
2173}
2174
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002175void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002176 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002177 DCHECK(block->GetSuccessors().empty());
2178 DCHECK(block->GetPredecessors().empty());
2179 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002180 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002181 DCHECK(block->GetInstructions().IsEmpty());
2182 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002183
David Brazdilc7af85d2015-05-26 12:05:55 +01002184 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002185 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002186 }
2187
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002188 RemoveElement(reverse_post_order_, block);
2189 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002190 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002191}
2192
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002193void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2194 HBasicBlock* reference,
2195 bool replace_if_back_edge) {
2196 if (block->IsLoopHeader()) {
2197 // Clear the information of which blocks are contained in that loop. Since the
2198 // information is stored as a bit vector based on block ids, we have to update
2199 // it, as those block ids were specific to the callee graph and we are now adding
2200 // these blocks to the caller graph.
2201 block->GetLoopInformation()->ClearAllBlocks();
2202 }
2203
2204 // If not already in a loop, update the loop information.
2205 if (!block->IsInLoop()) {
2206 block->SetLoopInformation(reference->GetLoopInformation());
2207 }
2208
2209 // If the block is in a loop, update all its outward loops.
2210 HLoopInformation* loop_info = block->GetLoopInformation();
2211 if (loop_info != nullptr) {
2212 for (HLoopInformationOutwardIterator loop_it(*block);
2213 !loop_it.Done();
2214 loop_it.Advance()) {
2215 loop_it.Current()->Add(block);
2216 }
2217 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2218 loop_info->ReplaceBackEdge(reference, block);
2219 }
2220 }
2221
2222 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2223 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2224 ? reference->GetTryCatchInformation()
2225 : nullptr;
2226 block->SetTryCatchInformation(try_catch_info);
2227}
2228
Calin Juravle2e768302015-07-28 14:41:11 +00002229HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002230 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002231 // Update the environments in this graph to have the invoke's environment
2232 // as parent.
2233 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002234 // Skip the entry block, we do not need to update the entry's suspend check.
2235 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002236 for (HInstructionIterator instr_it(block->GetInstructions());
2237 !instr_it.Done();
2238 instr_it.Advance()) {
2239 HInstruction* current = instr_it.Current();
2240 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002241 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002242 current->GetEnvironment()->SetAndCopyParentChain(
2243 outer_graph->GetArena(), invoke->GetEnvironment());
2244 }
2245 }
2246 }
2247 }
2248 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002249
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002250 if (HasBoundsChecks()) {
2251 outer_graph->SetHasBoundsChecks(true);
2252 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002253 if (HasLoops()) {
2254 outer_graph->SetHasLoops(true);
2255 }
2256 if (HasIrreducibleLoops()) {
2257 outer_graph->SetHasIrreducibleLoops(true);
2258 }
2259 if (HasTryCatch()) {
2260 outer_graph->SetHasTryCatch(true);
2261 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002262 if (HasSIMD()) {
2263 outer_graph->SetHasSIMD(true);
2264 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002265
Calin Juravle2e768302015-07-28 14:41:11 +00002266 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002267 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002268 // Inliner already made sure we don't inline methods that always throw.
2269 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002270 // Simple case of an entry block, a body block, and an exit block.
2271 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002272 HBasicBlock* body = GetBlocks()[1];
2273 DCHECK(GetBlocks()[0]->IsEntryBlock());
2274 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002275 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002276 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002277 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002278
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002279 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2280 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002281 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002282
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002283 // Replace the invoke with the return value of the inlined graph.
2284 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002285 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002286 } else {
2287 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002288 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002289
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002290 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002291 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002292 // Need to inline multiple blocks. We split `invoke`'s block
2293 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002294 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002295 // with the second half.
2296 ArenaAllocator* allocator = outer_graph->GetArena();
2297 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002298 // Note that we split before the invoke only to simplify polymorphic inlining.
2299 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002300
Vladimir Markoec7802a2015-10-01 20:57:57 +01002301 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002302 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002303 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002304 exit_block_->ReplaceWith(to);
2305
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002306 // Update the meta information surrounding blocks:
2307 // (1) the graph they are now in,
2308 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002309 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002310 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002311 // Note that we do not need to update catch phi inputs because they
2312 // correspond to the register file of the outer method which the inlinee
2313 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002314
2315 // We don't add the entry block, the exit block, and the first block, which
2316 // has been merged with `at`.
2317 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2318
2319 // We add the `to` block.
2320 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002321 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002322 + kNumberOfNewBlocksInCaller;
2323
2324 // Find the location of `at` in the outer graph's reverse post order. The new
2325 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002326 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002327 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2328
David Brazdil95177982015-10-30 12:56:58 -05002329 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2330 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002331 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002332 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002333 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002334 DCHECK(current->GetGraph() == this);
2335 current->SetGraph(outer_graph);
2336 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002337 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002338 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002339 }
2340 }
2341
David Brazdil95177982015-10-30 12:56:58 -05002342 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002343 to->SetGraph(outer_graph);
2344 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002345 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002346 // Only `to` can become a back edge, as the inlined blocks
2347 // are predecessors of `to`.
2348 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002349
David Brazdil3f523062016-02-29 16:53:33 +00002350 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002351 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2352 // to now get the outer graph exit block as successor. Note that the inliner
2353 // currently doesn't support inlining methods with try/catch.
2354 HPhi* return_value_phi = nullptr;
2355 bool rerun_dominance = false;
2356 bool rerun_loop_analysis = false;
2357 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2358 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002359 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002360 if (last->IsThrow()) {
2361 DCHECK(!at->IsTryBlock());
2362 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2363 --pred;
2364 // We need to re-run dominance information, as the exit block now has
2365 // a new dominator.
2366 rerun_dominance = true;
2367 if (predecessor->GetLoopInformation() != nullptr) {
2368 // The exit block and blocks post dominated by the exit block do not belong
2369 // to any loop. Because we do not compute the post dominators, we need to re-run
2370 // loop analysis to get the loop information correct.
2371 rerun_loop_analysis = true;
2372 }
2373 } else {
2374 if (last->IsReturnVoid()) {
2375 DCHECK(return_value == nullptr);
2376 DCHECK(return_value_phi == nullptr);
2377 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002378 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002379 if (return_value_phi != nullptr) {
2380 return_value_phi->AddInput(last->InputAt(0));
2381 } else if (return_value == nullptr) {
2382 return_value = last->InputAt(0);
2383 } else {
2384 // There will be multiple returns.
2385 return_value_phi = new (allocator) HPhi(
2386 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2387 to->AddPhi(return_value_phi);
2388 return_value_phi->AddInput(return_value);
2389 return_value_phi->AddInput(last->InputAt(0));
2390 return_value = return_value_phi;
2391 }
David Brazdil3f523062016-02-29 16:53:33 +00002392 }
2393 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2394 predecessor->RemoveInstruction(last);
2395 }
2396 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002397 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002398 DCHECK(!outer_graph->HasIrreducibleLoops())
2399 << "Recomputing loop information in graphs with irreducible loops "
2400 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002401 outer_graph->ClearLoopInformation();
2402 outer_graph->ClearDominanceInformation();
2403 outer_graph->BuildDominatorTree();
2404 } else if (rerun_dominance) {
2405 outer_graph->ClearDominanceInformation();
2406 outer_graph->ComputeDominanceInformation();
2407 }
David Brazdil3f523062016-02-29 16:53:33 +00002408 }
David Brazdil05144f42015-04-16 15:18:00 +01002409
2410 // Walk over the entry block and:
2411 // - Move constants from the entry block to the outer_graph's entry block,
2412 // - Replace HParameterValue instructions with their real value.
2413 // - Remove suspend checks, that hold an environment.
2414 // We must do this after the other blocks have been inlined, otherwise ids of
2415 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002416 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002417 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2418 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002419 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002420 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002421 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002422 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002423 replacement = outer_graph->GetIntConstant(
2424 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002425 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002426 replacement = outer_graph->GetLongConstant(
2427 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002428 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002429 replacement = outer_graph->GetFloatConstant(
2430 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002431 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002432 replacement = outer_graph->GetDoubleConstant(
2433 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002434 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002435 if (kIsDebugBuild
2436 && invoke->IsInvokeStaticOrDirect()
2437 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2438 // Ensure we do not use the last input of `invoke`, as it
2439 // contains a clinit check which is not an actual argument.
2440 size_t last_input_index = invoke->InputCount() - 1;
2441 DCHECK(parameter_index != last_input_index);
2442 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002443 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002444 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002445 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002446 } else {
2447 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2448 entry_block_->RemoveInstruction(current);
2449 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002450 if (replacement != nullptr) {
2451 current->ReplaceWith(replacement);
2452 // If the current is the return value then we need to update the latter.
2453 if (current == return_value) {
2454 DCHECK_EQ(entry_block_, return_value->GetBlock());
2455 return_value = replacement;
2456 }
2457 }
2458 }
2459
Calin Juravle2e768302015-07-28 14:41:11 +00002460 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002461}
2462
Mingyao Yang3584bce2015-05-19 16:01:59 -07002463/*
2464 * Loop will be transformed to:
2465 * old_pre_header
2466 * |
2467 * if_block
2468 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002469 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002470 * \ /
2471 * new_pre_header
2472 * |
2473 * header
2474 */
2475void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2476 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002477 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002478
Aart Bik3fc7f352015-11-20 22:03:03 -08002479 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002480 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002481 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2482 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002483 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2484 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002485 AddBlock(true_block);
2486 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002487 AddBlock(new_pre_header);
2488
Aart Bik3fc7f352015-11-20 22:03:03 -08002489 header->ReplacePredecessor(old_pre_header, new_pre_header);
2490 old_pre_header->successors_.clear();
2491 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002492
Aart Bik3fc7f352015-11-20 22:03:03 -08002493 old_pre_header->AddSuccessor(if_block);
2494 if_block->AddSuccessor(true_block); // True successor
2495 if_block->AddSuccessor(false_block); // False successor
2496 true_block->AddSuccessor(new_pre_header);
2497 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002498
Aart Bik3fc7f352015-11-20 22:03:03 -08002499 old_pre_header->dominated_blocks_.push_back(if_block);
2500 if_block->SetDominator(old_pre_header);
2501 if_block->dominated_blocks_.push_back(true_block);
2502 true_block->SetDominator(if_block);
2503 if_block->dominated_blocks_.push_back(false_block);
2504 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002505 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002506 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002507 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002508 header->SetDominator(new_pre_header);
2509
Aart Bik3fc7f352015-11-20 22:03:03 -08002510 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002511 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002512 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002513 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002514 reverse_post_order_[index_of_header++] = true_block;
2515 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002516 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002517
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002518 // The pre_header can never be a back edge of a loop.
2519 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2520 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2521 UpdateLoopAndTryInformationOfNewBlock(
2522 if_block, old_pre_header, /* replace_if_back_edge */ false);
2523 UpdateLoopAndTryInformationOfNewBlock(
2524 true_block, old_pre_header, /* replace_if_back_edge */ false);
2525 UpdateLoopAndTryInformationOfNewBlock(
2526 false_block, old_pre_header, /* replace_if_back_edge */ false);
2527 UpdateLoopAndTryInformationOfNewBlock(
2528 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002529}
2530
Aart Bikf8f5a162017-02-06 15:35:29 -08002531HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2532 HBasicBlock* body,
2533 HBasicBlock* exit) {
2534 DCHECK(header->IsLoopHeader());
2535 HLoopInformation* loop = header->GetLoopInformation();
2536
2537 // Add new loop blocks.
2538 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2539 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2540 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2541 AddBlock(new_pre_header);
2542 AddBlock(new_header);
2543 AddBlock(new_body);
2544
2545 // Set up control flow.
2546 header->ReplaceSuccessor(exit, new_pre_header);
2547 new_pre_header->AddSuccessor(new_header);
2548 new_header->AddSuccessor(exit);
2549 new_header->AddSuccessor(new_body);
2550 new_body->AddSuccessor(new_header);
2551
2552 // Set up dominators.
2553 header->ReplaceDominatedBlock(exit, new_pre_header);
2554 new_pre_header->SetDominator(header);
2555 new_pre_header->dominated_blocks_.push_back(new_header);
2556 new_header->SetDominator(new_pre_header);
2557 new_header->dominated_blocks_.push_back(new_body);
2558 new_body->SetDominator(new_header);
2559 new_header->dominated_blocks_.push_back(exit);
2560 exit->SetDominator(new_header);
2561
2562 // Fix reverse post order.
2563 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2564 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2565 reverse_post_order_[++index_of_header] = new_pre_header;
2566 reverse_post_order_[++index_of_header] = new_header;
2567 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2568 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2569 reverse_post_order_[index_of_body] = new_body;
2570
Aart Bikb07d1bc2017-04-05 10:03:15 -07002571 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002572 new_pre_header->AddInstruction(new (arena_) HGoto());
2573 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2574 new_header->AddInstruction(suspend_check);
2575 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002576 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2577 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002578
2579 // Update loop information.
2580 new_header->AddBackEdge(new_body);
2581 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2582 new_header->GetLoopInformation()->Populate();
2583 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2584 HLoopInformationOutwardIterator it(*new_header);
2585 for (it.Advance(); !it.Done(); it.Advance()) {
2586 it.Current()->Add(new_pre_header);
2587 it.Current()->Add(new_header);
2588 it.Current()->Add(new_body);
2589 }
2590 return new_pre_header;
2591}
2592
David Brazdilf5552582015-12-27 13:36:12 +00002593static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002594 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002595 if (rti.IsValid()) {
2596 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2597 << " upper_bound_rti: " << upper_bound_rti
2598 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002599 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2600 << " upper_bound_rti: " << upper_bound_rti
2601 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002602 }
2603}
2604
Calin Juravle2e768302015-07-28 14:41:11 +00002605void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2606 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002607 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002608 ScopedObjectAccess soa(Thread::Current());
2609 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2610 if (IsBoundType()) {
2611 // Having the test here spares us from making the method virtual just for
2612 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002613 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002614 }
2615 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002616 reference_type_handle_ = rti.GetTypeHandle();
2617 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002618}
2619
David Brazdilf5552582015-12-27 13:36:12 +00002620void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2621 if (kIsDebugBuild) {
2622 ScopedObjectAccess soa(Thread::Current());
2623 DCHECK(upper_bound.IsValid());
2624 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2625 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2626 }
2627 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002628 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002629}
2630
Vladimir Markoa1de9182016-02-25 11:37:38 +00002631ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002632 if (kIsDebugBuild) {
2633 ScopedObjectAccess soa(Thread::Current());
2634 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002635 if (!is_exact) {
2636 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2637 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2638 }
Calin Juravle2e768302015-07-28 14:41:11 +00002639 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002640 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002641}
2642
Calin Juravleacf735c2015-02-12 15:25:22 +00002643std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2644 ScopedObjectAccess soa(Thread::Current());
2645 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002646 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002647 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002648 << " is_exact=" << rhs.IsExact()
2649 << " ]";
2650 return os;
2651}
2652
Mark Mendellc4701932015-04-10 13:18:51 -04002653bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2654 // For now, assume that instructions in different blocks may use the
2655 // environment.
2656 // TODO: Use the control flow to decide if this is true.
2657 if (GetBlock() != other->GetBlock()) {
2658 return true;
2659 }
2660
2661 // We know that we are in the same block. Walk from 'this' to 'other',
2662 // checking to see if there is any instruction with an environment.
2663 HInstruction* current = this;
2664 for (; current != other && current != nullptr; current = current->GetNext()) {
2665 // This is a conservative check, as the instruction result may not be in
2666 // the referenced environment.
2667 if (current->HasEnvironment()) {
2668 return true;
2669 }
2670 }
2671
2672 // We should have been called with 'this' before 'other' in the block.
2673 // Just confirm this.
2674 DCHECK(current != nullptr);
2675 return false;
2676}
2677
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002678void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002679 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2680 IntrinsicSideEffects side_effects,
2681 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002682 intrinsic_ = intrinsic;
2683 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002684
Aart Bik5d75afe2015-12-14 11:57:01 -08002685 // Adjust method's side effects from intrinsic table.
2686 switch (side_effects) {
2687 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2688 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2689 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2690 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2691 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002692
2693 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2694 opt.SetDoesNotNeedDexCache();
2695 opt.SetDoesNotNeedEnvironment();
2696 } else {
2697 // If we need an environment, that means there will be a call, which can trigger GC.
2698 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2699 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002700 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002701 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002702}
2703
David Brazdil6de19382016-01-08 17:37:10 +00002704bool HNewInstance::IsStringAlloc() const {
2705 ScopedObjectAccess soa(Thread::Current());
2706 return GetReferenceTypeInfo().IsStringClass();
2707}
2708
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002709bool HInvoke::NeedsEnvironment() const {
2710 if (!IsIntrinsic()) {
2711 return true;
2712 }
2713 IntrinsicOptimizations opt(*this);
2714 return !opt.GetDoesNotNeedEnvironment();
2715}
2716
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002717const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2718 ArtMethod* caller = GetEnvironment()->GetMethod();
2719 ScopedObjectAccess soa(Thread::Current());
2720 // `caller` is null for a top-level graph representing a method whose declaring
2721 // class was not resolved.
2722 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2723}
2724
Vladimir Markodc151b22015-10-15 18:02:30 +01002725bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002726 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002727 return false;
2728 }
2729 if (!IsIntrinsic()) {
2730 return true;
2731 }
2732 IntrinsicOptimizations opt(*this);
2733 return !opt.GetDoesNotNeedDexCache();
2734}
2735
Vladimir Markof64242a2015-12-01 14:58:23 +00002736std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2737 switch (rhs) {
2738 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002739 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002740 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002741 return os << "Recursive";
2742 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2743 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002744 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002745 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002746 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2747 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002748 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2749 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002750 default:
2751 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2752 UNREACHABLE();
2753 }
2754}
2755
Vladimir Markofbb184a2015-11-13 14:47:00 +00002756std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2757 switch (rhs) {
2758 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2759 return os << "explicit";
2760 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2761 return os << "implicit";
2762 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2763 return os << "none";
2764 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002765 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2766 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002767 }
2768}
2769
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002770bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2771 const HLoadClass* other_load_class = other->AsLoadClass();
2772 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2773 // names rather than type indexes. However, we shall also have to re-think the hash code.
2774 if (type_index_ != other_load_class->type_index_ ||
2775 GetPackedFields() != other_load_class->GetPackedFields()) {
2776 return false;
2777 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002778 switch (GetLoadKind()) {
2779 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002780 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002781 case LoadKind::kJitTableAddress: {
2782 ScopedObjectAccess soa(Thread::Current());
2783 return GetClass().Get() == other_load_class->GetClass().Get();
2784 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002785 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002786 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002787 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002788 }
2789}
2790
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002791void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002792 SetPackedField<LoadKindField>(load_kind);
2793
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002794 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002795 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002796 RemoveAsUserOfInput(0u);
2797 SetRawInputAt(0u, nullptr);
2798 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002799
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002800 if (!NeedsEnvironment()) {
2801 RemoveEnvironment();
2802 SetSideEffects(SideEffects::None());
2803 }
2804}
2805
2806std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2807 switch (rhs) {
2808 case HLoadClass::LoadKind::kReferrersClass:
2809 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002810 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2811 return os << "BootImageLinkTimePcRelative";
2812 case HLoadClass::LoadKind::kBootImageAddress:
2813 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002814 case HLoadClass::LoadKind::kBootImageClassTable:
2815 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002816 case HLoadClass::LoadKind::kBssEntry:
2817 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002818 case HLoadClass::LoadKind::kJitTableAddress:
2819 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002820 case HLoadClass::LoadKind::kRuntimeCall:
2821 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002822 default:
2823 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2824 UNREACHABLE();
2825 }
2826}
2827
Vladimir Marko372f10e2016-05-17 16:30:10 +01002828bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2829 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002830 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2831 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002832 if (string_index_ != other_load_string->string_index_ ||
2833 GetPackedFields() != other_load_string->GetPackedFields()) {
2834 return false;
2835 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002836 switch (GetLoadKind()) {
2837 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002838 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002839 case LoadKind::kJitTableAddress: {
2840 ScopedObjectAccess soa(Thread::Current());
2841 return GetString().Get() == other_load_string->GetString().Get();
2842 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002843 default:
2844 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002845 }
2846}
2847
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002848void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002849 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002850 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002851 SetPackedField<LoadKindField>(load_kind);
2852
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002853 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002854 RemoveAsUserOfInput(0u);
2855 SetRawInputAt(0u, nullptr);
2856 }
2857 if (!NeedsEnvironment()) {
2858 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002859 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002860 }
2861}
2862
2863std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2864 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002865 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2866 return os << "BootImageLinkTimePcRelative";
2867 case HLoadString::LoadKind::kBootImageAddress:
2868 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002869 case HLoadString::LoadKind::kBootImageInternTable:
2870 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002871 case HLoadString::LoadKind::kBssEntry:
2872 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002873 case HLoadString::LoadKind::kJitTableAddress:
2874 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002875 case HLoadString::LoadKind::kRuntimeCall:
2876 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002877 default:
2878 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2879 UNREACHABLE();
2880 }
2881}
2882
Mark Mendellc4701932015-04-10 13:18:51 -04002883void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002884 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2885 HEnvironment* user = use.GetUser();
2886 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002887 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002888 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002889}
2890
Roland Levillainc9b21f82016-03-23 16:36:59 +00002891// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002892HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2893 ArenaAllocator* allocator = GetArena();
2894
2895 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002896 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05002897 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2898 HInstruction* lhs = cond->InputAt(0);
2899 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002900 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002901 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2902 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2903 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2904 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2905 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2906 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2907 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2908 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2909 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2910 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2911 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002912 default:
2913 LOG(FATAL) << "Unexpected condition";
2914 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002915 }
2916 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2917 return replacement;
2918 } else if (cond->IsIntConstant()) {
2919 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002920 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002921 return GetIntConstant(1);
2922 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002923 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002924 return GetIntConstant(0);
2925 }
2926 } else {
2927 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2928 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2929 return replacement;
2930 }
2931}
2932
Roland Levillainc9285912015-12-18 10:38:42 +00002933std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2934 os << "["
2935 << " source=" << rhs.GetSource()
2936 << " destination=" << rhs.GetDestination()
2937 << " type=" << rhs.GetType()
2938 << " instruction=";
2939 if (rhs.GetInstruction() != nullptr) {
2940 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2941 } else {
2942 os << "null";
2943 }
2944 os << " ]";
2945 return os;
2946}
2947
Roland Levillain86503782016-02-11 19:07:30 +00002948std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2949 switch (rhs) {
2950 case TypeCheckKind::kUnresolvedCheck:
2951 return os << "unresolved_check";
2952 case TypeCheckKind::kExactCheck:
2953 return os << "exact_check";
2954 case TypeCheckKind::kClassHierarchyCheck:
2955 return os << "class_hierarchy_check";
2956 case TypeCheckKind::kAbstractClassCheck:
2957 return os << "abstract_class_check";
2958 case TypeCheckKind::kInterfaceCheck:
2959 return os << "interface_check";
2960 case TypeCheckKind::kArrayObjectCheck:
2961 return os << "array_object_check";
2962 case TypeCheckKind::kArrayCheck:
2963 return os << "array_check";
2964 default:
2965 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2966 UNREACHABLE();
2967 }
2968}
2969
Andreas Gampe26de38b2016-07-27 17:53:11 -07002970std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2971 switch (kind) {
2972 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002973 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002974 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002975 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002976 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002977 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002978 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002979 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002980 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002981 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002982
2983 default:
2984 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2985 UNREACHABLE();
2986 }
2987}
2988
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002989} // namespace art