blob: e9a2f967985013fd9a9f3091ade4bf284bf3d83e [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"
Andreas Gampe85f1c572018-11-21 13:52:48 -080023#include "base/logging.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080025#include "class_linker-inl.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010026#include "class_root.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040027#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000028#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010029#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010030#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070031#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070032#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033
34namespace art {
35
Roland Levillain31dd3d62016-02-16 12:21:02 +000036// Enable floating-point static evaluation during constant folding
37// only if all floating-point operations and constants evaluate in the
38// range and precision of the type used (i.e., 32-bit float, 64-bit
39// double).
40static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
41
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070042void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000043 ScopedObjectAccess soa(Thread::Current());
44 // Create the inexact Object reference type and store it in the HGraph.
David Brazdilbadd8262016-02-02 16:28:56 +000045 inexact_object_rti_ = ReferenceTypeInfo::Create(
Vladimir Markob4eb1b12018-05-24 11:09:38 +010046 handles->NewHandle(GetClassRoot<mirror::Object>()),
Andreas Gampe3db70682018-12-26 15:12:03 -080047 /* is_exact= */ false);
David Brazdilbadd8262016-02-02 16:28:56 +000048}
49
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010051 block->SetBlockId(blocks_.size());
52 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000053}
54
Nicolas Geoffray804d0932014-05-02 08:46:00 +010055void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010056 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
57 DCHECK_EQ(visited->GetHighestBitSet(), -1);
58
Vladimir Marko69d310e2017-10-09 14:12:23 +010059 // Allocate memory from local ScopedArenaAllocator.
60 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010061 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010062 ArenaBitVector visiting(
Andreas Gampe3db70682018-12-26 15:12:03 -080063 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +010064 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010065 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010066 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
67 0u,
68 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010069 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010070 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010071 constexpr size_t kDefaultWorklistSize = 8;
72 worklist.reserve(kDefaultWorklistSize);
73 visited->SetBit(entry_block_->GetBlockId());
74 visiting.SetBit(entry_block_->GetBlockId());
75 worklist.push_back(entry_block_);
76
77 while (!worklist.empty()) {
78 HBasicBlock* current = worklist.back();
79 uint32_t current_id = current->GetBlockId();
80 if (successors_visited[current_id] == current->GetSuccessors().size()) {
81 visiting.ClearBit(current_id);
82 worklist.pop_back();
83 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010084 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
85 uint32_t successor_id = successor->GetBlockId();
86 if (visiting.IsBitSet(successor_id)) {
87 DCHECK(ContainsElement(worklist, successor));
88 successor->AddBackEdge(current);
89 } else if (!visited->IsBitSet(successor_id)) {
90 visited->SetBit(successor_id);
91 visiting.SetBit(successor_id);
92 worklist.push_back(successor);
93 }
94 }
95 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000096}
97
Artem Serov21c7e6f2017-07-27 16:04:42 +010098// Remove the environment use records of the instruction for users.
99void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100100 for (HEnvironment* environment = instruction->GetEnvironment();
101 environment != nullptr;
102 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000103 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000104 if (environment->GetInstructionAt(i) != nullptr) {
105 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 }
107 }
108 }
109}
110
Artem Serov21c7e6f2017-07-27 16:04:42 +0100111// Return whether the instruction has an environment and it's used by others.
112bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
113 for (HEnvironment* environment = instruction->GetEnvironment();
114 environment != nullptr;
115 environment = environment->GetParent()) {
116 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
117 HInstruction* user = environment->GetInstructionAt(i);
118 if (user != nullptr) {
119 return true;
120 }
121 }
122 }
123 return false;
124}
125
126// Reset environment records of the instruction itself.
127void ResetEnvironmentInputRecords(HInstruction* instruction) {
128 for (HEnvironment* environment = instruction->GetEnvironment();
129 environment != nullptr;
130 environment = environment->GetParent()) {
131 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
132 DCHECK(environment->GetHolder() == instruction);
133 if (environment->GetInstructionAt(i) != nullptr) {
134 environment->SetRawEnvAt(i, nullptr);
135 }
136 }
137 }
138}
139
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000140static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100141 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000142 RemoveEnvironmentUses(instruction);
143}
144
Roland Levillainfc600dc2014-12-02 17:16:31 +0000145void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100146 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000147 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100148 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000149 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100150 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000151 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
152 RemoveAsUser(it.Current());
153 }
154 }
155 }
156}
157
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100159 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000160 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100161 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000162 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100163 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000164 for (HBasicBlock* successor : block->GetSuccessors()) {
165 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000166 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100167 // Remove the block from the list of blocks, so that further analyses
168 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100169 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600170 if (block->IsExitBlock()) {
171 SetExitBlock(nullptr);
172 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000173 // Mark the block as removed. This is used by the HGraphBuilder to discard
174 // the block as a branch target.
175 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000176 }
177 }
178}
179
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000180GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100181 // Allocate memory from local ScopedArenaAllocator.
182 ScopedArenaAllocator allocator(GetArenaStack());
183
184 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
185 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000186
David Brazdil86ea7ee2016-02-16 09:26:07 +0000187 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 FindBackEdges(&visited);
189
David Brazdil86ea7ee2016-02-16 09:26:07 +0000190 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000191 // the initial DFS as users from other instructions, so that
192 // users can be safely removed before uses later.
193 RemoveInstructionsAsUsersFromDeadBlocks(visited);
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000196 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000197 // predecessors list of live blocks.
198 RemoveDeadBlocks(visited);
199
David Brazdil86ea7ee2016-02-16 09:26:07 +0000200 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100201 // dominators and the reverse post order.
202 SimplifyCFG();
203
David Brazdil86ea7ee2016-02-16 09:26:07 +0000204 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100205 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206
David Brazdil86ea7ee2016-02-16 09:26:07 +0000207 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000208 // set the loop information on each block.
209 GraphAnalysisResult result = AnalyzeLoops();
210 if (result != kAnalysisSuccess) {
211 return result;
212 }
213
David Brazdil86ea7ee2016-02-16 09:26:07 +0000214 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000215 // which needs the information to build catch block phis from values of
216 // locals at throwing instructions inside try blocks.
217 ComputeTryBlockInformation();
218
219 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100220}
221
222void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100223 for (HBasicBlock* block : GetReversePostOrder()) {
224 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100225 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100226 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227}
228
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000229void HGraph::ClearLoopInformation() {
230 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100231 for (HBasicBlock* block : GetReversePostOrder()) {
232 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000233 }
234}
235
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100236void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000237 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100238 dominator_ = nullptr;
239}
240
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000241HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
242 HInstruction* instruction = GetFirstInstruction();
243 while (instruction->IsParallelMove()) {
244 instruction = instruction->GetNext();
245 }
246 return instruction;
247}
248
David Brazdil3f4a5222016-05-06 12:46:21 +0100249static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
250 DCHECK(ContainsElement(block->GetSuccessors(), successor));
251
252 HBasicBlock* old_dominator = successor->GetDominator();
253 HBasicBlock* new_dominator =
254 (old_dominator == nullptr) ? block
255 : CommonDominator::ForPair(old_dominator, block);
256
257 if (old_dominator == new_dominator) {
258 return false;
259 } else {
260 successor->SetDominator(new_dominator);
261 return true;
262 }
263}
264
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100265void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100266 DCHECK(reverse_post_order_.empty());
267 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100268 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100269
Vladimir Marko69d310e2017-10-09 14:12:23 +0100270 // Allocate memory from local ScopedArenaAllocator.
271 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100272 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100273 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100274 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100275 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
276 0u,
277 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100278 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100279 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100280 constexpr size_t kDefaultWorklistSize = 8;
281 worklist.reserve(kDefaultWorklistSize);
282 worklist.push_back(entry_block_);
283
284 while (!worklist.empty()) {
285 HBasicBlock* current = worklist.back();
286 uint32_t current_id = current->GetBlockId();
287 if (successors_visited[current_id] == current->GetSuccessors().size()) {
288 worklist.pop_back();
289 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100290 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100291 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100292
293 // Once all the forward edges have been visited, we know the immediate
294 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100295 if (++visits[successor->GetBlockId()] ==
296 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100297 reverse_post_order_.push_back(successor);
298 worklist.push_back(successor);
299 }
300 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000301 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000302
David Brazdil3f4a5222016-05-06 12:46:21 +0100303 // Check if the graph has back edges not dominated by their respective headers.
304 // If so, we need to update the dominators of those headers and recursively of
305 // their successors. We do that with a fix-point iteration over all blocks.
306 // The algorithm is guaranteed to terminate because it loops only if the sum
307 // of all dominator chains has decreased in the current iteration.
308 bool must_run_fix_point = false;
309 for (HBasicBlock* block : blocks_) {
310 if (block != nullptr &&
311 block->IsLoopHeader() &&
312 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
313 must_run_fix_point = true;
314 break;
315 }
316 }
317 if (must_run_fix_point) {
318 bool update_occurred = true;
319 while (update_occurred) {
320 update_occurred = false;
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 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
324 }
325 }
326 }
327 }
328
329 // Make sure that there are no remaining blocks whose dominator information
330 // needs to be updated.
331 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100332 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100333 for (HBasicBlock* successor : block->GetSuccessors()) {
334 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
335 }
336 }
337 }
338
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000339 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000340 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100341 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000342 if (!block->IsEntryBlock()) {
343 block->GetDominator()->AddDominatedBlock(block);
344 }
345 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000346}
347
David Brazdilfc6a86a2015-06-26 10:33:45 +0000348HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100349 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000350 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000351 // Use `InsertBetween` to ensure the predecessor index and successor index of
352 // `block` and `successor` are preserved.
353 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000354 return new_block;
355}
356
357void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
358 // Insert a new node between `block` and `successor` to split the
359 // critical edge.
360 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100361 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100362 if (successor->IsLoopHeader()) {
363 // If we split at a back edge boundary, make the new block the back edge.
364 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000365 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100366 info->RemoveBackEdge(block);
367 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100368 }
369 }
370}
371
Artem Serovc73ee372017-07-31 15:08:40 +0100372// Reorder phi inputs to match reordering of the block's predecessors.
373static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
374 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
375 HPhi* phi = it.Current()->AsPhi();
376 HInstruction* first_instr = phi->InputAt(first);
377 HInstruction* second_instr = phi->InputAt(second);
378 phi->ReplaceInput(first_instr, second);
379 phi->ReplaceInput(second_instr, first);
380 }
381}
382
383// Make sure that the first predecessor of a loop header is the incoming block.
384void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
385 DCHECK(header->IsLoopHeader());
386 HLoopInformation* info = header->GetLoopInformation();
387 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
388 HBasicBlock* to_swap = header->GetPredecessors()[0];
389 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
390 HBasicBlock* predecessor = header->GetPredecessors()[pred];
391 if (!info->IsBackEdge(*predecessor)) {
392 header->predecessors_[pred] = to_swap;
393 header->predecessors_[0] = predecessor;
394 FixPhisAfterPredecessorsReodering(header, 0, pred);
395 break;
396 }
397 }
398 }
399}
400
Artem Serov09faaea2017-12-07 14:36:01 +0000401// Transform control flow of the loop to a single preheader format (don't touch the data flow).
402// New_preheader can be already among the header predecessors - this situation will be correctly
403// processed.
404static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
405 HLoopInformation* loop_info = header->GetLoopInformation();
406 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
407 HBasicBlock* predecessor = header->GetPredecessors()[pred];
408 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
409 predecessor->ReplaceSuccessor(header, new_preheader);
410 pred--;
411 }
412 }
413}
414
415// == Before == == After ==
416// _________ _________ _________ _________
417// | B0 | | B1 | (old preheaders) | B0 | | B1 |
418// |=========| |=========| |=========| |=========|
419// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
420// |_________| |_________| |_________| |_________|
421// \ / \ /
422// \ / ___v____________v___
423// \ / (new preheader) | B20 <- B0, B1 |
424// | | |====================|
425// | | | i20 = phi(i0, i1) |
426// | | |____________________|
427// | | |
428// /\ | | /\ /\ | /\
429// / v_______v_________v_______v \ / v___________v_____________v \
430// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
431// | |===========================| | (header) | |===========================| |
432// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
433// | |___________________________| | | |___________________________| |
434// | / \ | | / \ |
435// | ... ... | | ... ... |
436// | _________ _________ | | _________ _________ |
437// | | B2 | | B3 | | | | B2 | | B3 | |
438// | |=========| |=========| | (back edges) | |=========| |=========| |
439// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
440// | |_________| |_________| | | |_________| |_________| |
441// \ / \ / \ / \ /
442// \___/ \___/ \___/ \___/
443//
444void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
445 HLoopInformation* loop_info = header->GetLoopInformation();
446
447 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
448 AddBlock(preheader);
449 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
450
451 // If the old header has no Phis then we only need to fix the control flow.
452 if (header->GetPhis().IsEmpty()) {
453 FixControlForNewSinglePreheader(header, preheader);
454 preheader->AddSuccessor(header);
455 return;
456 }
457
458 // Find the first non-back edge block in the header's predecessors list.
459 size_t first_nonbackedge_pred_pos = 0;
460 bool found = false;
461 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
462 HBasicBlock* predecessor = header->GetPredecessors()[pred];
463 if (!loop_info->IsBackEdge(*predecessor)) {
464 first_nonbackedge_pred_pos = pred;
465 found = true;
466 break;
467 }
468 }
469
470 DCHECK(found);
471
472 // Fix the data-flow.
473 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
474 HPhi* header_phi = it.Current()->AsPhi();
475
476 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
477 header_phi->GetRegNumber(),
478 0,
479 header_phi->GetType());
480 if (header_phi->GetType() == DataType::Type::kReference) {
481 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
482 }
483 preheader->AddPhi(preheader_phi);
484
485 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
486 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
487 preheader_phi->AddInput(orig_input);
488
489 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
490 input_pos < header_phi->InputCount();
491 input_pos++) {
492 HInstruction* input = header_phi->InputAt(input_pos);
493 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
494
495 if (loop_info->Contains(*pred_block)) {
496 DCHECK(loop_info->IsBackEdge(*pred_block));
497 } else {
498 preheader_phi->AddInput(input);
499 header_phi->RemoveInputAt(input_pos);
500 input_pos--;
501 }
502 }
503 }
504
505 // Fix the control-flow.
506 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
507 preheader->InsertBetween(first_pred, header);
508
509 FixControlForNewSinglePreheader(header, preheader);
510}
511
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100512void HGraph::SimplifyLoop(HBasicBlock* header) {
513 HLoopInformation* info = header->GetLoopInformation();
514
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100515 // Make sure the loop has only one pre header. This simplifies SSA building by having
516 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000517 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
518 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000519 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000520 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000521 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100522 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100523
Artem Serovc73ee372017-07-31 15:08:40 +0100524 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100525
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100526 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000527 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
528 // Called from DeadBlockElimination. Update SuspendCheck pointer.
529 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100530 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100531}
532
David Brazdilffee3d32015-07-06 11:48:53 +0100533void HGraph::ComputeTryBlockInformation() {
534 // Iterate in reverse post order to propagate try membership information from
535 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100536 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100537 if (block->IsEntryBlock() || block->IsCatchBlock()) {
538 // Catch blocks after simplification have only exceptional predecessors
539 // and hence are never in tries.
540 continue;
541 }
542
543 // Infer try membership from the first predecessor. Having simplified loops,
544 // the first predecessor can never be a back edge and therefore it must have
545 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100546 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100547 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100548 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000549 if (try_entry != nullptr &&
550 (block->GetTryCatchInformation() == nullptr ||
551 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
552 // We are either setting try block membership for the first time or it
553 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100554 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100555 }
David Brazdilffee3d32015-07-06 11:48:53 +0100556 }
557}
558
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100559void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000560// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100561 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000562 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100563 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
564 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
565 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
566 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100567 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000568 if (block->GetSuccessors().size() > 1) {
569 // Only split normal-flow edges. We cannot split exceptional edges as they
570 // are synthesized (approximate real control flow), and we do not need to
571 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000572 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
573 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
574 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100575 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000576 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000577 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
578 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000579 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000580 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100581 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000582 // SplitCriticalEdge could have invalidated the `normal_successors`
583 // ArrayRef. We must re-acquire it.
584 normal_successors = block->GetNormalSuccessors();
585 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
586 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100587 }
588 }
589 }
590 if (block->IsLoopHeader()) {
591 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000592 } else if (!block->IsEntryBlock() &&
593 block->GetFirstInstruction() != nullptr &&
594 block->GetFirstInstruction()->IsSuspendCheck()) {
595 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000596 // a loop got dismantled. Just remove the suspend check.
597 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100598 }
599 }
600}
601
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000602GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100603 // We iterate post order to ensure we visit inner loops before outer loops.
604 // `PopulateRecursive` needs this guarantee to know whether a natural loop
605 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100606 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100607 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100608 if (block->IsCatchBlock()) {
609 // TODO: Dealing with exceptional back edges could be tricky because
610 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000611 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000612 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100613 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000614 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100615 }
616 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000617 return kAnalysisSuccess;
618}
619
620void HLoopInformation::Dump(std::ostream& os) {
621 os << "header: " << header_->GetBlockId() << std::endl;
622 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
623 for (HBasicBlock* block : back_edges_) {
624 os << "back edge: " << block->GetBlockId() << std::endl;
625 }
626 for (HBasicBlock* block : header_->GetPredecessors()) {
627 os << "predecessor: " << block->GetBlockId() << std::endl;
628 }
629 for (uint32_t idx : blocks_.Indexes()) {
630 os << " in loop: " << idx << std::endl;
631 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100632}
633
David Brazdil8d5b8b22015-03-24 10:51:52 +0000634void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000635 // New constants are inserted before the SuspendCheck at the bottom of the
636 // entry block. Note that this method can be called from the graph builder and
637 // the entry block therefore may not end with SuspendCheck->Goto yet.
638 HInstruction* insert_before = nullptr;
639
640 HInstruction* gota = entry_block_->GetLastInstruction();
641 if (gota != nullptr && gota->IsGoto()) {
642 HInstruction* suspend_check = gota->GetPrevious();
643 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
644 insert_before = suspend_check;
645 } else {
646 insert_before = gota;
647 }
648 }
649
650 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000651 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000652 } else {
653 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000654 }
655}
656
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600657HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100658 // For simplicity, don't bother reviving the cached null constant if it is
659 // not null and not in a block. Otherwise, we need to clear the instruction
660 // id and/or any invariants the graph is assuming when adding new instructions.
661 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100662 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000663 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000664 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000665 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000666 if (kIsDebugBuild) {
667 ScopedObjectAccess soa(Thread::Current());
668 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
669 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000670 return cached_null_constant_;
671}
672
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100673HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100674 // For simplicity, don't bother reviving the cached current method if it is
675 // not null and not in a block. Otherwise, we need to clear the instruction
676 // id and/or any invariants the graph is assuming when adding new instructions.
677 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100678 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100679 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600680 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100681 if (entry_block_->GetFirstInstruction() == nullptr) {
682 entry_block_->AddInstruction(cached_current_method_);
683 } else {
684 entry_block_->InsertInstructionBefore(
685 cached_current_method_, entry_block_->GetFirstInstruction());
686 }
687 }
688 return cached_current_method_;
689}
690
Igor Murashkind01745e2017-04-05 16:40:31 -0700691const char* HGraph::GetMethodName() const {
692 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
693 return dex_file_.GetMethodName(method_id);
694}
695
696std::string HGraph::PrettyMethod(bool with_signature) const {
697 return dex_file_.PrettyMethod(method_idx_, with_signature);
698}
699
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100700HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000701 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100702 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000703 DCHECK(IsUint<1>(value));
704 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100705 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100706 case DataType::Type::kInt8:
707 case DataType::Type::kUint16:
708 case DataType::Type::kInt16:
709 case DataType::Type::kInt32:
710 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600711 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000712
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100713 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600714 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000715
716 default:
717 LOG(FATAL) << "Unsupported constant type";
718 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000719 }
David Brazdil46e2a392015-03-16 17:31:52 +0000720}
721
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000722void HGraph::CacheFloatConstant(HFloatConstant* constant) {
723 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
724 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
725 cached_float_constants_.Overwrite(value, constant);
726}
727
728void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
729 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
730 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
731 cached_double_constants_.Overwrite(value, constant);
732}
733
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000734void HLoopInformation::Add(HBasicBlock* block) {
735 blocks_.SetBit(block->GetBlockId());
736}
737
David Brazdil46e2a392015-03-16 17:31:52 +0000738void HLoopInformation::Remove(HBasicBlock* block) {
739 blocks_.ClearBit(block->GetBlockId());
740}
741
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100742void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
743 if (blocks_.IsBitSet(block->GetBlockId())) {
744 return;
745 }
746
747 blocks_.SetBit(block->GetBlockId());
748 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100749 if (block->IsLoopHeader()) {
750 // We're visiting loops in post-order, so inner loops must have been
751 // populated already.
752 DCHECK(block->GetLoopInformation()->IsPopulated());
753 if (block->GetLoopInformation()->IsIrreducible()) {
754 contains_irreducible_loop_ = true;
755 }
756 }
Vladimir Marko60584552015-09-03 13:35:12 +0000757 for (HBasicBlock* predecessor : block->GetPredecessors()) {
758 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100759 }
760}
761
David Brazdilc2e8af92016-04-05 17:15:19 +0100762void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
763 size_t block_id = block->GetBlockId();
764
765 // If `block` is in `finalized`, we know its membership in the loop has been
766 // decided and it does not need to be revisited.
767 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000768 return;
769 }
770
David Brazdilc2e8af92016-04-05 17:15:19 +0100771 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000772 if (block->IsLoopHeader()) {
773 // If we hit a loop header in an irreducible loop, we first check if the
774 // pre header of that loop belongs to the currently analyzed loop. If it does,
775 // then we visit the back edges.
776 // Note that we cannot use GetPreHeader, as the loop may have not been populated
777 // yet.
778 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100779 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000780 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000781 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100782 blocks_.SetBit(block_id);
783 finalized->SetBit(block_id);
784 is_finalized = true;
785
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000786 HLoopInformation* info = block->GetLoopInformation();
787 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100788 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000789 }
790 }
791 } else {
792 // Visit all predecessors. If one predecessor is part of the loop, this
793 // block is also part of this loop.
794 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100795 PopulateIrreducibleRecursive(predecessor, finalized);
796 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000797 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100798 blocks_.SetBit(block_id);
799 finalized->SetBit(block_id);
800 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000801 }
802 }
803 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100804
805 // All predecessors have been recursively visited. Mark finalized if not marked yet.
806 if (!is_finalized) {
807 finalized->SetBit(block_id);
808 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000809}
810
811void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100812 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000813 // Populate this loop: starting with the back edge, recursively add predecessors
814 // that are not already part of that loop. Set the header as part of the loop
815 // to end the recursion.
816 // This is a recursive implementation of the algorithm described in
817 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100818 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000819 blocks_.SetBit(header_->GetBlockId());
820 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100821
David Brazdil3f4a5222016-05-06 12:46:21 +0100822 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100823
824 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100825 // Allocate memory from local ScopedArenaAllocator.
826 ScopedArenaAllocator allocator(graph->GetArenaStack());
827 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +0100828 graph->GetBlocks().size(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800829 /* expandable= */ false,
David Brazdilc2e8af92016-04-05 17:15:19 +0100830 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +0100831 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +0100832 // Stop marking blocks at the loop header.
833 visited.SetBit(header_->GetBlockId());
834
David Brazdilc2e8af92016-04-05 17:15:19 +0100835 for (HBasicBlock* back_edge : GetBackEdges()) {
836 PopulateIrreducibleRecursive(back_edge, &visited);
837 }
838 } else {
839 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000840 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100841 }
David Brazdila4b8c212015-05-07 09:59:30 +0100842 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100843
Vladimir Markofd66c502016-04-18 15:37:01 +0100844 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
845 // When compiling in OSR mode, all loops in the compiled method may be entered
846 // from the interpreter. We treat this OSR entry point just like an extra entry
847 // to an irreducible loop, so we need to mark the method's loops as irreducible.
848 // This does not apply to inlined loops which do not act as OSR entry points.
849 if (suspend_check_ == nullptr) {
850 // Just building the graph in OSR mode, this loop is not inlined. We never build an
851 // inner graph in OSR mode as we can do OSR transition only from the outer method.
852 is_irreducible_loop = true;
853 } else {
854 // Look at the suspend check's environment to determine if the loop was inlined.
855 DCHECK(suspend_check_->HasEnvironment());
856 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
857 is_irreducible_loop = true;
858 }
859 }
860 }
861 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100862 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100863 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100864 graph->SetHasIrreducibleLoops(true);
865 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800866 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100867}
868
Artem Serov7f4aff62017-06-21 17:02:18 +0100869void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
870 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
871 blocks_.Union(&inner_loop->blocks_);
872 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
873 if (outer_loop != nullptr) {
874 outer_loop->PopulateInnerLoopUpwards(this);
875 }
876}
877
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100878HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000879 HBasicBlock* block = header_->GetPredecessors()[0];
880 DCHECK(irreducible_ || (block == header_->GetDominator()));
881 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100882}
883
884bool HLoopInformation::Contains(const HBasicBlock& block) const {
885 return blocks_.IsBitSet(block.GetBlockId());
886}
887
888bool HLoopInformation::IsIn(const HLoopInformation& other) const {
889 return other.blocks_.IsBitSet(header_->GetBlockId());
890}
891
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800892bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
893 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700894}
895
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100896size_t HLoopInformation::GetLifetimeEnd() const {
897 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100898 for (HBasicBlock* back_edge : GetBackEdges()) {
899 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100900 }
901 return last_position;
902}
903
David Brazdil3f4a5222016-05-06 12:46:21 +0100904bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
905 for (HBasicBlock* back_edge : GetBackEdges()) {
906 DCHECK(back_edge->GetDominator() != nullptr);
907 if (!header_->Dominates(back_edge)) {
908 return true;
909 }
910 }
911 return false;
912}
913
Anton Shaminf89381f2016-05-16 16:44:13 +0600914bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
915 for (HBasicBlock* back_edge : GetBackEdges()) {
916 if (!block->Dominates(back_edge)) {
917 return false;
918 }
919 }
920 return true;
921}
922
David Sehrc757dec2016-11-04 15:48:34 -0700923
924bool HLoopInformation::HasExitEdge() const {
925 // Determine if this loop has at least one exit edge.
926 HBlocksInLoopReversePostOrderIterator it_loop(*this);
927 for (; !it_loop.Done(); it_loop.Advance()) {
928 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
929 if (!Contains(*successor)) {
930 return true;
931 }
932 }
933 }
934 return false;
935}
936
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100937bool HBasicBlock::Dominates(HBasicBlock* other) const {
938 // Walk up the dominator tree from `other`, to find out if `this`
939 // is an ancestor.
940 HBasicBlock* current = other;
941 while (current != nullptr) {
942 if (current == this) {
943 return true;
944 }
945 current = current->GetDominator();
946 }
947 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100948}
949
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100950static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100951 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100952 for (size_t i = 0; i < inputs.size(); ++i) {
953 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100954 }
955 // Environment should be created later.
956 DCHECK(!instruction->HasEnvironment());
957}
958
Artem Serovcced8ba2017-07-19 18:18:09 +0100959void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
960 DCHECK(initial->GetBlock() == this);
961 InsertPhiAfter(replacement, initial);
962 initial->ReplaceWith(replacement);
963 RemovePhi(initial);
964}
965
Roland Levillainccc07a92014-09-16 14:48:16 +0100966void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
967 HInstruction* replacement) {
968 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400969 if (initial->IsControlFlow()) {
970 // We can only replace a control flow instruction with another control flow instruction.
971 DCHECK(replacement->IsControlFlow());
972 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100973 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400974 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100975 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100976 DCHECK(initial->GetUses().empty());
977 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400978 replacement->SetBlock(this);
979 replacement->SetId(GetGraph()->GetNextInstructionId());
980 instructions_.InsertInstructionBefore(replacement, initial);
981 UpdateInputsUsers(replacement);
982 } else {
983 InsertInstructionBefore(replacement, initial);
984 initial->ReplaceWith(replacement);
985 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100986 RemoveInstruction(initial);
987}
988
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100989static void Add(HInstructionList* instruction_list,
990 HBasicBlock* block,
991 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000992 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000993 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100994 instruction->SetBlock(block);
995 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100996 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100997 instruction_list->AddInstruction(instruction);
998}
999
1000void HBasicBlock::AddInstruction(HInstruction* instruction) {
1001 Add(&instructions_, this, instruction);
1002}
1003
1004void HBasicBlock::AddPhi(HPhi* phi) {
1005 Add(&phis_, this, phi);
1006}
1007
David Brazdilc3d743f2015-04-22 13:40:50 +01001008void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1009 DCHECK(!cursor->IsPhi());
1010 DCHECK(!instruction->IsPhi());
1011 DCHECK_EQ(instruction->GetId(), -1);
1012 DCHECK_NE(cursor->GetId(), -1);
1013 DCHECK_EQ(cursor->GetBlock(), this);
1014 DCHECK(!instruction->IsControlFlow());
1015 instruction->SetBlock(this);
1016 instruction->SetId(GetGraph()->GetNextInstructionId());
1017 UpdateInputsUsers(instruction);
1018 instructions_.InsertInstructionBefore(instruction, cursor);
1019}
1020
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001021void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1022 DCHECK(!cursor->IsPhi());
1023 DCHECK(!instruction->IsPhi());
1024 DCHECK_EQ(instruction->GetId(), -1);
1025 DCHECK_NE(cursor->GetId(), -1);
1026 DCHECK_EQ(cursor->GetBlock(), this);
1027 DCHECK(!instruction->IsControlFlow());
1028 DCHECK(!cursor->IsControlFlow());
1029 instruction->SetBlock(this);
1030 instruction->SetId(GetGraph()->GetNextInstructionId());
1031 UpdateInputsUsers(instruction);
1032 instructions_.InsertInstructionAfter(instruction, cursor);
1033}
1034
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001035void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1036 DCHECK_EQ(phi->GetId(), -1);
1037 DCHECK_NE(cursor->GetId(), -1);
1038 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001039 phi->SetBlock(this);
1040 phi->SetId(GetGraph()->GetNextInstructionId());
1041 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001042 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001043}
1044
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001045static void Remove(HInstructionList* instruction_list,
1046 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001047 HInstruction* instruction,
1048 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001049 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001050 instruction->SetBlock(nullptr);
1051 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001052 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001053 DCHECK(instruction->GetUses().empty());
1054 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001055 RemoveAsUser(instruction);
1056 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001057}
1058
David Brazdil1abb4192015-02-17 18:33:36 +00001059void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001060 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001061 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001062}
1063
David Brazdil1abb4192015-02-17 18:33:36 +00001064void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1065 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001066}
1067
David Brazdilc7508e92015-04-27 13:28:57 +01001068void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1069 if (instruction->IsPhi()) {
1070 RemovePhi(instruction->AsPhi(), ensure_safety);
1071 } else {
1072 RemoveInstruction(instruction, ensure_safety);
1073 }
1074}
1075
Vladimir Marko69d310e2017-10-09 14:12:23 +01001076void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001077 for (size_t i = 0; i < locals.size(); i++) {
1078 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001079 SetRawEnvAt(i, instruction);
1080 if (instruction != nullptr) {
1081 instruction->AddEnvUseAt(this, i);
1082 }
1083 }
1084}
1085
David Brazdiled596192015-01-23 10:39:45 +00001086void HEnvironment::CopyFrom(HEnvironment* env) {
1087 for (size_t i = 0; i < env->Size(); i++) {
1088 HInstruction* instruction = env->GetInstructionAt(i);
1089 SetRawEnvAt(i, instruction);
1090 if (instruction != nullptr) {
1091 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001092 }
David Brazdiled596192015-01-23 10:39:45 +00001093 }
1094}
1095
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001096void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1097 HBasicBlock* loop_header) {
1098 DCHECK(loop_header->IsLoopHeader());
1099 for (size_t i = 0; i < env->Size(); i++) {
1100 HInstruction* instruction = env->GetInstructionAt(i);
1101 SetRawEnvAt(i, instruction);
1102 if (instruction == nullptr) {
1103 continue;
1104 }
1105 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1106 // At the end of the loop pre-header, the corresponding value for instruction
1107 // is the first input of the phi.
1108 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001109 SetRawEnvAt(i, initial);
1110 initial->AddEnvUseAt(this, i);
1111 } else {
1112 instruction->AddEnvUseAt(this, i);
1113 }
1114 }
1115}
1116
David Brazdil1abb4192015-02-17 18:33:36 +00001117void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001118 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1119 HInstruction* user = env_use.GetInstruction();
1120 auto before_env_use_node = env_use.GetBeforeUseNode();
1121 user->env_uses_.erase_after(before_env_use_node);
1122 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001123}
1124
Artem Serovca210e32017-12-15 13:43:20 +00001125void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1126 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1127 HInstruction* orig_instr = env_use_record.GetInstruction();
1128
1129 DCHECK(orig_instr != replacement);
1130
1131 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1132 // Note: fixup_end remains valid across splice_after().
1133 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1134 : ++replacement->env_uses_.begin();
1135 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1136 env_use_record.GetInstruction()->env_uses_,
1137 before_use_node);
1138 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1139 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1140}
1141
Calin Juravle77520bc2015-01-12 18:45:46 +00001142HInstruction* HInstruction::GetNextDisregardingMoves() const {
1143 HInstruction* next = GetNext();
1144 while (next != nullptr && next->IsParallelMove()) {
1145 next = next->GetNext();
1146 }
1147 return next;
1148}
1149
1150HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1151 HInstruction* previous = GetPrevious();
1152 while (previous != nullptr && previous->IsParallelMove()) {
1153 previous = previous->GetPrevious();
1154 }
1155 return previous;
1156}
1157
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001158void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001159 if (first_instruction_ == nullptr) {
1160 DCHECK(last_instruction_ == nullptr);
1161 first_instruction_ = last_instruction_ = instruction;
1162 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001163 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001164 last_instruction_->next_ = instruction;
1165 instruction->previous_ = last_instruction_;
1166 last_instruction_ = instruction;
1167 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001168}
1169
David Brazdilc3d743f2015-04-22 13:40:50 +01001170void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1171 DCHECK(Contains(cursor));
1172 if (cursor == first_instruction_) {
1173 cursor->previous_ = instruction;
1174 instruction->next_ = cursor;
1175 first_instruction_ = instruction;
1176 } else {
1177 instruction->previous_ = cursor->previous_;
1178 instruction->next_ = cursor;
1179 cursor->previous_ = instruction;
1180 instruction->previous_->next_ = instruction;
1181 }
1182}
1183
1184void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1185 DCHECK(Contains(cursor));
1186 if (cursor == last_instruction_) {
1187 cursor->next_ = instruction;
1188 instruction->previous_ = cursor;
1189 last_instruction_ = instruction;
1190 } else {
1191 instruction->next_ = cursor->next_;
1192 instruction->previous_ = cursor;
1193 cursor->next_ = instruction;
1194 instruction->next_->previous_ = instruction;
1195 }
1196}
1197
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001198void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1199 if (instruction->previous_ != nullptr) {
1200 instruction->previous_->next_ = instruction->next_;
1201 }
1202 if (instruction->next_ != nullptr) {
1203 instruction->next_->previous_ = instruction->previous_;
1204 }
1205 if (instruction == first_instruction_) {
1206 first_instruction_ = instruction->next_;
1207 }
1208 if (instruction == last_instruction_) {
1209 last_instruction_ = instruction->previous_;
1210 }
1211}
1212
Roland Levillain6b469232014-09-25 10:10:38 +01001213bool HInstructionList::Contains(HInstruction* instruction) const {
1214 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1215 if (it.Current() == instruction) {
1216 return true;
1217 }
1218 }
1219 return false;
1220}
1221
Roland Levillainccc07a92014-09-16 14:48:16 +01001222bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1223 const HInstruction* instruction2) const {
1224 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1225 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1226 if (it.Current() == instruction1) {
1227 return true;
1228 }
1229 if (it.Current() == instruction2) {
1230 return false;
1231 }
1232 }
1233 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001234 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001235}
1236
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001237bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001238 if (other_instruction == this) {
1239 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001240 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001241 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001242 HBasicBlock* block = GetBlock();
1243 HBasicBlock* other_block = other_instruction->GetBlock();
1244 if (block != other_block) {
1245 return GetBlock()->Dominates(other_instruction->GetBlock());
1246 } else {
1247 // If both instructions are in the same block, ensure this
1248 // instruction comes before `other_instruction`.
1249 if (IsPhi()) {
1250 if (!other_instruction->IsPhi()) {
1251 // Phis appear before non phi-instructions so this instruction
1252 // dominates `other_instruction`.
1253 return true;
1254 } else {
1255 // There is no order among phis.
1256 LOG(FATAL) << "There is no dominance between phis of a same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001257 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001258 }
1259 } else {
1260 // `this` is not a phi.
1261 if (other_instruction->IsPhi()) {
1262 // Phis appear before non phi-instructions so this instruction
1263 // does not dominate `other_instruction`.
1264 return false;
1265 } else {
1266 // Check whether this instruction comes before
1267 // `other_instruction` in the instruction list.
1268 return block->GetInstructions().FoundBefore(this, other_instruction);
1269 }
1270 }
1271 }
1272}
1273
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001274void HInstruction::RemoveEnvironment() {
1275 RemoveEnvironmentUses(this);
1276 environment_ = nullptr;
1277}
1278
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001279void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001280 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001281 // Note: fixup_end remains valid across splice_after().
1282 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1283 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1284 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001285
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001286 // Note: env_fixup_end remains valid across splice_after().
1287 auto env_fixup_end =
1288 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1289 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1290 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001291
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001292 DCHECK(uses_.empty());
1293 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001294}
1295
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001296void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001297 const HUseList<HInstruction*>& uses = GetUses();
1298 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1299 HInstruction* user = it->GetUser();
1300 size_t index = it->GetIndex();
1301 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1302 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001303 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001304 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001305 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1306 // If the input flows from a block dominated by `dominator`, we can replace it.
1307 // We do not perform this for catch phis as we don't have control flow support
1308 // for their inputs.
1309 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1310 HBasicBlock* predecessor = predecessors[index];
1311 if (dominator->GetBlock()->Dominates(predecessor)) {
1312 user->ReplaceInput(replacement, index);
1313 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001314 }
1315 }
1316}
1317
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001318void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1319 const HUseList<HEnvironment*>& uses = GetEnvUses();
1320 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1321 HEnvironment* user = it->GetUser();
1322 size_t index = it->GetIndex();
1323 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1324 ++it;
1325 if (dominator->StrictlyDominates(user->GetHolder())) {
1326 user->ReplaceInput(replacement, index);
1327 }
1328 }
1329}
1330
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001331void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001332 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001333 if (input_use.GetInstruction() == replacement) {
1334 // Nothing to do.
1335 return;
1336 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001337 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001338 // Note: fixup_end remains valid across splice_after().
1339 auto fixup_end =
1340 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1341 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1342 input_use.GetInstruction()->uses_,
1343 before_use_node);
1344 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1345 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001346}
1347
Nicolas Geoffray39468442014-09-02 15:17:15 +01001348size_t HInstruction::EnvironmentSize() const {
1349 return HasEnvironment() ? environment_->Size() : 0;
1350}
1351
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001352void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001353 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001354 inputs_.push_back(HUserRecord<HInstruction*>(input));
1355 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001356}
1357
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001358void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1359 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1360 input->AddUseAt(this, index);
1361 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1362 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1363 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1364 inputs_[i].GetUseNode()->SetIndex(i);
1365 }
1366}
1367
1368void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001369 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001370 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001371 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1372 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1373 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1374 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001375 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001376}
1377
Igor Murashkind01745e2017-04-05 16:40:31 -07001378void HVariableInputSizeInstruction::RemoveAllInputs() {
1379 RemoveAsUserOfAllInputs();
1380 DCHECK(!HasNonEnvironmentUses());
1381
1382 inputs_.clear();
1383 DCHECK_EQ(0u, InputCount());
1384}
1385
Igor Murashkin6ef45672017-08-08 13:59:55 -07001386size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001387 DCHECK(instruction->GetBlock() != nullptr);
1388 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001389 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001390
Igor Murashkin6ef45672017-08-08 13:59:55 -07001391 // Return how many instructions were removed for statistic purposes.
1392 size_t remove_count = 0;
1393
Igor Murashkind01745e2017-04-05 16:40:31 -07001394 // Efficient implementation that simultaneously (in one pass):
1395 // * Scans the uses list for all constructor fences.
1396 // * Deletes that constructor fence from the uses list of `instruction`.
1397 // * Deletes `instruction` from the constructor fence's inputs.
1398 // * Deletes the constructor fence if it now has 0 inputs.
1399
1400 const HUseList<HInstruction*>& uses = instruction->GetUses();
1401 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1402 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1403 const HUseListNode<HInstruction*>& use_node = *it;
1404 HInstruction* const use_instruction = use_node.GetUser();
1405
1406 // Advance the iterator immediately once we fetch the use_node.
1407 // Warning: If the input is removed, the current iterator becomes invalid.
1408 ++it;
1409
1410 if (use_instruction->IsConstructorFence()) {
1411 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1412 size_t input_index = use_node.GetIndex();
1413
1414 // Process the candidate instruction for removal
1415 // from the graph.
1416
1417 // Constructor fence instructions are never
1418 // used by other instructions.
1419 //
1420 // If we wanted to make this more generic, it
1421 // could be a runtime if statement.
1422 DCHECK(!ctor_fence->HasUses());
1423
1424 // A constructor fence's return type is "kPrimVoid"
1425 // and therefore it can't have any environment uses.
1426 DCHECK(!ctor_fence->HasEnvironmentUses());
1427
1428 // Remove the inputs first, otherwise removing the instruction
1429 // will try to remove its uses while we are already removing uses
1430 // and this operation will fail.
1431 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1432
1433 // Removing the input will also remove the `use_node`.
1434 // (Do not look at `use_node` after this, it will be a dangling reference).
1435 ctor_fence->RemoveInputAt(input_index);
1436
1437 // Once all inputs are removed, the fence is considered dead and
1438 // is removed.
1439 if (ctor_fence->InputCount() == 0u) {
1440 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001441 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001442 }
1443 }
1444 }
1445
1446 if (kIsDebugBuild) {
1447 // Post-condition checks:
1448 // * None of the uses of `instruction` are a constructor fence.
1449 // * The `instruction` itself did not get removed from a block.
1450 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1451 CHECK(!use_node.GetUser()->IsConstructorFence());
1452 }
1453 CHECK(instruction->GetBlock() != nullptr);
1454 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001455
1456 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001457}
1458
Igor Murashkindd018df2017-08-09 10:38:31 -07001459void HConstructorFence::Merge(HConstructorFence* other) {
1460 // Do not delete yourself from the graph.
1461 DCHECK(this != other);
1462 // Don't try to merge with an instruction not associated with a block.
1463 DCHECK(other->GetBlock() != nullptr);
1464 // A constructor fence's return type is "kPrimVoid"
1465 // and therefore it cannot have any environment uses.
1466 DCHECK(!other->HasEnvironmentUses());
1467
1468 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1469 // Check if `haystack` has `needle` as any of its inputs.
1470 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1471 if (haystack->InputAt(input_count) == needle) {
1472 return true;
1473 }
1474 }
1475 return false;
1476 };
1477
1478 // Add any inputs from `other` into `this` if it wasn't already an input.
1479 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1480 HInstruction* other_input = other->InputAt(input_count);
1481 if (!has_input(this, other_input)) {
1482 AddInput(other_input);
1483 }
1484 }
1485
1486 other->GetBlock()->RemoveInstruction(other);
1487}
1488
1489HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001490 HInstruction* new_instance_inst = GetPrevious();
1491 // Check if the immediately preceding instruction is a new-instance/new-array.
1492 // Otherwise this fence is for protecting final fields.
1493 if (new_instance_inst != nullptr &&
1494 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001495 if (ignore_inputs) {
1496 // If inputs are ignored, simply check if the predecessor is
1497 // *any* HNewInstance/HNewArray.
1498 //
1499 // Inputs are normally only ignored for prepare_for_register_allocation,
1500 // at which point *any* prior HNewInstance/Array can be considered
1501 // associated.
1502 return new_instance_inst;
1503 } else {
1504 // Normal case: There must be exactly 1 input and the previous instruction
1505 // must be that input.
1506 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1507 return new_instance_inst;
1508 }
1509 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001510 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001511 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001512}
1513
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001514#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001515void H##name::Accept(HGraphVisitor* visitor) { \
1516 visitor->Visit##name(this); \
1517}
1518
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001519FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001520
1521#undef DEFINE_ACCEPT
1522
1523void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001524 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1525 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001526 if (block != nullptr) {
1527 VisitBasicBlock(block);
1528 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001529 }
1530}
1531
Roland Levillain633021e2014-10-01 14:12:25 +01001532void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001533 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1534 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001535 }
1536}
1537
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001538void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001539 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001540 it.Current()->Accept(this);
1541 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001542 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001543 it.Current()->Accept(this);
1544 }
1545}
1546
Mark Mendelle82549b2015-05-06 10:55:34 -04001547HConstant* HTypeConversion::TryStaticEvaluation() const {
1548 HGraph* graph = GetBlock()->GetGraph();
1549 if (GetInput()->IsIntConstant()) {
1550 int32_t value = GetInput()->AsIntConstant()->GetValue();
1551 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001552 case DataType::Type::kInt8:
1553 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1554 case DataType::Type::kUint8:
1555 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1556 case DataType::Type::kInt16:
1557 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1558 case DataType::Type::kUint16:
1559 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001561 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001563 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001565 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001566 default:
1567 return nullptr;
1568 }
1569 } else if (GetInput()->IsLongConstant()) {
1570 int64_t value = GetInput()->AsLongConstant()->GetValue();
1571 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001572 case DataType::Type::kInt8:
1573 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1574 case DataType::Type::kUint8:
1575 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1576 case DataType::Type::kInt16:
1577 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1578 case DataType::Type::kUint16:
1579 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001580 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001581 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001582 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001583 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001585 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001586 default:
1587 return nullptr;
1588 }
1589 } else if (GetInput()->IsFloatConstant()) {
1590 float value = GetInput()->AsFloatConstant()->GetValue();
1591 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001593 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001594 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001595 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001596 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001597 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001598 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1599 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001600 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001601 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001602 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001603 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001604 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001605 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001606 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1607 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001608 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001609 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001610 default:
1611 return nullptr;
1612 }
1613 } else if (GetInput()->IsDoubleConstant()) {
1614 double value = GetInput()->AsDoubleConstant()->GetValue();
1615 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001616 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001617 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001618 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001619 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001620 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001621 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001622 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1623 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001624 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001625 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001626 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001627 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001628 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001629 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001630 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1631 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001633 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001634 default:
1635 return nullptr;
1636 }
1637 }
1638 return nullptr;
1639}
1640
Roland Levillain9240d6a2014-10-20 16:47:04 +01001641HConstant* HUnaryOperation::TryStaticEvaluation() const {
1642 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001643 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001644 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001645 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001646 } else if (kEnableFloatingPointStaticEvaluation) {
1647 if (GetInput()->IsFloatConstant()) {
1648 return Evaluate(GetInput()->AsFloatConstant());
1649 } else if (GetInput()->IsDoubleConstant()) {
1650 return Evaluate(GetInput()->AsDoubleConstant());
1651 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001652 }
1653 return nullptr;
1654}
1655
1656HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001657 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1658 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001659 } else if (GetLeft()->IsLongConstant()) {
1660 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001661 // The binop(long, int) case is only valid for shifts and rotations.
1662 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001663 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1664 } else if (GetRight()->IsLongConstant()) {
1665 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001666 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001667 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001668 // The binop(null, null) case is only valid for equal and not-equal conditions.
1669 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001670 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001671 } else if (kEnableFloatingPointStaticEvaluation) {
1672 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1673 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1674 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1675 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1676 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001677 }
1678 return nullptr;
1679}
Dave Allison20dfc792014-06-16 20:44:29 -07001680
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001681HConstant* HBinaryOperation::GetConstantRight() const {
1682 if (GetRight()->IsConstant()) {
1683 return GetRight()->AsConstant();
1684 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1685 return GetLeft()->AsConstant();
1686 } else {
1687 return nullptr;
1688 }
1689}
1690
1691// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001692// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001693HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1694 HInstruction* most_constant_right = GetConstantRight();
1695 if (most_constant_right == nullptr) {
1696 return nullptr;
1697 } else if (most_constant_right == GetLeft()) {
1698 return GetRight();
1699 } else {
1700 return GetLeft();
1701 }
1702}
1703
Roland Levillain31dd3d62016-02-16 12:21:02 +00001704std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1705 switch (rhs) {
1706 case ComparisonBias::kNoBias:
1707 return os << "no_bias";
1708 case ComparisonBias::kGtBias:
1709 return os << "gt_bias";
1710 case ComparisonBias::kLtBias:
1711 return os << "lt_bias";
1712 default:
1713 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1714 UNREACHABLE();
1715 }
1716}
1717
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001718bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1719 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001720}
1721
Vladimir Marko372f10e2016-05-17 16:30:10 +01001722bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001723 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001724 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001725 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001726 HConstInputsRef inputs = GetInputs();
1727 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001728 if (inputs.size() != other_inputs.size()) return false;
1729 for (size_t i = 0; i != inputs.size(); ++i) {
1730 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001731 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001732
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001733 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001734 return true;
1735}
1736
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001737std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1738#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1739 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01001740 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001741 default:
1742 os << "Unknown instruction kind " << static_cast<int>(rhs);
1743 break;
1744 }
1745#undef DECLARE_CASE
1746 return os;
1747}
1748
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001749void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1750 if (do_checks) {
1751 DCHECK(!IsPhi());
1752 DCHECK(!IsControlFlow());
1753 DCHECK(CanBeMoved() ||
1754 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1755 IsShouldDeoptimizeFlag());
1756 DCHECK(!cursor->IsPhi());
1757 }
David Brazdild6c205e2016-06-07 14:20:52 +01001758
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001759 next_->previous_ = previous_;
1760 if (previous_ != nullptr) {
1761 previous_->next_ = next_;
1762 }
1763 if (block_->instructions_.first_instruction_ == this) {
1764 block_->instructions_.first_instruction_ = next_;
1765 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001766 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001767
1768 previous_ = cursor->previous_;
1769 if (previous_ != nullptr) {
1770 previous_->next_ = this;
1771 }
1772 next_ = cursor;
1773 cursor->previous_ = this;
1774 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001775
1776 if (block_->instructions_.first_instruction_ == cursor) {
1777 block_->instructions_.first_instruction_ = this;
1778 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001779}
1780
Vladimir Markofb337ea2015-11-25 15:25:10 +00001781void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1782 DCHECK(!CanThrow());
1783 DCHECK(!HasSideEffects());
1784 DCHECK(!HasEnvironmentUses());
1785 DCHECK(HasNonEnvironmentUses());
1786 DCHECK(!IsPhi()); // Makes no sense for Phi.
1787 DCHECK_EQ(InputCount(), 0u);
1788
1789 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001790 auto uses_it = GetUses().begin();
1791 auto uses_end = GetUses().end();
1792 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1793 ++uses_it;
1794 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1795 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001796 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001797 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001798 // This instruction has uses in two or more blocks. Find the common dominator.
1799 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001800 for (; uses_it != uses_end; ++uses_it) {
1801 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001802 }
1803 target_block = finder.Get();
1804 DCHECK(target_block != nullptr);
1805 }
1806 // Move to the first dominator not in a loop.
1807 while (target_block->IsInLoop()) {
1808 target_block = target_block->GetDominator();
1809 DCHECK(target_block != nullptr);
1810 }
1811
1812 // Find insertion position.
1813 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001814 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1815 if (use.GetUser()->GetBlock() == target_block &&
1816 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1817 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001818 }
1819 }
1820 if (insert_pos == nullptr) {
1821 // No user in `target_block`, insert before the control flow instruction.
1822 insert_pos = target_block->GetLastInstruction();
1823 DCHECK(insert_pos->IsControlFlow());
1824 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1825 if (insert_pos->IsIf()) {
1826 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1827 if (if_input == insert_pos->GetPrevious()) {
1828 insert_pos = if_input;
1829 }
1830 }
1831 }
1832 MoveBefore(insert_pos);
1833}
1834
David Brazdilfc6a86a2015-06-26 10:33:45 +00001835HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001836 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001837 DCHECK_EQ(cursor->GetBlock(), this);
1838
Vladimir Markoca6fff82017-10-03 14:49:14 +01001839 HBasicBlock* new_block =
1840 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001841 new_block->instructions_.first_instruction_ = cursor;
1842 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1843 instructions_.last_instruction_ = cursor->previous_;
1844 if (cursor->previous_ == nullptr) {
1845 instructions_.first_instruction_ = nullptr;
1846 } else {
1847 cursor->previous_->next_ = nullptr;
1848 cursor->previous_ = nullptr;
1849 }
1850
1851 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001852 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001853
Vladimir Marko60584552015-09-03 13:35:12 +00001854 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001855 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001856 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001857 new_block->successors_.swap(successors_);
1858 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001859 AddSuccessor(new_block);
1860
David Brazdil56e1acc2015-06-30 15:41:36 +01001861 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001862 return new_block;
1863}
1864
David Brazdild7558da2015-09-22 13:04:14 +01001865HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001866 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001867 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1868
Vladimir Markoca6fff82017-10-03 14:49:14 +01001869 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001870
1871 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001872 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1873 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001874 new_block->predecessors_.swap(predecessors_);
1875 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001876 AddPredecessor(new_block);
1877
1878 GetGraph()->AddBlock(new_block);
1879 return new_block;
1880}
1881
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001882HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1883 DCHECK_EQ(cursor->GetBlock(), this);
1884
Vladimir Markoca6fff82017-10-03 14:49:14 +01001885 HBasicBlock* new_block =
1886 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001887 new_block->instructions_.first_instruction_ = cursor;
1888 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1889 instructions_.last_instruction_ = cursor->previous_;
1890 if (cursor->previous_ == nullptr) {
1891 instructions_.first_instruction_ = nullptr;
1892 } else {
1893 cursor->previous_->next_ = nullptr;
1894 cursor->previous_ = nullptr;
1895 }
1896
1897 new_block->instructions_.SetBlockOfInstructions(new_block);
1898
1899 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001900 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1901 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001902 new_block->successors_.swap(successors_);
1903 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001904
1905 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1906 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001907 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001908 new_block->dominated_blocks_.swap(dominated_blocks_);
1909 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001910 return new_block;
1911}
1912
1913HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001914 DCHECK(!cursor->IsControlFlow());
1915 DCHECK_NE(instructions_.last_instruction_, cursor);
1916 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001917
Vladimir Markoca6fff82017-10-03 14:49:14 +01001918 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001919 new_block->instructions_.first_instruction_ = cursor->GetNext();
1920 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1921 cursor->next_->previous_ = nullptr;
1922 cursor->next_ = nullptr;
1923 instructions_.last_instruction_ = cursor;
1924
1925 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001926 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001927 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001928 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001929 new_block->successors_.swap(successors_);
1930 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001931
Vladimir Marko60584552015-09-03 13:35:12 +00001932 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001933 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001934 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001935 new_block->dominated_blocks_.swap(dominated_blocks_);
1936 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001937 return new_block;
1938}
1939
David Brazdilec16f792015-08-19 15:04:01 +01001940const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001941 if (EndsWithTryBoundary()) {
1942 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1943 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001944 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001945 return try_boundary;
1946 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001947 DCHECK(IsTryBlock());
1948 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001949 return nullptr;
1950 }
David Brazdilec16f792015-08-19 15:04:01 +01001951 } else if (IsTryBlock()) {
1952 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001953 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001954 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001955 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001956}
1957
Aart Bik75ff2c92018-04-21 01:28:11 +00001958bool HBasicBlock::HasThrowingInstructions() const {
1959 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1960 if (it.Current()->CanThrow()) {
1961 return true;
1962 }
1963 }
1964 return false;
1965}
1966
David Brazdilfc6a86a2015-06-26 10:33:45 +00001967static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1968 return block.GetPhis().IsEmpty()
1969 && !block.GetInstructions().IsEmpty()
1970 && block.GetFirstInstruction() == block.GetLastInstruction();
1971}
1972
David Brazdil46e2a392015-03-16 17:31:52 +00001973bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001974 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1975}
1976
Mads Ager16e52892017-07-14 13:11:37 +02001977bool HBasicBlock::IsSingleReturn() const {
1978 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1979}
1980
Mingyao Yang46721ef2017-10-05 14:45:17 -07001981bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1982 return (GetFirstInstruction() == GetLastInstruction()) &&
1983 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1984}
1985
David Brazdilfc6a86a2015-06-26 10:33:45 +00001986bool HBasicBlock::IsSingleTryBoundary() const {
1987 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001988}
1989
David Brazdil8d5b8b22015-03-24 10:51:52 +00001990bool HBasicBlock::EndsWithControlFlowInstruction() const {
1991 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1992}
1993
Aart Bik4dc09e72018-05-11 14:40:31 -07001994bool HBasicBlock::EndsWithReturn() const {
1995 return !GetInstructions().IsEmpty() &&
1996 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1997}
1998
David Brazdilb2bd1c52015-03-25 11:17:37 +00001999bool HBasicBlock::EndsWithIf() const {
2000 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2001}
2002
David Brazdilffee3d32015-07-06 11:48:53 +01002003bool HBasicBlock::EndsWithTryBoundary() const {
2004 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2005}
2006
David Brazdilb2bd1c52015-03-25 11:17:37 +00002007bool HBasicBlock::HasSinglePhi() const {
2008 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2009}
2010
David Brazdild26a4112015-11-10 11:07:31 +00002011ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2012 if (EndsWithTryBoundary()) {
2013 // The normal-flow successor of HTryBoundary is always stored at index zero.
2014 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2015 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2016 } else {
2017 // All successors of blocks not ending with TryBoundary are normal.
2018 return ArrayRef<HBasicBlock* const>(successors_);
2019 }
2020}
2021
2022ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2023 if (EndsWithTryBoundary()) {
2024 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2025 } else {
2026 // Blocks not ending with TryBoundary do not have exceptional successors.
2027 return ArrayRef<HBasicBlock* const>();
2028 }
2029}
2030
David Brazdilffee3d32015-07-06 11:48:53 +01002031bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002032 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2033 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2034
2035 size_t length = handlers1.size();
2036 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002037 return false;
2038 }
2039
David Brazdilb618ade2015-07-29 10:31:29 +01002040 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002041 for (size_t i = 0; i < length; ++i) {
2042 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002043 return false;
2044 }
2045 }
2046 return true;
2047}
2048
David Brazdil2d7352b2015-04-20 14:52:42 +01002049size_t HInstructionList::CountSize() const {
2050 size_t size = 0;
2051 HInstruction* current = first_instruction_;
2052 for (; current != nullptr; current = current->GetNext()) {
2053 size++;
2054 }
2055 return size;
2056}
2057
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002058void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2059 for (HInstruction* current = first_instruction_;
2060 current != nullptr;
2061 current = current->GetNext()) {
2062 current->SetBlock(block);
2063 }
2064}
2065
2066void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2067 DCHECK(Contains(cursor));
2068 if (!instruction_list.IsEmpty()) {
2069 if (cursor == last_instruction_) {
2070 last_instruction_ = instruction_list.last_instruction_;
2071 } else {
2072 cursor->next_->previous_ = instruction_list.last_instruction_;
2073 }
2074 instruction_list.last_instruction_->next_ = cursor->next_;
2075 cursor->next_ = instruction_list.first_instruction_;
2076 instruction_list.first_instruction_->previous_ = cursor;
2077 }
2078}
2079
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002080void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2081 DCHECK(Contains(cursor));
2082 if (!instruction_list.IsEmpty()) {
2083 if (cursor == first_instruction_) {
2084 first_instruction_ = instruction_list.first_instruction_;
2085 } else {
2086 cursor->previous_->next_ = instruction_list.first_instruction_;
2087 }
2088 instruction_list.last_instruction_->next_ = cursor;
2089 instruction_list.first_instruction_->previous_ = cursor->previous_;
2090 cursor->previous_ = instruction_list.last_instruction_;
2091 }
2092}
2093
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002094void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002095 if (IsEmpty()) {
2096 first_instruction_ = instruction_list.first_instruction_;
2097 last_instruction_ = instruction_list.last_instruction_;
2098 } else {
2099 AddAfter(last_instruction_, instruction_list);
2100 }
2101}
2102
David Brazdil04ff4e82015-12-10 13:54:52 +00002103// Should be called on instructions in a dead block in post order. This method
2104// assumes `insn` has been removed from all users with the exception of catch
2105// phis because of missing exceptional edges in the graph. It removes the
2106// instruction from catch phi uses, together with inputs of other catch phis in
2107// the catch block at the same index, as these must be dead too.
2108static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2109 DCHECK(!insn->HasEnvironmentUses());
2110 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002111 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2112 size_t use_index = use.GetIndex();
2113 HBasicBlock* user_block = use.GetUser()->GetBlock();
2114 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002115 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2116 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2117 }
2118 }
2119}
2120
David Brazdil2d7352b2015-04-20 14:52:42 +01002121void HBasicBlock::DisconnectAndDelete() {
2122 // Dominators must be removed after all the blocks they dominate. This way
2123 // a loop header is removed last, a requirement for correct loop information
2124 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002125 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002126
David Brazdil9eeebf62016-03-24 11:18:15 +00002127 // The following steps gradually remove the block from all its dependants in
2128 // post order (b/27683071).
2129
2130 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2131 // We need to do this before step (4) which destroys the predecessor list.
2132 HBasicBlock* loop_update_start = this;
2133 if (IsLoopHeader()) {
2134 HLoopInformation* loop_info = GetLoopInformation();
2135 // All other blocks in this loop should have been removed because the header
2136 // was their dominator.
2137 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2138 DCHECK(!loop_info->IsIrreducible());
2139 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2140 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2141 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002142 }
2143
David Brazdil9eeebf62016-03-24 11:18:15 +00002144 // (2) Disconnect the block from its successors and update their phis.
2145 for (HBasicBlock* successor : successors_) {
2146 // Delete this block from the list of predecessors.
2147 size_t this_index = successor->GetPredecessorIndexOf(this);
2148 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2149
2150 // Check that `successor` has other predecessors, otherwise `this` is the
2151 // dominator of `successor` which violates the order DCHECKed at the top.
2152 DCHECK(!successor->predecessors_.empty());
2153
2154 // Remove this block's entries in the successor's phis. Skip exceptional
2155 // successors because catch phi inputs do not correspond to predecessor
2156 // blocks but throwing instructions. The inputs of the catch phis will be
2157 // updated in step (3).
2158 if (!successor->IsCatchBlock()) {
2159 if (successor->predecessors_.size() == 1u) {
2160 // The successor has just one predecessor left. Replace phis with the only
2161 // remaining input.
2162 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2163 HPhi* phi = phi_it.Current()->AsPhi();
2164 phi->ReplaceWith(phi->InputAt(1 - this_index));
2165 successor->RemovePhi(phi);
2166 }
2167 } else {
2168 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2169 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2170 }
2171 }
2172 }
2173 }
2174 successors_.clear();
2175
2176 // (3) Remove instructions and phis. Instructions should have no remaining uses
2177 // except in catch phis. If an instruction is used by a catch phi at `index`,
2178 // remove `index`-th input of all phis in the catch block since they are
2179 // guaranteed dead. Note that we may miss dead inputs this way but the
2180 // graph will always remain consistent.
2181 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2182 HInstruction* insn = it.Current();
2183 RemoveUsesOfDeadInstruction(insn);
2184 RemoveInstruction(insn);
2185 }
2186 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2187 HPhi* insn = it.Current()->AsPhi();
2188 RemoveUsesOfDeadInstruction(insn);
2189 RemovePhi(insn);
2190 }
2191
2192 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002193 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002194 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002195 // We should not see any back edges as they would have been removed by step (3).
2196 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2197
David Brazdil2d7352b2015-04-20 14:52:42 +01002198 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002199 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2200 // This block is the only normal-flow successor of the TryBoundary which
2201 // makes `predecessor` dead. Since DCE removes blocks in post order,
2202 // exception handlers of this TryBoundary were already visited and any
2203 // remaining handlers therefore must be live. We remove `predecessor` from
2204 // their list of predecessors.
2205 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2206 while (predecessor->GetSuccessors().size() > 1) {
2207 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2208 DCHECK(handler->IsCatchBlock());
2209 predecessor->RemoveSuccessor(handler);
2210 handler->RemovePredecessor(predecessor);
2211 }
2212 }
2213
David Brazdil2d7352b2015-04-20 14:52:42 +01002214 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002215 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2216 if (num_pred_successors == 1u) {
2217 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002218 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2219 // successor. Replace those with a HGoto.
2220 DCHECK(last_instruction->IsIf() ||
2221 last_instruction->IsPackedSwitch() ||
2222 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002223 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002224 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002225 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002226 // The predecessor has no remaining successors and therefore must be dead.
2227 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002228 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002229 predecessor->RemoveInstruction(last_instruction);
2230 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002231 // There are multiple successors left. The removed block might be a successor
2232 // of a PackedSwitch which will be completely removed (perhaps replaced with
2233 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2234 // case, leave `last_instruction` as is for now.
2235 DCHECK(last_instruction->IsPackedSwitch() ||
2236 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002237 }
David Brazdil46e2a392015-03-16 17:31:52 +00002238 }
Vladimir Marko60584552015-09-03 13:35:12 +00002239 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002240
David Brazdil9eeebf62016-03-24 11:18:15 +00002241 // (5) Remove the block from all loops it is included in. Skip the inner-most
2242 // loop if this is the loop header (see definition of `loop_update_start`)
2243 // because the loop header's predecessor list has been destroyed in step (4).
2244 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2245 HLoopInformation* loop_info = it.Current();
2246 loop_info->Remove(this);
2247 if (loop_info->IsBackEdge(*this)) {
2248 // If this was the last back edge of the loop, we deliberately leave the
2249 // loop in an inconsistent state and will fail GraphChecker unless the
2250 // entire loop is removed during the pass.
2251 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002252 }
2253 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002254
David Brazdil9eeebf62016-03-24 11:18:15 +00002255 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002256 dominator_->RemoveDominatedBlock(this);
2257 SetDominator(nullptr);
2258
David Brazdil9eeebf62016-03-24 11:18:15 +00002259 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002260 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002261 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002262}
2263
Aart Bik6b69e0a2017-01-11 10:20:43 -08002264void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2265 DCHECK(EndsWithControlFlowInstruction());
2266 RemoveInstruction(GetLastInstruction());
2267 instructions_.Add(other->GetInstructions());
2268 other->instructions_.SetBlockOfInstructions(this);
2269 other->instructions_.Clear();
2270}
2271
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002272void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002273 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002274 DCHECK(ContainsElement(dominated_blocks_, other));
2275 DCHECK_EQ(GetSingleSuccessor(), other);
2276 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002277 DCHECK(other->GetPhis().IsEmpty());
2278
David Brazdil2d7352b2015-04-20 14:52:42 +01002279 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002280 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002281
David Brazdil2d7352b2015-04-20 14:52:42 +01002282 // Remove `other` from the loops it is included in.
2283 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2284 HLoopInformation* loop_info = it.Current();
2285 loop_info->Remove(other);
2286 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002287 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002288 }
2289 }
2290
2291 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002292 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002293 for (HBasicBlock* successor : other->GetSuccessors()) {
2294 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002295 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002296 successors_.swap(other->successors_);
2297 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002298
David Brazdil2d7352b2015-04-20 14:52:42 +01002299 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002300 RemoveDominatedBlock(other);
2301 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002302 dominated->SetDominator(this);
2303 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002304 dominated_blocks_.insert(
2305 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002306 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002307 other->dominator_ = nullptr;
2308
2309 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002310 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002311
2312 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002313 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002314 other->SetGraph(nullptr);
2315}
2316
2317void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2318 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002319 DCHECK(GetDominatedBlocks().empty());
2320 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002321 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002322 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002323 DCHECK(other->GetPhis().IsEmpty());
2324 DCHECK(!other->IsInLoop());
2325
2326 // Move instructions from `other` to `this`.
2327 instructions_.Add(other->GetInstructions());
2328 other->instructions_.SetBlockOfInstructions(this);
2329
2330 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002331 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002332 for (HBasicBlock* successor : other->GetSuccessors()) {
2333 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002334 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002335 successors_.swap(other->successors_);
2336 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002337
2338 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002339 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002340 dominated->SetDominator(this);
2341 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002342 dominated_blocks_.insert(
2343 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002344 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002345 other->dominator_ = nullptr;
2346 other->graph_ = nullptr;
2347}
2348
2349void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002350 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002351 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002352 predecessor->ReplaceSuccessor(this, other);
2353 }
Vladimir Marko60584552015-09-03 13:35:12 +00002354 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002355 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002356 successor->ReplacePredecessor(this, other);
2357 }
Vladimir Marko60584552015-09-03 13:35:12 +00002358 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2359 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002360 }
2361 GetDominator()->ReplaceDominatedBlock(this, other);
2362 other->SetDominator(GetDominator());
2363 dominator_ = nullptr;
2364 graph_ = nullptr;
2365}
2366
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002367void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002368 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002369 DCHECK(block->GetSuccessors().empty());
2370 DCHECK(block->GetPredecessors().empty());
2371 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002372 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002373 DCHECK(block->GetInstructions().IsEmpty());
2374 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002375
David Brazdilc7af85d2015-05-26 12:05:55 +01002376 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002377 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002378 }
2379
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002380 RemoveElement(reverse_post_order_, block);
2381 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002382 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002383}
2384
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002385void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2386 HBasicBlock* reference,
2387 bool replace_if_back_edge) {
2388 if (block->IsLoopHeader()) {
2389 // Clear the information of which blocks are contained in that loop. Since the
2390 // information is stored as a bit vector based on block ids, we have to update
2391 // it, as those block ids were specific to the callee graph and we are now adding
2392 // these blocks to the caller graph.
2393 block->GetLoopInformation()->ClearAllBlocks();
2394 }
2395
2396 // If not already in a loop, update the loop information.
2397 if (!block->IsInLoop()) {
2398 block->SetLoopInformation(reference->GetLoopInformation());
2399 }
2400
2401 // If the block is in a loop, update all its outward loops.
2402 HLoopInformation* loop_info = block->GetLoopInformation();
2403 if (loop_info != nullptr) {
2404 for (HLoopInformationOutwardIterator loop_it(*block);
2405 !loop_it.Done();
2406 loop_it.Advance()) {
2407 loop_it.Current()->Add(block);
2408 }
2409 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2410 loop_info->ReplaceBackEdge(reference, block);
2411 }
2412 }
2413
2414 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2415 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2416 ? reference->GetTryCatchInformation()
2417 : nullptr;
2418 block->SetTryCatchInformation(try_catch_info);
2419}
2420
Calin Juravle2e768302015-07-28 14:41:11 +00002421HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002422 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002423 // Update the environments in this graph to have the invoke's environment
2424 // as parent.
2425 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002426 // Skip the entry block, we do not need to update the entry's suspend check.
2427 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002428 for (HInstructionIterator instr_it(block->GetInstructions());
2429 !instr_it.Done();
2430 instr_it.Advance()) {
2431 HInstruction* current = instr_it.Current();
2432 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002433 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002434 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002435 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002436 }
2437 }
2438 }
2439 }
2440 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002441
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002442 if (HasBoundsChecks()) {
2443 outer_graph->SetHasBoundsChecks(true);
2444 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002445 if (HasLoops()) {
2446 outer_graph->SetHasLoops(true);
2447 }
2448 if (HasIrreducibleLoops()) {
2449 outer_graph->SetHasIrreducibleLoops(true);
2450 }
2451 if (HasTryCatch()) {
2452 outer_graph->SetHasTryCatch(true);
2453 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002454 if (HasSIMD()) {
2455 outer_graph->SetHasSIMD(true);
2456 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002457
Calin Juravle2e768302015-07-28 14:41:11 +00002458 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002459 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002460 // Inliner already made sure we don't inline methods that always throw.
2461 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002462 // Simple case of an entry block, a body block, and an exit block.
2463 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002464 HBasicBlock* body = GetBlocks()[1];
2465 DCHECK(GetBlocks()[0]->IsEntryBlock());
2466 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002467 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002468 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002469 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002470
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002471 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2472 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002473 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002474
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002475 // Replace the invoke with the return value of the inlined graph.
2476 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002477 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002478 } else {
2479 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002480 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002481
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002482 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002483 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002484 // Need to inline multiple blocks. We split `invoke`'s block
2485 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002486 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002487 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002488 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002489 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002490 // Note that we split before the invoke only to simplify polymorphic inlining.
2491 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002492
Vladimir Markoec7802a2015-10-01 20:57:57 +01002493 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002494 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002495 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002496 exit_block_->ReplaceWith(to);
2497
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002498 // Update the meta information surrounding blocks:
2499 // (1) the graph they are now in,
2500 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002501 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002502 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002503 // Note that we do not need to update catch phi inputs because they
2504 // correspond to the register file of the outer method which the inlinee
2505 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002506
2507 // We don't add the entry block, the exit block, and the first block, which
2508 // has been merged with `at`.
2509 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2510
2511 // We add the `to` block.
2512 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002513 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002514 + kNumberOfNewBlocksInCaller;
2515
2516 // Find the location of `at` in the outer graph's reverse post order. The new
2517 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002518 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002519 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2520
David Brazdil95177982015-10-30 12:56:58 -05002521 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2522 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002523 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002524 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002525 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002526 DCHECK(current->GetGraph() == this);
2527 current->SetGraph(outer_graph);
2528 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002529 outer_graph->reverse_post_order_[++index_of_at] = current;
Andreas Gampe3db70682018-12-26 15:12:03 -08002530 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge= */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002531 }
2532 }
2533
David Brazdil95177982015-10-30 12:56:58 -05002534 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002535 to->SetGraph(outer_graph);
2536 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002537 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002538 // Only `to` can become a back edge, as the inlined blocks
2539 // are predecessors of `to`.
Andreas Gampe3db70682018-12-26 15:12:03 -08002540 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002541
David Brazdil3f523062016-02-29 16:53:33 +00002542 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002543 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2544 // to now get the outer graph exit block as successor. Note that the inliner
2545 // currently doesn't support inlining methods with try/catch.
2546 HPhi* return_value_phi = nullptr;
2547 bool rerun_dominance = false;
2548 bool rerun_loop_analysis = false;
2549 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2550 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002551 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002552 if (last->IsThrow()) {
2553 DCHECK(!at->IsTryBlock());
2554 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2555 --pred;
2556 // We need to re-run dominance information, as the exit block now has
2557 // a new dominator.
2558 rerun_dominance = true;
2559 if (predecessor->GetLoopInformation() != nullptr) {
2560 // The exit block and blocks post dominated by the exit block do not belong
2561 // to any loop. Because we do not compute the post dominators, we need to re-run
2562 // loop analysis to get the loop information correct.
2563 rerun_loop_analysis = true;
2564 }
2565 } else {
2566 if (last->IsReturnVoid()) {
2567 DCHECK(return_value == nullptr);
2568 DCHECK(return_value_phi == nullptr);
2569 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002570 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002571 if (return_value_phi != nullptr) {
2572 return_value_phi->AddInput(last->InputAt(0));
2573 } else if (return_value == nullptr) {
2574 return_value = last->InputAt(0);
2575 } else {
2576 // There will be multiple returns.
2577 return_value_phi = new (allocator) HPhi(
2578 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2579 to->AddPhi(return_value_phi);
2580 return_value_phi->AddInput(return_value);
2581 return_value_phi->AddInput(last->InputAt(0));
2582 return_value = return_value_phi;
2583 }
David Brazdil3f523062016-02-29 16:53:33 +00002584 }
2585 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2586 predecessor->RemoveInstruction(last);
2587 }
2588 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002589 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002590 DCHECK(!outer_graph->HasIrreducibleLoops())
2591 << "Recomputing loop information in graphs with irreducible loops "
2592 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002593 outer_graph->ClearLoopInformation();
2594 outer_graph->ClearDominanceInformation();
2595 outer_graph->BuildDominatorTree();
2596 } else if (rerun_dominance) {
2597 outer_graph->ClearDominanceInformation();
2598 outer_graph->ComputeDominanceInformation();
2599 }
David Brazdil3f523062016-02-29 16:53:33 +00002600 }
David Brazdil05144f42015-04-16 15:18:00 +01002601
2602 // Walk over the entry block and:
2603 // - Move constants from the entry block to the outer_graph's entry block,
2604 // - Replace HParameterValue instructions with their real value.
2605 // - Remove suspend checks, that hold an environment.
2606 // We must do this after the other blocks have been inlined, otherwise ids of
2607 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002608 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002609 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2610 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002611 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002612 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002613 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002614 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002615 replacement = outer_graph->GetIntConstant(
2616 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002617 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002618 replacement = outer_graph->GetLongConstant(
2619 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002620 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002621 replacement = outer_graph->GetFloatConstant(
2622 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002623 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002624 replacement = outer_graph->GetDoubleConstant(
2625 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002626 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002627 if (kIsDebugBuild
2628 && invoke->IsInvokeStaticOrDirect()
2629 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2630 // Ensure we do not use the last input of `invoke`, as it
2631 // contains a clinit check which is not an actual argument.
2632 size_t last_input_index = invoke->InputCount() - 1;
2633 DCHECK(parameter_index != last_input_index);
2634 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002635 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002636 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002637 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002638 } else {
2639 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2640 entry_block_->RemoveInstruction(current);
2641 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002642 if (replacement != nullptr) {
2643 current->ReplaceWith(replacement);
2644 // If the current is the return value then we need to update the latter.
2645 if (current == return_value) {
2646 DCHECK_EQ(entry_block_, return_value->GetBlock());
2647 return_value = replacement;
2648 }
2649 }
2650 }
2651
Calin Juravle2e768302015-07-28 14:41:11 +00002652 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002653}
2654
Mingyao Yang3584bce2015-05-19 16:01:59 -07002655/*
2656 * Loop will be transformed to:
2657 * old_pre_header
2658 * |
2659 * if_block
2660 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002661 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002662 * \ /
2663 * new_pre_header
2664 * |
2665 * header
2666 */
2667void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2668 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002669 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002670
Aart Bik3fc7f352015-11-20 22:03:03 -08002671 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002672 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2673 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2674 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2675 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002676 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002677 AddBlock(true_block);
2678 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002679 AddBlock(new_pre_header);
2680
Aart Bik3fc7f352015-11-20 22:03:03 -08002681 header->ReplacePredecessor(old_pre_header, new_pre_header);
2682 old_pre_header->successors_.clear();
2683 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002684
Aart Bik3fc7f352015-11-20 22:03:03 -08002685 old_pre_header->AddSuccessor(if_block);
2686 if_block->AddSuccessor(true_block); // True successor
2687 if_block->AddSuccessor(false_block); // False successor
2688 true_block->AddSuccessor(new_pre_header);
2689 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002690
Aart Bik3fc7f352015-11-20 22:03:03 -08002691 old_pre_header->dominated_blocks_.push_back(if_block);
2692 if_block->SetDominator(old_pre_header);
2693 if_block->dominated_blocks_.push_back(true_block);
2694 true_block->SetDominator(if_block);
2695 if_block->dominated_blocks_.push_back(false_block);
2696 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002697 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002698 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002699 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002700 header->SetDominator(new_pre_header);
2701
Aart Bik3fc7f352015-11-20 22:03:03 -08002702 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002703 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002704 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002705 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002706 reverse_post_order_[index_of_header++] = true_block;
2707 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002708 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002709
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002710 // The pre_header can never be a back edge of a loop.
2711 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2712 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2713 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002714 if_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002715 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002716 true_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002717 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002718 false_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002719 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002720 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002721}
2722
Aart Bikf8f5a162017-02-06 15:35:29 -08002723HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2724 HBasicBlock* body,
2725 HBasicBlock* exit) {
2726 DCHECK(header->IsLoopHeader());
2727 HLoopInformation* loop = header->GetLoopInformation();
2728
2729 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002730 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2731 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2732 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002733 AddBlock(new_pre_header);
2734 AddBlock(new_header);
2735 AddBlock(new_body);
2736
2737 // Set up control flow.
2738 header->ReplaceSuccessor(exit, new_pre_header);
2739 new_pre_header->AddSuccessor(new_header);
2740 new_header->AddSuccessor(exit);
2741 new_header->AddSuccessor(new_body);
2742 new_body->AddSuccessor(new_header);
2743
2744 // Set up dominators.
2745 header->ReplaceDominatedBlock(exit, new_pre_header);
2746 new_pre_header->SetDominator(header);
2747 new_pre_header->dominated_blocks_.push_back(new_header);
2748 new_header->SetDominator(new_pre_header);
2749 new_header->dominated_blocks_.push_back(new_body);
2750 new_body->SetDominator(new_header);
2751 new_header->dominated_blocks_.push_back(exit);
2752 exit->SetDominator(new_header);
2753
2754 // Fix reverse post order.
2755 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2756 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2757 reverse_post_order_[++index_of_header] = new_pre_header;
2758 reverse_post_order_[++index_of_header] = new_header;
2759 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2760 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2761 reverse_post_order_[index_of_body] = new_body;
2762
Aart Bikb07d1bc2017-04-05 10:03:15 -07002763 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002764 new_pre_header->AddInstruction(new (allocator_) HGoto());
2765 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002766 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002767 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002768 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2769 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002770
2771 // Update loop information.
2772 new_header->AddBackEdge(new_body);
2773 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2774 new_header->GetLoopInformation()->Populate();
2775 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2776 HLoopInformationOutwardIterator it(*new_header);
2777 for (it.Advance(); !it.Done(); it.Advance()) {
2778 it.Current()->Add(new_pre_header);
2779 it.Current()->Add(new_header);
2780 it.Current()->Add(new_body);
2781 }
2782 return new_pre_header;
2783}
2784
David Brazdilf5552582015-12-27 13:36:12 +00002785static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002786 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002787 if (rti.IsValid()) {
2788 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2789 << " upper_bound_rti: " << upper_bound_rti
2790 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002791 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2792 << " upper_bound_rti: " << upper_bound_rti
2793 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002794 }
2795}
2796
Calin Juravle2e768302015-07-28 14:41:11 +00002797void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2798 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002799 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002800 ScopedObjectAccess soa(Thread::Current());
2801 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2802 if (IsBoundType()) {
2803 // Having the test here spares us from making the method virtual just for
2804 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002805 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002806 }
2807 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002808 reference_type_handle_ = rti.GetTypeHandle();
2809 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002810}
2811
Artem Serov4d277ba2018-06-05 20:54:42 +01002812bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
2813 const HBoundType* other_bt = other->AsBoundType();
2814 ScopedObjectAccess soa(Thread::Current());
2815 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
2816 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
2817 CanBeNull() == other_bt->CanBeNull();
2818}
2819
David Brazdilf5552582015-12-27 13:36:12 +00002820void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2821 if (kIsDebugBuild) {
2822 ScopedObjectAccess soa(Thread::Current());
2823 DCHECK(upper_bound.IsValid());
2824 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2825 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2826 }
2827 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002828 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002829}
2830
Vladimir Markoa1de9182016-02-25 11:37:38 +00002831ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002832 if (kIsDebugBuild) {
2833 ScopedObjectAccess soa(Thread::Current());
2834 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002835 if (!is_exact) {
2836 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2837 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2838 }
Calin Juravle2e768302015-07-28 14:41:11 +00002839 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002840 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002841}
2842
Calin Juravleacf735c2015-02-12 15:25:22 +00002843std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2844 ScopedObjectAccess soa(Thread::Current());
2845 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002846 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002847 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002848 << " is_exact=" << rhs.IsExact()
2849 << " ]";
2850 return os;
2851}
2852
Mark Mendellc4701932015-04-10 13:18:51 -04002853bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2854 // For now, assume that instructions in different blocks may use the
2855 // environment.
2856 // TODO: Use the control flow to decide if this is true.
2857 if (GetBlock() != other->GetBlock()) {
2858 return true;
2859 }
2860
2861 // We know that we are in the same block. Walk from 'this' to 'other',
2862 // checking to see if there is any instruction with an environment.
2863 HInstruction* current = this;
2864 for (; current != other && current != nullptr; current = current->GetNext()) {
2865 // This is a conservative check, as the instruction result may not be in
2866 // the referenced environment.
2867 if (current->HasEnvironment()) {
2868 return true;
2869 }
2870 }
2871
2872 // We should have been called with 'this' before 'other' in the block.
2873 // Just confirm this.
2874 DCHECK(current != nullptr);
2875 return false;
2876}
2877
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002878void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002879 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2880 IntrinsicSideEffects side_effects,
2881 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002882 intrinsic_ = intrinsic;
2883 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002884
Aart Bik5d75afe2015-12-14 11:57:01 -08002885 // Adjust method's side effects from intrinsic table.
2886 switch (side_effects) {
2887 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2888 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2889 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2890 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2891 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002892
2893 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2894 opt.SetDoesNotNeedDexCache();
2895 opt.SetDoesNotNeedEnvironment();
2896 } else {
2897 // If we need an environment, that means there will be a call, which can trigger GC.
2898 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2899 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002900 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002901 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002902}
2903
David Brazdil6de19382016-01-08 17:37:10 +00002904bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07002905 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00002906}
2907
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002908bool HInvoke::NeedsEnvironment() const {
2909 if (!IsIntrinsic()) {
2910 return true;
2911 }
2912 IntrinsicOptimizations opt(*this);
2913 return !opt.GetDoesNotNeedEnvironment();
2914}
2915
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002916const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2917 ArtMethod* caller = GetEnvironment()->GetMethod();
2918 ScopedObjectAccess soa(Thread::Current());
2919 // `caller` is null for a top-level graph representing a method whose declaring
2920 // class was not resolved.
2921 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2922}
2923
Vladimir Markodc151b22015-10-15 18:02:30 +01002924bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002925 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002926 return false;
2927 }
2928 if (!IsIntrinsic()) {
2929 return true;
2930 }
2931 IntrinsicOptimizations opt(*this);
2932 return !opt.GetDoesNotNeedDexCache();
2933}
2934
Vladimir Markof64242a2015-12-01 14:58:23 +00002935std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2936 switch (rhs) {
2937 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002938 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002939 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002940 return os << "Recursive";
2941 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2942 return os << "BootImageLinkTimePcRelative";
Vladimir Markob066d432018-01-03 13:14:37 +00002943 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageRelRo:
2944 return os << "BootImageRelRo";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002945 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2946 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002947 case HInvokeStaticOrDirect::MethodLoadKind::kJitDirectAddress:
2948 return os << "JitDirectAddress";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002949 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2950 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002951 default:
2952 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2953 UNREACHABLE();
2954 }
2955}
2956
Vladimir Markofbb184a2015-11-13 14:47:00 +00002957std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2958 switch (rhs) {
2959 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2960 return os << "explicit";
2961 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2962 return os << "implicit";
2963 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2964 return os << "none";
2965 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002966 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2967 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002968 }
2969}
2970
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002971bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2972 const HLoadClass* other_load_class = other->AsLoadClass();
2973 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2974 // names rather than type indexes. However, we shall also have to re-think the hash code.
2975 if (type_index_ != other_load_class->type_index_ ||
2976 GetPackedFields() != other_load_class->GetPackedFields()) {
2977 return false;
2978 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002979 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002980 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002981 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002982 case LoadKind::kJitTableAddress: {
2983 ScopedObjectAccess soa(Thread::Current());
2984 return GetClass().Get() == other_load_class->GetClass().Get();
2985 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002986 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002987 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002988 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002989 }
2990}
2991
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002992std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2993 switch (rhs) {
2994 case HLoadClass::LoadKind::kReferrersClass:
2995 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002996 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2997 return os << "BootImageLinkTimePcRelative";
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002998 case HLoadClass::LoadKind::kBootImageRelRo:
2999 return os << "BootImageRelRo";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00003000 case HLoadClass::LoadKind::kBssEntry:
3001 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003002 case HLoadClass::LoadKind::kJitBootImageAddress:
3003 return os << "JitBootImageAddress";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00003004 case HLoadClass::LoadKind::kJitTableAddress:
3005 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01003006 case HLoadClass::LoadKind::kRuntimeCall:
3007 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003008 default:
3009 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
3010 UNREACHABLE();
3011 }
3012}
3013
Vladimir Marko372f10e2016-05-17 16:30:10 +01003014bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3015 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003016 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3017 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003018 if (string_index_ != other_load_string->string_index_ ||
3019 GetPackedFields() != other_load_string->GetPackedFields()) {
3020 return false;
3021 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003022 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003023 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003024 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003025 case LoadKind::kJitTableAddress: {
3026 ScopedObjectAccess soa(Thread::Current());
3027 return GetString().Get() == other_load_string->GetString().Get();
3028 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003029 default:
3030 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003031 }
3032}
3033
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003034std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
3035 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003036 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
3037 return os << "BootImageLinkTimePcRelative";
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003038 case HLoadString::LoadKind::kBootImageRelRo:
3039 return os << "BootImageRelRo";
Vladimir Markoaad75c62016-10-03 08:46:48 +00003040 case HLoadString::LoadKind::kBssEntry:
3041 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003042 case HLoadString::LoadKind::kJitBootImageAddress:
3043 return os << "JitBootImageAddress";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08003044 case HLoadString::LoadKind::kJitTableAddress:
3045 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01003046 case HLoadString::LoadKind::kRuntimeCall:
3047 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003048 default:
3049 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
3050 UNREACHABLE();
3051 }
3052}
3053
Mark Mendellc4701932015-04-10 13:18:51 -04003054void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003055 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3056 HEnvironment* user = use.GetUser();
3057 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003058 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003059 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003060}
3061
Artem Serovcced8ba2017-07-19 18:18:09 +01003062HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3063 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3064 HBasicBlock* block = instr->GetBlock();
3065
3066 if (instr->IsPhi()) {
3067 HPhi* phi = instr->AsPhi();
3068 DCHECK(!phi->HasEnvironment());
3069 HPhi* phi_clone = clone->AsPhi();
3070 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3071 } else {
3072 block->ReplaceAndRemoveInstructionWith(instr, clone);
3073 if (instr->HasEnvironment()) {
3074 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3075 HLoopInformation* loop_info = block->GetLoopInformation();
3076 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3077 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3078 }
3079 }
3080 }
3081 return clone;
3082}
3083
Roland Levillainc9b21f82016-03-23 16:36:59 +00003084// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003085HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003086 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003087
3088 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003089 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003090 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3091 HInstruction* lhs = cond->InputAt(0);
3092 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003093 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003094 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3095 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3096 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3097 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3098 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3099 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3100 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3101 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3102 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3103 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3104 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003105 default:
3106 LOG(FATAL) << "Unexpected condition";
3107 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003108 }
3109 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3110 return replacement;
3111 } else if (cond->IsIntConstant()) {
3112 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003113 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003114 return GetIntConstant(1);
3115 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003116 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003117 return GetIntConstant(0);
3118 }
3119 } else {
3120 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3121 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3122 return replacement;
3123 }
3124}
3125
Roland Levillainc9285912015-12-18 10:38:42 +00003126std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3127 os << "["
3128 << " source=" << rhs.GetSource()
3129 << " destination=" << rhs.GetDestination()
3130 << " type=" << rhs.GetType()
3131 << " instruction=";
3132 if (rhs.GetInstruction() != nullptr) {
3133 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3134 } else {
3135 os << "null";
3136 }
3137 os << " ]";
3138 return os;
3139}
3140
Roland Levillain86503782016-02-11 19:07:30 +00003141std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3142 switch (rhs) {
3143 case TypeCheckKind::kUnresolvedCheck:
3144 return os << "unresolved_check";
3145 case TypeCheckKind::kExactCheck:
3146 return os << "exact_check";
3147 case TypeCheckKind::kClassHierarchyCheck:
3148 return os << "class_hierarchy_check";
3149 case TypeCheckKind::kAbstractClassCheck:
3150 return os << "abstract_class_check";
3151 case TypeCheckKind::kInterfaceCheck:
3152 return os << "interface_check";
3153 case TypeCheckKind::kArrayObjectCheck:
3154 return os << "array_object_check";
3155 case TypeCheckKind::kArrayCheck:
3156 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003157 case TypeCheckKind::kBitstringCheck:
3158 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003159 default:
3160 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3161 UNREACHABLE();
3162 }
3163}
3164
Andreas Gampe26de38b2016-07-27 17:53:11 -07003165std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
3166 switch (kind) {
3167 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003168 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003169 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003170 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003171 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003172 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003173 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003174 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003175 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003176 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003177
3178 default:
3179 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3180 UNREACHABLE();
3181 }
3182}
3183
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003184// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3185#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3186 static_assert( \
3187 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3188 "Instrinsics enumeration space overflow.");
3189#include "intrinsics_list.h"
3190 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3191#undef INTRINSICS_LIST
3192#undef CHECK_INTRINSICS_ENUM_VALUES
3193
3194// Function that returns whether an intrinsic needs an environment or not.
3195static inline IntrinsicNeedsEnvironmentOrCache NeedsEnvironmentOrCacheIntrinsic(Intrinsics i) {
3196 switch (i) {
3197 case Intrinsics::kNone:
3198 return kNeedsEnvironmentOrCache; // Non-sensical for intrinsic.
3199#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3200 case Intrinsics::k ## Name: \
3201 return NeedsEnvOrCache;
3202#include "intrinsics_list.h"
3203 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3204#undef INTRINSICS_LIST
3205#undef OPTIMIZING_INTRINSICS
3206 }
3207 return kNeedsEnvironmentOrCache;
3208}
3209
3210// Function that returns whether an intrinsic has side effects.
3211static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3212 switch (i) {
3213 case Intrinsics::kNone:
3214 return kAllSideEffects;
3215#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3216 case Intrinsics::k ## Name: \
3217 return SideEffects;
3218#include "intrinsics_list.h"
3219 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3220#undef INTRINSICS_LIST
3221#undef OPTIMIZING_INTRINSICS
3222 }
3223 return kAllSideEffects;
3224}
3225
3226// Function that returns whether an intrinsic can throw exceptions.
3227static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3228 switch (i) {
3229 case Intrinsics::kNone:
3230 return kCanThrow;
3231#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3232 case Intrinsics::k ## Name: \
3233 return Exceptions;
3234#include "intrinsics_list.h"
3235 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3236#undef INTRINSICS_LIST
3237#undef OPTIMIZING_INTRINSICS
3238 }
3239 return kCanThrow;
3240}
3241
3242void HInvoke::SetResolvedMethod(ArtMethod* method) {
3243 // TODO: b/65872996 The intent is that polymorphic signature methods should
3244 // be compiler intrinsics. At present, they are only interpreter intrinsics.
3245 if (method != nullptr &&
3246 method->IsIntrinsic() &&
3247 !method->IsPolymorphicSignature()) {
3248 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3249 SetIntrinsic(intrinsic,
3250 NeedsEnvironmentOrCacheIntrinsic(intrinsic),
3251 GetSideEffectsIntrinsic(intrinsic),
3252 GetExceptionsIntrinsic(intrinsic));
3253 }
3254 resolved_method_ = method;
3255}
3256
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003257} // namespace art