blob: aad06b91b6ff96f78d06a2103a477f1b3cbd2009 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010025#include "class_root.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040026#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000027#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010029#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070031#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000032
33namespace art {
34
Roland Levillain31dd3d62016-02-16 12:21:02 +000035// Enable floating-point static evaluation during constant folding
36// only if all floating-point operations and constants evaluate in the
37// range and precision of the type used (i.e., 32-bit float, 64-bit
38// double).
39static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
40
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070041void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000042 ScopedObjectAccess soa(Thread::Current());
43 // Create the inexact Object reference type and store it in the HGraph.
David Brazdilbadd8262016-02-02 16:28:56 +000044 inexact_object_rti_ = ReferenceTypeInfo::Create(
Vladimir Markob4eb1b12018-05-24 11:09:38 +010045 handles->NewHandle(GetClassRoot<mirror::Object>()),
David Brazdilbadd8262016-02-02 16:28:56 +000046 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
Vladimir Marko69d310e2017-10-09 14:12:23 +010058 // Allocate memory from local ScopedArenaAllocator.
59 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010061 ArenaBitVector visiting(
62 &allocator, blocks_.size(), /* expandable */ false, kArenaAllocGraphBuilder);
63 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010065 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
66 0u,
67 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010068 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010069 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010070 constexpr size_t kDefaultWorklistSize = 8;
71 worklist.reserve(kDefaultWorklistSize);
72 visited->SetBit(entry_block_->GetBlockId());
73 visiting.SetBit(entry_block_->GetBlockId());
74 worklist.push_back(entry_block_);
75
76 while (!worklist.empty()) {
77 HBasicBlock* current = worklist.back();
78 uint32_t current_id = current->GetBlockId();
79 if (successors_visited[current_id] == current->GetSuccessors().size()) {
80 visiting.ClearBit(current_id);
81 worklist.pop_back();
82 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010083 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
84 uint32_t successor_id = successor->GetBlockId();
85 if (visiting.IsBitSet(successor_id)) {
86 DCHECK(ContainsElement(worklist, successor));
87 successor->AddBackEdge(current);
88 } else if (!visited->IsBitSet(successor_id)) {
89 visited->SetBit(successor_id);
90 visiting.SetBit(successor_id);
91 worklist.push_back(successor);
92 }
93 }
94 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000095}
96
Artem Serov21c7e6f2017-07-27 16:04:42 +010097// Remove the environment use records of the instruction for users.
98void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010099 for (HEnvironment* environment = instruction->GetEnvironment();
100 environment != nullptr;
101 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000103 if (environment->GetInstructionAt(i) != nullptr) {
104 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000105 }
106 }
107 }
108}
109
Artem Serov21c7e6f2017-07-27 16:04:42 +0100110// Return whether the instruction has an environment and it's used by others.
111bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
112 for (HEnvironment* environment = instruction->GetEnvironment();
113 environment != nullptr;
114 environment = environment->GetParent()) {
115 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
116 HInstruction* user = environment->GetInstructionAt(i);
117 if (user != nullptr) {
118 return true;
119 }
120 }
121 }
122 return false;
123}
124
125// Reset environment records of the instruction itself.
126void ResetEnvironmentInputRecords(HInstruction* instruction) {
127 for (HEnvironment* environment = instruction->GetEnvironment();
128 environment != nullptr;
129 environment = environment->GetParent()) {
130 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
131 DCHECK(environment->GetHolder() == instruction);
132 if (environment->GetInstructionAt(i) != nullptr) {
133 environment->SetRawEnvAt(i, nullptr);
134 }
135 }
136 }
137}
138
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000139static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100140 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000141 RemoveEnvironmentUses(instruction);
142}
143
Roland Levillainfc600dc2014-12-02 17:16:31 +0000144void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100147 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000148 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100149 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000150 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
151 RemoveAsUser(it.Current());
152 }
153 }
154 }
155}
156
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100157void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100158 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100160 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000163 for (HBasicBlock* successor : block->GetSuccessors()) {
164 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000165 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100166 // Remove the block from the list of blocks, so that further analyses
167 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100168 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600169 if (block->IsExitBlock()) {
170 SetExitBlock(nullptr);
171 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000172 // Mark the block as removed. This is used by the HGraphBuilder to discard
173 // the block as a branch target.
174 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000175 }
176 }
177}
178
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000179GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100180 // Allocate memory from local ScopedArenaAllocator.
181 ScopedArenaAllocator allocator(GetArenaStack());
182
183 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
184 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 FindBackEdges(&visited);
188
David Brazdil86ea7ee2016-02-16 09:26:07 +0000189 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000190 // the initial DFS as users from other instructions, so that
191 // users can be safely removed before uses later.
192 RemoveInstructionsAsUsersFromDeadBlocks(visited);
193
David Brazdil86ea7ee2016-02-16 09:26:07 +0000194 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000196 // predecessors list of live blocks.
197 RemoveDeadBlocks(visited);
198
David Brazdil86ea7ee2016-02-16 09:26:07 +0000199 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100200 // dominators and the reverse post order.
201 SimplifyCFG();
202
David Brazdil86ea7ee2016-02-16 09:26:07 +0000203 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100204 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000205
David Brazdil86ea7ee2016-02-16 09:26:07 +0000206 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000207 // set the loop information on each block.
208 GraphAnalysisResult result = AnalyzeLoops();
209 if (result != kAnalysisSuccess) {
210 return result;
211 }
212
David Brazdil86ea7ee2016-02-16 09:26:07 +0000213 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000214 // which needs the information to build catch block phis from values of
215 // locals at throwing instructions inside try blocks.
216 ComputeTryBlockInformation();
217
218 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100219}
220
221void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100224 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100225 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226}
227
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228void HGraph::ClearLoopInformation() {
229 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100230 for (HBasicBlock* block : GetReversePostOrder()) {
231 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000232 }
233}
234
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100235void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000236 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100237 dominator_ = nullptr;
238}
239
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000240HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
241 HInstruction* instruction = GetFirstInstruction();
242 while (instruction->IsParallelMove()) {
243 instruction = instruction->GetNext();
244 }
245 return instruction;
246}
247
David Brazdil3f4a5222016-05-06 12:46:21 +0100248static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
249 DCHECK(ContainsElement(block->GetSuccessors(), successor));
250
251 HBasicBlock* old_dominator = successor->GetDominator();
252 HBasicBlock* new_dominator =
253 (old_dominator == nullptr) ? block
254 : CommonDominator::ForPair(old_dominator, block);
255
256 if (old_dominator == new_dominator) {
257 return false;
258 } else {
259 successor->SetDominator(new_dominator);
260 return true;
261 }
262}
263
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100264void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100265 DCHECK(reverse_post_order_.empty());
266 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100267 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100268
Vladimir Marko69d310e2017-10-09 14:12:23 +0100269 // Allocate memory from local ScopedArenaAllocator.
270 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100271 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100272 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100273 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100274 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
275 0u,
276 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100277 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100278 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 constexpr size_t kDefaultWorklistSize = 8;
280 worklist.reserve(kDefaultWorklistSize);
281 worklist.push_back(entry_block_);
282
283 while (!worklist.empty()) {
284 HBasicBlock* current = worklist.back();
285 uint32_t current_id = current->GetBlockId();
286 if (successors_visited[current_id] == current->GetSuccessors().size()) {
287 worklist.pop_back();
288 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100289 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100290 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100291
292 // Once all the forward edges have been visited, we know the immediate
293 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100294 if (++visits[successor->GetBlockId()] ==
295 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100296 reverse_post_order_.push_back(successor);
297 worklist.push_back(successor);
298 }
299 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000300 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301
David Brazdil3f4a5222016-05-06 12:46:21 +0100302 // Check if the graph has back edges not dominated by their respective headers.
303 // If so, we need to update the dominators of those headers and recursively of
304 // their successors. We do that with a fix-point iteration over all blocks.
305 // The algorithm is guaranteed to terminate because it loops only if the sum
306 // of all dominator chains has decreased in the current iteration.
307 bool must_run_fix_point = false;
308 for (HBasicBlock* block : blocks_) {
309 if (block != nullptr &&
310 block->IsLoopHeader() &&
311 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
312 must_run_fix_point = true;
313 break;
314 }
315 }
316 if (must_run_fix_point) {
317 bool update_occurred = true;
318 while (update_occurred) {
319 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100320 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100321 for (HBasicBlock* successor : block->GetSuccessors()) {
322 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
323 }
324 }
325 }
326 }
327
328 // Make sure that there are no remaining blocks whose dominator information
329 // needs to be updated.
330 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100331 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100332 for (HBasicBlock* successor : block->GetSuccessors()) {
333 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
334 }
335 }
336 }
337
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000338 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000339 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100340 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000341 if (!block->IsEntryBlock()) {
342 block->GetDominator()->AddDominatedBlock(block);
343 }
344 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000345}
346
David Brazdilfc6a86a2015-06-26 10:33:45 +0000347HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100348 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000349 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000350 // Use `InsertBetween` to ensure the predecessor index and successor index of
351 // `block` and `successor` are preserved.
352 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000353 return new_block;
354}
355
356void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
357 // Insert a new node between `block` and `successor` to split the
358 // critical edge.
359 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100360 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361 if (successor->IsLoopHeader()) {
362 // If we split at a back edge boundary, make the new block the back edge.
363 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000364 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100365 info->RemoveBackEdge(block);
366 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100367 }
368 }
369}
370
Artem Serovc73ee372017-07-31 15:08:40 +0100371// Reorder phi inputs to match reordering of the block's predecessors.
372static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
373 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
374 HPhi* phi = it.Current()->AsPhi();
375 HInstruction* first_instr = phi->InputAt(first);
376 HInstruction* second_instr = phi->InputAt(second);
377 phi->ReplaceInput(first_instr, second);
378 phi->ReplaceInput(second_instr, first);
379 }
380}
381
382// Make sure that the first predecessor of a loop header is the incoming block.
383void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
384 DCHECK(header->IsLoopHeader());
385 HLoopInformation* info = header->GetLoopInformation();
386 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
387 HBasicBlock* to_swap = header->GetPredecessors()[0];
388 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
389 HBasicBlock* predecessor = header->GetPredecessors()[pred];
390 if (!info->IsBackEdge(*predecessor)) {
391 header->predecessors_[pred] = to_swap;
392 header->predecessors_[0] = predecessor;
393 FixPhisAfterPredecessorsReodering(header, 0, pred);
394 break;
395 }
396 }
397 }
398}
399
Artem Serov09faaea2017-12-07 14:36:01 +0000400// Transform control flow of the loop to a single preheader format (don't touch the data flow).
401// New_preheader can be already among the header predecessors - this situation will be correctly
402// processed.
403static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
404 HLoopInformation* loop_info = header->GetLoopInformation();
405 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
406 HBasicBlock* predecessor = header->GetPredecessors()[pred];
407 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
408 predecessor->ReplaceSuccessor(header, new_preheader);
409 pred--;
410 }
411 }
412}
413
414// == Before == == After ==
415// _________ _________ _________ _________
416// | B0 | | B1 | (old preheaders) | B0 | | B1 |
417// |=========| |=========| |=========| |=========|
418// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
419// |_________| |_________| |_________| |_________|
420// \ / \ /
421// \ / ___v____________v___
422// \ / (new preheader) | B20 <- B0, B1 |
423// | | |====================|
424// | | | i20 = phi(i0, i1) |
425// | | |____________________|
426// | | |
427// /\ | | /\ /\ | /\
428// / v_______v_________v_______v \ / v___________v_____________v \
429// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
430// | |===========================| | (header) | |===========================| |
431// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
432// | |___________________________| | | |___________________________| |
433// | / \ | | / \ |
434// | ... ... | | ... ... |
435// | _________ _________ | | _________ _________ |
436// | | B2 | | B3 | | | | B2 | | B3 | |
437// | |=========| |=========| | (back edges) | |=========| |=========| |
438// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
439// | |_________| |_________| | | |_________| |_________| |
440// \ / \ / \ / \ /
441// \___/ \___/ \___/ \___/
442//
443void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
444 HLoopInformation* loop_info = header->GetLoopInformation();
445
446 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
447 AddBlock(preheader);
448 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
449
450 // If the old header has no Phis then we only need to fix the control flow.
451 if (header->GetPhis().IsEmpty()) {
452 FixControlForNewSinglePreheader(header, preheader);
453 preheader->AddSuccessor(header);
454 return;
455 }
456
457 // Find the first non-back edge block in the header's predecessors list.
458 size_t first_nonbackedge_pred_pos = 0;
459 bool found = false;
460 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
461 HBasicBlock* predecessor = header->GetPredecessors()[pred];
462 if (!loop_info->IsBackEdge(*predecessor)) {
463 first_nonbackedge_pred_pos = pred;
464 found = true;
465 break;
466 }
467 }
468
469 DCHECK(found);
470
471 // Fix the data-flow.
472 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
473 HPhi* header_phi = it.Current()->AsPhi();
474
475 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
476 header_phi->GetRegNumber(),
477 0,
478 header_phi->GetType());
479 if (header_phi->GetType() == DataType::Type::kReference) {
480 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
481 }
482 preheader->AddPhi(preheader_phi);
483
484 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
485 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
486 preheader_phi->AddInput(orig_input);
487
488 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
489 input_pos < header_phi->InputCount();
490 input_pos++) {
491 HInstruction* input = header_phi->InputAt(input_pos);
492 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
493
494 if (loop_info->Contains(*pred_block)) {
495 DCHECK(loop_info->IsBackEdge(*pred_block));
496 } else {
497 preheader_phi->AddInput(input);
498 header_phi->RemoveInputAt(input_pos);
499 input_pos--;
500 }
501 }
502 }
503
504 // Fix the control-flow.
505 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
506 preheader->InsertBetween(first_pred, header);
507
508 FixControlForNewSinglePreheader(header, preheader);
509}
510
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100511void HGraph::SimplifyLoop(HBasicBlock* header) {
512 HLoopInformation* info = header->GetLoopInformation();
513
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100514 // Make sure the loop has only one pre header. This simplifies SSA building by having
515 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000516 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
517 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000518 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000519 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000520 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100521 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100522
Artem Serovc73ee372017-07-31 15:08:40 +0100523 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100524
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100525 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000526 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
527 // Called from DeadBlockElimination. Update SuspendCheck pointer.
528 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100529 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100530}
531
David Brazdilffee3d32015-07-06 11:48:53 +0100532void HGraph::ComputeTryBlockInformation() {
533 // Iterate in reverse post order to propagate try membership information from
534 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100535 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100536 if (block->IsEntryBlock() || block->IsCatchBlock()) {
537 // Catch blocks after simplification have only exceptional predecessors
538 // and hence are never in tries.
539 continue;
540 }
541
542 // Infer try membership from the first predecessor. Having simplified loops,
543 // the first predecessor can never be a back edge and therefore it must have
544 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100545 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100546 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100547 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000548 if (try_entry != nullptr &&
549 (block->GetTryCatchInformation() == nullptr ||
550 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
551 // We are either setting try block membership for the first time or it
552 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100553 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100554 }
David Brazdilffee3d32015-07-06 11:48:53 +0100555 }
556}
557
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100558void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000559// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100560 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000561 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100562 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
563 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
564 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
565 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100566 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000567 if (block->GetSuccessors().size() > 1) {
568 // Only split normal-flow edges. We cannot split exceptional edges as they
569 // are synthesized (approximate real control flow), and we do not need to
570 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000571 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
572 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
573 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100574 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000575 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000576 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
577 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000578 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000579 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100580 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000581 // SplitCriticalEdge could have invalidated the `normal_successors`
582 // ArrayRef. We must re-acquire it.
583 normal_successors = block->GetNormalSuccessors();
584 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
585 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100586 }
587 }
588 }
589 if (block->IsLoopHeader()) {
590 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000591 } else if (!block->IsEntryBlock() &&
592 block->GetFirstInstruction() != nullptr &&
593 block->GetFirstInstruction()->IsSuspendCheck()) {
594 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000595 // a loop got dismantled. Just remove the suspend check.
596 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100597 }
598 }
599}
600
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000601GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100602 // We iterate post order to ensure we visit inner loops before outer loops.
603 // `PopulateRecursive` needs this guarantee to know whether a natural loop
604 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100605 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100606 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100607 if (block->IsCatchBlock()) {
608 // TODO: Dealing with exceptional back edges could be tricky because
609 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000610 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100612 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000613 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100614 }
615 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000616 return kAnalysisSuccess;
617}
618
619void HLoopInformation::Dump(std::ostream& os) {
620 os << "header: " << header_->GetBlockId() << std::endl;
621 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
622 for (HBasicBlock* block : back_edges_) {
623 os << "back edge: " << block->GetBlockId() << std::endl;
624 }
625 for (HBasicBlock* block : header_->GetPredecessors()) {
626 os << "predecessor: " << block->GetBlockId() << std::endl;
627 }
628 for (uint32_t idx : blocks_.Indexes()) {
629 os << " in loop: " << idx << std::endl;
630 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100631}
632
David Brazdil8d5b8b22015-03-24 10:51:52 +0000633void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000634 // New constants are inserted before the SuspendCheck at the bottom of the
635 // entry block. Note that this method can be called from the graph builder and
636 // the entry block therefore may not end with SuspendCheck->Goto yet.
637 HInstruction* insert_before = nullptr;
638
639 HInstruction* gota = entry_block_->GetLastInstruction();
640 if (gota != nullptr && gota->IsGoto()) {
641 HInstruction* suspend_check = gota->GetPrevious();
642 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
643 insert_before = suspend_check;
644 } else {
645 insert_before = gota;
646 }
647 }
648
649 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000650 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000651 } else {
652 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000653 }
654}
655
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600656HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100657 // For simplicity, don't bother reviving the cached null constant if it is
658 // not null and not in a block. Otherwise, we need to clear the instruction
659 // id and/or any invariants the graph is assuming when adding new instructions.
660 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100661 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000662 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000663 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000664 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000665 if (kIsDebugBuild) {
666 ScopedObjectAccess soa(Thread::Current());
667 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
668 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000669 return cached_null_constant_;
670}
671
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100672HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100673 // For simplicity, don't bother reviving the cached current method if it is
674 // not null and not in a block. Otherwise, we need to clear the instruction
675 // id and/or any invariants the graph is assuming when adding new instructions.
676 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100677 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100678 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600679 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100680 if (entry_block_->GetFirstInstruction() == nullptr) {
681 entry_block_->AddInstruction(cached_current_method_);
682 } else {
683 entry_block_->InsertInstructionBefore(
684 cached_current_method_, entry_block_->GetFirstInstruction());
685 }
686 }
687 return cached_current_method_;
688}
689
Igor Murashkind01745e2017-04-05 16:40:31 -0700690const char* HGraph::GetMethodName() const {
691 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
692 return dex_file_.GetMethodName(method_id);
693}
694
695std::string HGraph::PrettyMethod(bool with_signature) const {
696 return dex_file_.PrettyMethod(method_idx_, with_signature);
697}
698
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100699HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000700 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100701 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000702 DCHECK(IsUint<1>(value));
703 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100704 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100705 case DataType::Type::kInt8:
706 case DataType::Type::kUint16:
707 case DataType::Type::kInt16:
708 case DataType::Type::kInt32:
709 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600710 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000711
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100712 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600713 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000714
715 default:
716 LOG(FATAL) << "Unsupported constant type";
717 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000718 }
David Brazdil46e2a392015-03-16 17:31:52 +0000719}
720
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000721void HGraph::CacheFloatConstant(HFloatConstant* constant) {
722 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
723 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
724 cached_float_constants_.Overwrite(value, constant);
725}
726
727void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
728 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
729 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
730 cached_double_constants_.Overwrite(value, constant);
731}
732
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000733void HLoopInformation::Add(HBasicBlock* block) {
734 blocks_.SetBit(block->GetBlockId());
735}
736
David Brazdil46e2a392015-03-16 17:31:52 +0000737void HLoopInformation::Remove(HBasicBlock* block) {
738 blocks_.ClearBit(block->GetBlockId());
739}
740
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100741void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
742 if (blocks_.IsBitSet(block->GetBlockId())) {
743 return;
744 }
745
746 blocks_.SetBit(block->GetBlockId());
747 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100748 if (block->IsLoopHeader()) {
749 // We're visiting loops in post-order, so inner loops must have been
750 // populated already.
751 DCHECK(block->GetLoopInformation()->IsPopulated());
752 if (block->GetLoopInformation()->IsIrreducible()) {
753 contains_irreducible_loop_ = true;
754 }
755 }
Vladimir Marko60584552015-09-03 13:35:12 +0000756 for (HBasicBlock* predecessor : block->GetPredecessors()) {
757 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100758 }
759}
760
David Brazdilc2e8af92016-04-05 17:15:19 +0100761void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
762 size_t block_id = block->GetBlockId();
763
764 // If `block` is in `finalized`, we know its membership in the loop has been
765 // decided and it does not need to be revisited.
766 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000767 return;
768 }
769
David Brazdilc2e8af92016-04-05 17:15:19 +0100770 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000771 if (block->IsLoopHeader()) {
772 // If we hit a loop header in an irreducible loop, we first check if the
773 // pre header of that loop belongs to the currently analyzed loop. If it does,
774 // then we visit the back edges.
775 // Note that we cannot use GetPreHeader, as the loop may have not been populated
776 // yet.
777 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100778 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000779 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000780 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100781 blocks_.SetBit(block_id);
782 finalized->SetBit(block_id);
783 is_finalized = true;
784
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000785 HLoopInformation* info = block->GetLoopInformation();
786 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100787 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000788 }
789 }
790 } else {
791 // Visit all predecessors. If one predecessor is part of the loop, this
792 // block is also part of this loop.
793 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100794 PopulateIrreducibleRecursive(predecessor, finalized);
795 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000796 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100797 blocks_.SetBit(block_id);
798 finalized->SetBit(block_id);
799 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000800 }
801 }
802 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100803
804 // All predecessors have been recursively visited. Mark finalized if not marked yet.
805 if (!is_finalized) {
806 finalized->SetBit(block_id);
807 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000808}
809
810void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100811 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000812 // Populate this loop: starting with the back edge, recursively add predecessors
813 // that are not already part of that loop. Set the header as part of the loop
814 // to end the recursion.
815 // This is a recursive implementation of the algorithm described in
816 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100817 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000818 blocks_.SetBit(header_->GetBlockId());
819 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100820
David Brazdil3f4a5222016-05-06 12:46:21 +0100821 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100822
823 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100824 // Allocate memory from local ScopedArenaAllocator.
825 ScopedArenaAllocator allocator(graph->GetArenaStack());
826 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +0100827 graph->GetBlocks().size(),
828 /* expandable */ false,
829 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +0100830 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +0100831 // Stop marking blocks at the loop header.
832 visited.SetBit(header_->GetBlockId());
833
David Brazdilc2e8af92016-04-05 17:15:19 +0100834 for (HBasicBlock* back_edge : GetBackEdges()) {
835 PopulateIrreducibleRecursive(back_edge, &visited);
836 }
837 } else {
838 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000839 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100840 }
David Brazdila4b8c212015-05-07 09:59:30 +0100841 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100842
Vladimir Markofd66c502016-04-18 15:37:01 +0100843 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
844 // When compiling in OSR mode, all loops in the compiled method may be entered
845 // from the interpreter. We treat this OSR entry point just like an extra entry
846 // to an irreducible loop, so we need to mark the method's loops as irreducible.
847 // This does not apply to inlined loops which do not act as OSR entry points.
848 if (suspend_check_ == nullptr) {
849 // Just building the graph in OSR mode, this loop is not inlined. We never build an
850 // inner graph in OSR mode as we can do OSR transition only from the outer method.
851 is_irreducible_loop = true;
852 } else {
853 // Look at the suspend check's environment to determine if the loop was inlined.
854 DCHECK(suspend_check_->HasEnvironment());
855 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
856 is_irreducible_loop = true;
857 }
858 }
859 }
860 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100861 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100862 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100863 graph->SetHasIrreducibleLoops(true);
864 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800865 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100866}
867
Artem Serov7f4aff62017-06-21 17:02:18 +0100868void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
869 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
870 blocks_.Union(&inner_loop->blocks_);
871 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
872 if (outer_loop != nullptr) {
873 outer_loop->PopulateInnerLoopUpwards(this);
874 }
875}
876
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100877HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000878 HBasicBlock* block = header_->GetPredecessors()[0];
879 DCHECK(irreducible_ || (block == header_->GetDominator()));
880 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100881}
882
883bool HLoopInformation::Contains(const HBasicBlock& block) const {
884 return blocks_.IsBitSet(block.GetBlockId());
885}
886
887bool HLoopInformation::IsIn(const HLoopInformation& other) const {
888 return other.blocks_.IsBitSet(header_->GetBlockId());
889}
890
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800891bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
892 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700893}
894
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100895size_t HLoopInformation::GetLifetimeEnd() const {
896 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100897 for (HBasicBlock* back_edge : GetBackEdges()) {
898 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100899 }
900 return last_position;
901}
902
David Brazdil3f4a5222016-05-06 12:46:21 +0100903bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
904 for (HBasicBlock* back_edge : GetBackEdges()) {
905 DCHECK(back_edge->GetDominator() != nullptr);
906 if (!header_->Dominates(back_edge)) {
907 return true;
908 }
909 }
910 return false;
911}
912
Anton Shaminf89381f2016-05-16 16:44:13 +0600913bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
914 for (HBasicBlock* back_edge : GetBackEdges()) {
915 if (!block->Dominates(back_edge)) {
916 return false;
917 }
918 }
919 return true;
920}
921
David Sehrc757dec2016-11-04 15:48:34 -0700922
923bool HLoopInformation::HasExitEdge() const {
924 // Determine if this loop has at least one exit edge.
925 HBlocksInLoopReversePostOrderIterator it_loop(*this);
926 for (; !it_loop.Done(); it_loop.Advance()) {
927 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
928 if (!Contains(*successor)) {
929 return true;
930 }
931 }
932 }
933 return false;
934}
935
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100936bool HBasicBlock::Dominates(HBasicBlock* other) const {
937 // Walk up the dominator tree from `other`, to find out if `this`
938 // is an ancestor.
939 HBasicBlock* current = other;
940 while (current != nullptr) {
941 if (current == this) {
942 return true;
943 }
944 current = current->GetDominator();
945 }
946 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100947}
948
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100949static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100950 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100951 for (size_t i = 0; i < inputs.size(); ++i) {
952 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100953 }
954 // Environment should be created later.
955 DCHECK(!instruction->HasEnvironment());
956}
957
Artem Serovcced8ba2017-07-19 18:18:09 +0100958void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
959 DCHECK(initial->GetBlock() == this);
960 InsertPhiAfter(replacement, initial);
961 initial->ReplaceWith(replacement);
962 RemovePhi(initial);
963}
964
Roland Levillainccc07a92014-09-16 14:48:16 +0100965void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
966 HInstruction* replacement) {
967 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400968 if (initial->IsControlFlow()) {
969 // We can only replace a control flow instruction with another control flow instruction.
970 DCHECK(replacement->IsControlFlow());
971 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100972 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400973 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100974 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100975 DCHECK(initial->GetUses().empty());
976 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400977 replacement->SetBlock(this);
978 replacement->SetId(GetGraph()->GetNextInstructionId());
979 instructions_.InsertInstructionBefore(replacement, initial);
980 UpdateInputsUsers(replacement);
981 } else {
982 InsertInstructionBefore(replacement, initial);
983 initial->ReplaceWith(replacement);
984 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100985 RemoveInstruction(initial);
986}
987
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100988static void Add(HInstructionList* instruction_list,
989 HBasicBlock* block,
990 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000991 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000992 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100993 instruction->SetBlock(block);
994 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100995 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100996 instruction_list->AddInstruction(instruction);
997}
998
999void HBasicBlock::AddInstruction(HInstruction* instruction) {
1000 Add(&instructions_, this, instruction);
1001}
1002
1003void HBasicBlock::AddPhi(HPhi* phi) {
1004 Add(&phis_, this, phi);
1005}
1006
David Brazdilc3d743f2015-04-22 13:40:50 +01001007void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1008 DCHECK(!cursor->IsPhi());
1009 DCHECK(!instruction->IsPhi());
1010 DCHECK_EQ(instruction->GetId(), -1);
1011 DCHECK_NE(cursor->GetId(), -1);
1012 DCHECK_EQ(cursor->GetBlock(), this);
1013 DCHECK(!instruction->IsControlFlow());
1014 instruction->SetBlock(this);
1015 instruction->SetId(GetGraph()->GetNextInstructionId());
1016 UpdateInputsUsers(instruction);
1017 instructions_.InsertInstructionBefore(instruction, cursor);
1018}
1019
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001020void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1021 DCHECK(!cursor->IsPhi());
1022 DCHECK(!instruction->IsPhi());
1023 DCHECK_EQ(instruction->GetId(), -1);
1024 DCHECK_NE(cursor->GetId(), -1);
1025 DCHECK_EQ(cursor->GetBlock(), this);
1026 DCHECK(!instruction->IsControlFlow());
1027 DCHECK(!cursor->IsControlFlow());
1028 instruction->SetBlock(this);
1029 instruction->SetId(GetGraph()->GetNextInstructionId());
1030 UpdateInputsUsers(instruction);
1031 instructions_.InsertInstructionAfter(instruction, cursor);
1032}
1033
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001034void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1035 DCHECK_EQ(phi->GetId(), -1);
1036 DCHECK_NE(cursor->GetId(), -1);
1037 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001038 phi->SetBlock(this);
1039 phi->SetId(GetGraph()->GetNextInstructionId());
1040 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001041 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001042}
1043
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001044static void Remove(HInstructionList* instruction_list,
1045 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001046 HInstruction* instruction,
1047 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001048 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001049 instruction->SetBlock(nullptr);
1050 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001051 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001052 DCHECK(instruction->GetUses().empty());
1053 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001054 RemoveAsUser(instruction);
1055 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001056}
1057
David Brazdil1abb4192015-02-17 18:33:36 +00001058void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001059 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001060 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001061}
1062
David Brazdil1abb4192015-02-17 18:33:36 +00001063void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1064 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001065}
1066
David Brazdilc7508e92015-04-27 13:28:57 +01001067void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1068 if (instruction->IsPhi()) {
1069 RemovePhi(instruction->AsPhi(), ensure_safety);
1070 } else {
1071 RemoveInstruction(instruction, ensure_safety);
1072 }
1073}
1074
Vladimir Marko69d310e2017-10-09 14:12:23 +01001075void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001076 for (size_t i = 0; i < locals.size(); i++) {
1077 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001078 SetRawEnvAt(i, instruction);
1079 if (instruction != nullptr) {
1080 instruction->AddEnvUseAt(this, i);
1081 }
1082 }
1083}
1084
David Brazdiled596192015-01-23 10:39:45 +00001085void HEnvironment::CopyFrom(HEnvironment* env) {
1086 for (size_t i = 0; i < env->Size(); i++) {
1087 HInstruction* instruction = env->GetInstructionAt(i);
1088 SetRawEnvAt(i, instruction);
1089 if (instruction != nullptr) {
1090 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001091 }
David Brazdiled596192015-01-23 10:39:45 +00001092 }
1093}
1094
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001095void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1096 HBasicBlock* loop_header) {
1097 DCHECK(loop_header->IsLoopHeader());
1098 for (size_t i = 0; i < env->Size(); i++) {
1099 HInstruction* instruction = env->GetInstructionAt(i);
1100 SetRawEnvAt(i, instruction);
1101 if (instruction == nullptr) {
1102 continue;
1103 }
1104 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1105 // At the end of the loop pre-header, the corresponding value for instruction
1106 // is the first input of the phi.
1107 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001108 SetRawEnvAt(i, initial);
1109 initial->AddEnvUseAt(this, i);
1110 } else {
1111 instruction->AddEnvUseAt(this, i);
1112 }
1113 }
1114}
1115
David Brazdil1abb4192015-02-17 18:33:36 +00001116void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001117 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1118 HInstruction* user = env_use.GetInstruction();
1119 auto before_env_use_node = env_use.GetBeforeUseNode();
1120 user->env_uses_.erase_after(before_env_use_node);
1121 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122}
1123
Artem Serovca210e32017-12-15 13:43:20 +00001124void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1125 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1126 HInstruction* orig_instr = env_use_record.GetInstruction();
1127
1128 DCHECK(orig_instr != replacement);
1129
1130 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1131 // Note: fixup_end remains valid across splice_after().
1132 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1133 : ++replacement->env_uses_.begin();
1134 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1135 env_use_record.GetInstruction()->env_uses_,
1136 before_use_node);
1137 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1138 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1139}
1140
Calin Juravle77520bc2015-01-12 18:45:46 +00001141HInstruction* HInstruction::GetNextDisregardingMoves() const {
1142 HInstruction* next = GetNext();
1143 while (next != nullptr && next->IsParallelMove()) {
1144 next = next->GetNext();
1145 }
1146 return next;
1147}
1148
1149HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1150 HInstruction* previous = GetPrevious();
1151 while (previous != nullptr && previous->IsParallelMove()) {
1152 previous = previous->GetPrevious();
1153 }
1154 return previous;
1155}
1156
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001157void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001158 if (first_instruction_ == nullptr) {
1159 DCHECK(last_instruction_ == nullptr);
1160 first_instruction_ = last_instruction_ = instruction;
1161 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001162 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001163 last_instruction_->next_ = instruction;
1164 instruction->previous_ = last_instruction_;
1165 last_instruction_ = instruction;
1166 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001167}
1168
David Brazdilc3d743f2015-04-22 13:40:50 +01001169void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1170 DCHECK(Contains(cursor));
1171 if (cursor == first_instruction_) {
1172 cursor->previous_ = instruction;
1173 instruction->next_ = cursor;
1174 first_instruction_ = instruction;
1175 } else {
1176 instruction->previous_ = cursor->previous_;
1177 instruction->next_ = cursor;
1178 cursor->previous_ = instruction;
1179 instruction->previous_->next_ = instruction;
1180 }
1181}
1182
1183void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1184 DCHECK(Contains(cursor));
1185 if (cursor == last_instruction_) {
1186 cursor->next_ = instruction;
1187 instruction->previous_ = cursor;
1188 last_instruction_ = instruction;
1189 } else {
1190 instruction->next_ = cursor->next_;
1191 instruction->previous_ = cursor;
1192 cursor->next_ = instruction;
1193 instruction->next_->previous_ = instruction;
1194 }
1195}
1196
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001197void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1198 if (instruction->previous_ != nullptr) {
1199 instruction->previous_->next_ = instruction->next_;
1200 }
1201 if (instruction->next_ != nullptr) {
1202 instruction->next_->previous_ = instruction->previous_;
1203 }
1204 if (instruction == first_instruction_) {
1205 first_instruction_ = instruction->next_;
1206 }
1207 if (instruction == last_instruction_) {
1208 last_instruction_ = instruction->previous_;
1209 }
1210}
1211
Roland Levillain6b469232014-09-25 10:10:38 +01001212bool HInstructionList::Contains(HInstruction* instruction) const {
1213 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1214 if (it.Current() == instruction) {
1215 return true;
1216 }
1217 }
1218 return false;
1219}
1220
Roland Levillainccc07a92014-09-16 14:48:16 +01001221bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1222 const HInstruction* instruction2) const {
1223 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1224 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1225 if (it.Current() == instruction1) {
1226 return true;
1227 }
1228 if (it.Current() == instruction2) {
1229 return false;
1230 }
1231 }
1232 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1233 return true;
1234}
1235
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001236bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001237 if (other_instruction == this) {
1238 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001239 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001240 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001241 HBasicBlock* block = GetBlock();
1242 HBasicBlock* other_block = other_instruction->GetBlock();
1243 if (block != other_block) {
1244 return GetBlock()->Dominates(other_instruction->GetBlock());
1245 } else {
1246 // If both instructions are in the same block, ensure this
1247 // instruction comes before `other_instruction`.
1248 if (IsPhi()) {
1249 if (!other_instruction->IsPhi()) {
1250 // Phis appear before non phi-instructions so this instruction
1251 // dominates `other_instruction`.
1252 return true;
1253 } else {
1254 // There is no order among phis.
1255 LOG(FATAL) << "There is no dominance between phis of a same block.";
1256 return false;
1257 }
1258 } else {
1259 // `this` is not a phi.
1260 if (other_instruction->IsPhi()) {
1261 // Phis appear before non phi-instructions so this instruction
1262 // does not dominate `other_instruction`.
1263 return false;
1264 } else {
1265 // Check whether this instruction comes before
1266 // `other_instruction` in the instruction list.
1267 return block->GetInstructions().FoundBefore(this, other_instruction);
1268 }
1269 }
1270 }
1271}
1272
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001273void HInstruction::RemoveEnvironment() {
1274 RemoveEnvironmentUses(this);
1275 environment_ = nullptr;
1276}
1277
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001278void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001279 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001280 // Note: fixup_end remains valid across splice_after().
1281 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1282 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1283 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001284
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001285 // Note: env_fixup_end remains valid across splice_after().
1286 auto env_fixup_end =
1287 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1288 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1289 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001290
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001291 DCHECK(uses_.empty());
1292 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001293}
1294
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001295void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001296 const HUseList<HInstruction*>& uses = GetUses();
1297 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1298 HInstruction* user = it->GetUser();
1299 size_t index = it->GetIndex();
1300 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1301 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001302 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001303 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001304 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1305 // If the input flows from a block dominated by `dominator`, we can replace it.
1306 // We do not perform this for catch phis as we don't have control flow support
1307 // for their inputs.
1308 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1309 HBasicBlock* predecessor = predecessors[index];
1310 if (dominator->GetBlock()->Dominates(predecessor)) {
1311 user->ReplaceInput(replacement, index);
1312 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001313 }
1314 }
1315}
1316
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001317void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1318 const HUseList<HEnvironment*>& uses = GetEnvUses();
1319 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1320 HEnvironment* user = it->GetUser();
1321 size_t index = it->GetIndex();
1322 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1323 ++it;
1324 if (dominator->StrictlyDominates(user->GetHolder())) {
1325 user->ReplaceInput(replacement, index);
1326 }
1327 }
1328}
1329
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001330void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001331 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001332 if (input_use.GetInstruction() == replacement) {
1333 // Nothing to do.
1334 return;
1335 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001336 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001337 // Note: fixup_end remains valid across splice_after().
1338 auto fixup_end =
1339 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1340 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1341 input_use.GetInstruction()->uses_,
1342 before_use_node);
1343 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1344 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001345}
1346
Nicolas Geoffray39468442014-09-02 15:17:15 +01001347size_t HInstruction::EnvironmentSize() const {
1348 return HasEnvironment() ? environment_->Size() : 0;
1349}
1350
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001351void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001352 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001353 inputs_.push_back(HUserRecord<HInstruction*>(input));
1354 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001355}
1356
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001357void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1358 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1359 input->AddUseAt(this, index);
1360 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1361 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1362 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1363 inputs_[i].GetUseNode()->SetIndex(i);
1364 }
1365}
1366
1367void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001368 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001369 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001370 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1371 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1372 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1373 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001374 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001375}
1376
Igor Murashkind01745e2017-04-05 16:40:31 -07001377void HVariableInputSizeInstruction::RemoveAllInputs() {
1378 RemoveAsUserOfAllInputs();
1379 DCHECK(!HasNonEnvironmentUses());
1380
1381 inputs_.clear();
1382 DCHECK_EQ(0u, InputCount());
1383}
1384
Igor Murashkin6ef45672017-08-08 13:59:55 -07001385size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001386 DCHECK(instruction->GetBlock() != nullptr);
1387 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001388 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001389
Igor Murashkin6ef45672017-08-08 13:59:55 -07001390 // Return how many instructions were removed for statistic purposes.
1391 size_t remove_count = 0;
1392
Igor Murashkind01745e2017-04-05 16:40:31 -07001393 // Efficient implementation that simultaneously (in one pass):
1394 // * Scans the uses list for all constructor fences.
1395 // * Deletes that constructor fence from the uses list of `instruction`.
1396 // * Deletes `instruction` from the constructor fence's inputs.
1397 // * Deletes the constructor fence if it now has 0 inputs.
1398
1399 const HUseList<HInstruction*>& uses = instruction->GetUses();
1400 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1401 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1402 const HUseListNode<HInstruction*>& use_node = *it;
1403 HInstruction* const use_instruction = use_node.GetUser();
1404
1405 // Advance the iterator immediately once we fetch the use_node.
1406 // Warning: If the input is removed, the current iterator becomes invalid.
1407 ++it;
1408
1409 if (use_instruction->IsConstructorFence()) {
1410 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1411 size_t input_index = use_node.GetIndex();
1412
1413 // Process the candidate instruction for removal
1414 // from the graph.
1415
1416 // Constructor fence instructions are never
1417 // used by other instructions.
1418 //
1419 // If we wanted to make this more generic, it
1420 // could be a runtime if statement.
1421 DCHECK(!ctor_fence->HasUses());
1422
1423 // A constructor fence's return type is "kPrimVoid"
1424 // and therefore it can't have any environment uses.
1425 DCHECK(!ctor_fence->HasEnvironmentUses());
1426
1427 // Remove the inputs first, otherwise removing the instruction
1428 // will try to remove its uses while we are already removing uses
1429 // and this operation will fail.
1430 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1431
1432 // Removing the input will also remove the `use_node`.
1433 // (Do not look at `use_node` after this, it will be a dangling reference).
1434 ctor_fence->RemoveInputAt(input_index);
1435
1436 // Once all inputs are removed, the fence is considered dead and
1437 // is removed.
1438 if (ctor_fence->InputCount() == 0u) {
1439 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001440 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001441 }
1442 }
1443 }
1444
1445 if (kIsDebugBuild) {
1446 // Post-condition checks:
1447 // * None of the uses of `instruction` are a constructor fence.
1448 // * The `instruction` itself did not get removed from a block.
1449 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1450 CHECK(!use_node.GetUser()->IsConstructorFence());
1451 }
1452 CHECK(instruction->GetBlock() != nullptr);
1453 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001454
1455 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001456}
1457
Igor Murashkindd018df2017-08-09 10:38:31 -07001458void HConstructorFence::Merge(HConstructorFence* other) {
1459 // Do not delete yourself from the graph.
1460 DCHECK(this != other);
1461 // Don't try to merge with an instruction not associated with a block.
1462 DCHECK(other->GetBlock() != nullptr);
1463 // A constructor fence's return type is "kPrimVoid"
1464 // and therefore it cannot have any environment uses.
1465 DCHECK(!other->HasEnvironmentUses());
1466
1467 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1468 // Check if `haystack` has `needle` as any of its inputs.
1469 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1470 if (haystack->InputAt(input_count) == needle) {
1471 return true;
1472 }
1473 }
1474 return false;
1475 };
1476
1477 // Add any inputs from `other` into `this` if it wasn't already an input.
1478 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1479 HInstruction* other_input = other->InputAt(input_count);
1480 if (!has_input(this, other_input)) {
1481 AddInput(other_input);
1482 }
1483 }
1484
1485 other->GetBlock()->RemoveInstruction(other);
1486}
1487
1488HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001489 HInstruction* new_instance_inst = GetPrevious();
1490 // Check if the immediately preceding instruction is a new-instance/new-array.
1491 // Otherwise this fence is for protecting final fields.
1492 if (new_instance_inst != nullptr &&
1493 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001494 if (ignore_inputs) {
1495 // If inputs are ignored, simply check if the predecessor is
1496 // *any* HNewInstance/HNewArray.
1497 //
1498 // Inputs are normally only ignored for prepare_for_register_allocation,
1499 // at which point *any* prior HNewInstance/Array can be considered
1500 // associated.
1501 return new_instance_inst;
1502 } else {
1503 // Normal case: There must be exactly 1 input and the previous instruction
1504 // must be that input.
1505 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1506 return new_instance_inst;
1507 }
1508 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001509 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001510 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001511}
1512
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001513#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001514void H##name::Accept(HGraphVisitor* visitor) { \
1515 visitor->Visit##name(this); \
1516}
1517
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001518FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001519
1520#undef DEFINE_ACCEPT
1521
1522void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001523 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1524 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001525 if (block != nullptr) {
1526 VisitBasicBlock(block);
1527 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001528 }
1529}
1530
Roland Levillain633021e2014-10-01 14:12:25 +01001531void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001532 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1533 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001534 }
1535}
1536
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001537void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001538 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001539 it.Current()->Accept(this);
1540 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001541 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001542 it.Current()->Accept(this);
1543 }
1544}
1545
Mark Mendelle82549b2015-05-06 10:55:34 -04001546HConstant* HTypeConversion::TryStaticEvaluation() const {
1547 HGraph* graph = GetBlock()->GetGraph();
1548 if (GetInput()->IsIntConstant()) {
1549 int32_t value = GetInput()->AsIntConstant()->GetValue();
1550 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001551 case DataType::Type::kInt8:
1552 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1553 case DataType::Type::kUint8:
1554 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1555 case DataType::Type::kInt16:
1556 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1557 case DataType::Type::kUint16:
1558 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001560 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001562 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001564 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001565 default:
1566 return nullptr;
1567 }
1568 } else if (GetInput()->IsLongConstant()) {
1569 int64_t value = GetInput()->AsLongConstant()->GetValue();
1570 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001571 case DataType::Type::kInt8:
1572 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1573 case DataType::Type::kUint8:
1574 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1575 case DataType::Type::kInt16:
1576 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1577 case DataType::Type::kUint16:
1578 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001580 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001582 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001583 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001584 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001585 default:
1586 return nullptr;
1587 }
1588 } else if (GetInput()->IsFloatConstant()) {
1589 float value = GetInput()->AsFloatConstant()->GetValue();
1590 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001592 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001593 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001594 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001595 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001596 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001597 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1598 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001600 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001601 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001602 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001603 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001604 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001605 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1606 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001607 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001608 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001609 default:
1610 return nullptr;
1611 }
1612 } else if (GetInput()->IsDoubleConstant()) {
1613 double value = GetInput()->AsDoubleConstant()->GetValue();
1614 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001615 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001616 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001617 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001618 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001619 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001620 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001621 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1622 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001623 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001624 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001625 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001626 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001627 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001628 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001629 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1630 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001632 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001633 default:
1634 return nullptr;
1635 }
1636 }
1637 return nullptr;
1638}
1639
Roland Levillain9240d6a2014-10-20 16:47:04 +01001640HConstant* HUnaryOperation::TryStaticEvaluation() const {
1641 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001642 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001643 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001644 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001645 } else if (kEnableFloatingPointStaticEvaluation) {
1646 if (GetInput()->IsFloatConstant()) {
1647 return Evaluate(GetInput()->AsFloatConstant());
1648 } else if (GetInput()->IsDoubleConstant()) {
1649 return Evaluate(GetInput()->AsDoubleConstant());
1650 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001651 }
1652 return nullptr;
1653}
1654
1655HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001656 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1657 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001658 } else if (GetLeft()->IsLongConstant()) {
1659 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001660 // The binop(long, int) case is only valid for shifts and rotations.
1661 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001662 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1663 } else if (GetRight()->IsLongConstant()) {
1664 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001665 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001666 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001667 // The binop(null, null) case is only valid for equal and not-equal conditions.
1668 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001669 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001670 } else if (kEnableFloatingPointStaticEvaluation) {
1671 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1672 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1673 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1674 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1675 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001676 }
1677 return nullptr;
1678}
Dave Allison20dfc792014-06-16 20:44:29 -07001679
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001680HConstant* HBinaryOperation::GetConstantRight() const {
1681 if (GetRight()->IsConstant()) {
1682 return GetRight()->AsConstant();
1683 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1684 return GetLeft()->AsConstant();
1685 } else {
1686 return nullptr;
1687 }
1688}
1689
1690// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001691// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001692HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1693 HInstruction* most_constant_right = GetConstantRight();
1694 if (most_constant_right == nullptr) {
1695 return nullptr;
1696 } else if (most_constant_right == GetLeft()) {
1697 return GetRight();
1698 } else {
1699 return GetLeft();
1700 }
1701}
1702
Roland Levillain31dd3d62016-02-16 12:21:02 +00001703std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1704 switch (rhs) {
1705 case ComparisonBias::kNoBias:
1706 return os << "no_bias";
1707 case ComparisonBias::kGtBias:
1708 return os << "gt_bias";
1709 case ComparisonBias::kLtBias:
1710 return os << "lt_bias";
1711 default:
1712 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1713 UNREACHABLE();
1714 }
1715}
1716
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001717bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1718 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001719}
1720
Vladimir Marko372f10e2016-05-17 16:30:10 +01001721bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001722 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001723 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001724 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001725 HConstInputsRef inputs = GetInputs();
1726 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001727 if (inputs.size() != other_inputs.size()) return false;
1728 for (size_t i = 0; i != inputs.size(); ++i) {
1729 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001730 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001731
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001732 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001733 return true;
1734}
1735
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001736std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1737#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1738 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01001739 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001740 default:
1741 os << "Unknown instruction kind " << static_cast<int>(rhs);
1742 break;
1743 }
1744#undef DECLARE_CASE
1745 return os;
1746}
1747
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001748void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1749 if (do_checks) {
1750 DCHECK(!IsPhi());
1751 DCHECK(!IsControlFlow());
1752 DCHECK(CanBeMoved() ||
1753 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1754 IsShouldDeoptimizeFlag());
1755 DCHECK(!cursor->IsPhi());
1756 }
David Brazdild6c205e2016-06-07 14:20:52 +01001757
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001758 next_->previous_ = previous_;
1759 if (previous_ != nullptr) {
1760 previous_->next_ = next_;
1761 }
1762 if (block_->instructions_.first_instruction_ == this) {
1763 block_->instructions_.first_instruction_ = next_;
1764 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001765 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001766
1767 previous_ = cursor->previous_;
1768 if (previous_ != nullptr) {
1769 previous_->next_ = this;
1770 }
1771 next_ = cursor;
1772 cursor->previous_ = this;
1773 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001774
1775 if (block_->instructions_.first_instruction_ == cursor) {
1776 block_->instructions_.first_instruction_ = this;
1777 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001778}
1779
Vladimir Markofb337ea2015-11-25 15:25:10 +00001780void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1781 DCHECK(!CanThrow());
1782 DCHECK(!HasSideEffects());
1783 DCHECK(!HasEnvironmentUses());
1784 DCHECK(HasNonEnvironmentUses());
1785 DCHECK(!IsPhi()); // Makes no sense for Phi.
1786 DCHECK_EQ(InputCount(), 0u);
1787
1788 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001789 auto uses_it = GetUses().begin();
1790 auto uses_end = GetUses().end();
1791 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1792 ++uses_it;
1793 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1794 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001795 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001796 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001797 // This instruction has uses in two or more blocks. Find the common dominator.
1798 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001799 for (; uses_it != uses_end; ++uses_it) {
1800 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001801 }
1802 target_block = finder.Get();
1803 DCHECK(target_block != nullptr);
1804 }
1805 // Move to the first dominator not in a loop.
1806 while (target_block->IsInLoop()) {
1807 target_block = target_block->GetDominator();
1808 DCHECK(target_block != nullptr);
1809 }
1810
1811 // Find insertion position.
1812 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001813 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1814 if (use.GetUser()->GetBlock() == target_block &&
1815 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1816 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001817 }
1818 }
1819 if (insert_pos == nullptr) {
1820 // No user in `target_block`, insert before the control flow instruction.
1821 insert_pos = target_block->GetLastInstruction();
1822 DCHECK(insert_pos->IsControlFlow());
1823 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1824 if (insert_pos->IsIf()) {
1825 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1826 if (if_input == insert_pos->GetPrevious()) {
1827 insert_pos = if_input;
1828 }
1829 }
1830 }
1831 MoveBefore(insert_pos);
1832}
1833
David Brazdilfc6a86a2015-06-26 10:33:45 +00001834HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001835 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001836 DCHECK_EQ(cursor->GetBlock(), this);
1837
Vladimir Markoca6fff82017-10-03 14:49:14 +01001838 HBasicBlock* new_block =
1839 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001840 new_block->instructions_.first_instruction_ = cursor;
1841 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1842 instructions_.last_instruction_ = cursor->previous_;
1843 if (cursor->previous_ == nullptr) {
1844 instructions_.first_instruction_ = nullptr;
1845 } else {
1846 cursor->previous_->next_ = nullptr;
1847 cursor->previous_ = nullptr;
1848 }
1849
1850 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001851 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001852
Vladimir Marko60584552015-09-03 13:35:12 +00001853 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001854 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001855 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001856 new_block->successors_.swap(successors_);
1857 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001858 AddSuccessor(new_block);
1859
David Brazdil56e1acc2015-06-30 15:41:36 +01001860 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001861 return new_block;
1862}
1863
David Brazdild7558da2015-09-22 13:04:14 +01001864HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001865 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001866 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1867
Vladimir Markoca6fff82017-10-03 14:49:14 +01001868 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001869
1870 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001871 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1872 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001873 new_block->predecessors_.swap(predecessors_);
1874 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001875 AddPredecessor(new_block);
1876
1877 GetGraph()->AddBlock(new_block);
1878 return new_block;
1879}
1880
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001881HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1882 DCHECK_EQ(cursor->GetBlock(), this);
1883
Vladimir Markoca6fff82017-10-03 14:49:14 +01001884 HBasicBlock* new_block =
1885 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001886 new_block->instructions_.first_instruction_ = cursor;
1887 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1888 instructions_.last_instruction_ = cursor->previous_;
1889 if (cursor->previous_ == nullptr) {
1890 instructions_.first_instruction_ = nullptr;
1891 } else {
1892 cursor->previous_->next_ = nullptr;
1893 cursor->previous_ = nullptr;
1894 }
1895
1896 new_block->instructions_.SetBlockOfInstructions(new_block);
1897
1898 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001899 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1900 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001901 new_block->successors_.swap(successors_);
1902 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001903
1904 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1905 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001906 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001907 new_block->dominated_blocks_.swap(dominated_blocks_);
1908 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001909 return new_block;
1910}
1911
1912HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001913 DCHECK(!cursor->IsControlFlow());
1914 DCHECK_NE(instructions_.last_instruction_, cursor);
1915 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001916
Vladimir Markoca6fff82017-10-03 14:49:14 +01001917 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 new_block->instructions_.first_instruction_ = cursor->GetNext();
1919 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1920 cursor->next_->previous_ = nullptr;
1921 cursor->next_ = nullptr;
1922 instructions_.last_instruction_ = cursor;
1923
1924 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001925 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001926 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001927 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001928 new_block->successors_.swap(successors_);
1929 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930
Vladimir Marko60584552015-09-03 13:35:12 +00001931 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001932 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001933 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001934 new_block->dominated_blocks_.swap(dominated_blocks_);
1935 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001936 return new_block;
1937}
1938
David Brazdilec16f792015-08-19 15:04:01 +01001939const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001940 if (EndsWithTryBoundary()) {
1941 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1942 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001943 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001944 return try_boundary;
1945 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001946 DCHECK(IsTryBlock());
1947 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001948 return nullptr;
1949 }
David Brazdilec16f792015-08-19 15:04:01 +01001950 } else if (IsTryBlock()) {
1951 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001952 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001953 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001954 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001955}
1956
Aart Bik75ff2c92018-04-21 01:28:11 +00001957bool HBasicBlock::HasThrowingInstructions() const {
1958 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1959 if (it.Current()->CanThrow()) {
1960 return true;
1961 }
1962 }
1963 return false;
1964}
1965
David Brazdilfc6a86a2015-06-26 10:33:45 +00001966static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1967 return block.GetPhis().IsEmpty()
1968 && !block.GetInstructions().IsEmpty()
1969 && block.GetFirstInstruction() == block.GetLastInstruction();
1970}
1971
David Brazdil46e2a392015-03-16 17:31:52 +00001972bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001973 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1974}
1975
Mads Ager16e52892017-07-14 13:11:37 +02001976bool HBasicBlock::IsSingleReturn() const {
1977 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1978}
1979
Mingyao Yang46721ef2017-10-05 14:45:17 -07001980bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1981 return (GetFirstInstruction() == GetLastInstruction()) &&
1982 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1983}
1984
David Brazdilfc6a86a2015-06-26 10:33:45 +00001985bool HBasicBlock::IsSingleTryBoundary() const {
1986 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001987}
1988
David Brazdil8d5b8b22015-03-24 10:51:52 +00001989bool HBasicBlock::EndsWithControlFlowInstruction() const {
1990 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1991}
1992
Aart Bik4dc09e72018-05-11 14:40:31 -07001993bool HBasicBlock::EndsWithReturn() const {
1994 return !GetInstructions().IsEmpty() &&
1995 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1996}
1997
David Brazdilb2bd1c52015-03-25 11:17:37 +00001998bool HBasicBlock::EndsWithIf() const {
1999 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2000}
2001
David Brazdilffee3d32015-07-06 11:48:53 +01002002bool HBasicBlock::EndsWithTryBoundary() const {
2003 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2004}
2005
David Brazdilb2bd1c52015-03-25 11:17:37 +00002006bool HBasicBlock::HasSinglePhi() const {
2007 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2008}
2009
David Brazdild26a4112015-11-10 11:07:31 +00002010ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2011 if (EndsWithTryBoundary()) {
2012 // The normal-flow successor of HTryBoundary is always stored at index zero.
2013 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2014 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2015 } else {
2016 // All successors of blocks not ending with TryBoundary are normal.
2017 return ArrayRef<HBasicBlock* const>(successors_);
2018 }
2019}
2020
2021ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2022 if (EndsWithTryBoundary()) {
2023 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2024 } else {
2025 // Blocks not ending with TryBoundary do not have exceptional successors.
2026 return ArrayRef<HBasicBlock* const>();
2027 }
2028}
2029
David Brazdilffee3d32015-07-06 11:48:53 +01002030bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002031 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2032 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2033
2034 size_t length = handlers1.size();
2035 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002036 return false;
2037 }
2038
David Brazdilb618ade2015-07-29 10:31:29 +01002039 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002040 for (size_t i = 0; i < length; ++i) {
2041 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002042 return false;
2043 }
2044 }
2045 return true;
2046}
2047
David Brazdil2d7352b2015-04-20 14:52:42 +01002048size_t HInstructionList::CountSize() const {
2049 size_t size = 0;
2050 HInstruction* current = first_instruction_;
2051 for (; current != nullptr; current = current->GetNext()) {
2052 size++;
2053 }
2054 return size;
2055}
2056
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002057void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2058 for (HInstruction* current = first_instruction_;
2059 current != nullptr;
2060 current = current->GetNext()) {
2061 current->SetBlock(block);
2062 }
2063}
2064
2065void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2066 DCHECK(Contains(cursor));
2067 if (!instruction_list.IsEmpty()) {
2068 if (cursor == last_instruction_) {
2069 last_instruction_ = instruction_list.last_instruction_;
2070 } else {
2071 cursor->next_->previous_ = instruction_list.last_instruction_;
2072 }
2073 instruction_list.last_instruction_->next_ = cursor->next_;
2074 cursor->next_ = instruction_list.first_instruction_;
2075 instruction_list.first_instruction_->previous_ = cursor;
2076 }
2077}
2078
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002079void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2080 DCHECK(Contains(cursor));
2081 if (!instruction_list.IsEmpty()) {
2082 if (cursor == first_instruction_) {
2083 first_instruction_ = instruction_list.first_instruction_;
2084 } else {
2085 cursor->previous_->next_ = instruction_list.first_instruction_;
2086 }
2087 instruction_list.last_instruction_->next_ = cursor;
2088 instruction_list.first_instruction_->previous_ = cursor->previous_;
2089 cursor->previous_ = instruction_list.last_instruction_;
2090 }
2091}
2092
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002093void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002094 if (IsEmpty()) {
2095 first_instruction_ = instruction_list.first_instruction_;
2096 last_instruction_ = instruction_list.last_instruction_;
2097 } else {
2098 AddAfter(last_instruction_, instruction_list);
2099 }
2100}
2101
David Brazdil04ff4e82015-12-10 13:54:52 +00002102// Should be called on instructions in a dead block in post order. This method
2103// assumes `insn` has been removed from all users with the exception of catch
2104// phis because of missing exceptional edges in the graph. It removes the
2105// instruction from catch phi uses, together with inputs of other catch phis in
2106// the catch block at the same index, as these must be dead too.
2107static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2108 DCHECK(!insn->HasEnvironmentUses());
2109 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002110 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2111 size_t use_index = use.GetIndex();
2112 HBasicBlock* user_block = use.GetUser()->GetBlock();
2113 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002114 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2115 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2116 }
2117 }
2118}
2119
David Brazdil2d7352b2015-04-20 14:52:42 +01002120void HBasicBlock::DisconnectAndDelete() {
2121 // Dominators must be removed after all the blocks they dominate. This way
2122 // a loop header is removed last, a requirement for correct loop information
2123 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002124 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002125
David Brazdil9eeebf62016-03-24 11:18:15 +00002126 // The following steps gradually remove the block from all its dependants in
2127 // post order (b/27683071).
2128
2129 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2130 // We need to do this before step (4) which destroys the predecessor list.
2131 HBasicBlock* loop_update_start = this;
2132 if (IsLoopHeader()) {
2133 HLoopInformation* loop_info = GetLoopInformation();
2134 // All other blocks in this loop should have been removed because the header
2135 // was their dominator.
2136 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2137 DCHECK(!loop_info->IsIrreducible());
2138 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2139 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2140 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002141 }
2142
David Brazdil9eeebf62016-03-24 11:18:15 +00002143 // (2) Disconnect the block from its successors and update their phis.
2144 for (HBasicBlock* successor : successors_) {
2145 // Delete this block from the list of predecessors.
2146 size_t this_index = successor->GetPredecessorIndexOf(this);
2147 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2148
2149 // Check that `successor` has other predecessors, otherwise `this` is the
2150 // dominator of `successor` which violates the order DCHECKed at the top.
2151 DCHECK(!successor->predecessors_.empty());
2152
2153 // Remove this block's entries in the successor's phis. Skip exceptional
2154 // successors because catch phi inputs do not correspond to predecessor
2155 // blocks but throwing instructions. The inputs of the catch phis will be
2156 // updated in step (3).
2157 if (!successor->IsCatchBlock()) {
2158 if (successor->predecessors_.size() == 1u) {
2159 // The successor has just one predecessor left. Replace phis with the only
2160 // remaining input.
2161 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2162 HPhi* phi = phi_it.Current()->AsPhi();
2163 phi->ReplaceWith(phi->InputAt(1 - this_index));
2164 successor->RemovePhi(phi);
2165 }
2166 } else {
2167 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2168 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2169 }
2170 }
2171 }
2172 }
2173 successors_.clear();
2174
2175 // (3) Remove instructions and phis. Instructions should have no remaining uses
2176 // except in catch phis. If an instruction is used by a catch phi at `index`,
2177 // remove `index`-th input of all phis in the catch block since they are
2178 // guaranteed dead. Note that we may miss dead inputs this way but the
2179 // graph will always remain consistent.
2180 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2181 HInstruction* insn = it.Current();
2182 RemoveUsesOfDeadInstruction(insn);
2183 RemoveInstruction(insn);
2184 }
2185 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2186 HPhi* insn = it.Current()->AsPhi();
2187 RemoveUsesOfDeadInstruction(insn);
2188 RemovePhi(insn);
2189 }
2190
2191 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002192 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002193 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002194 // We should not see any back edges as they would have been removed by step (3).
2195 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2196
David Brazdil2d7352b2015-04-20 14:52:42 +01002197 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002198 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2199 // This block is the only normal-flow successor of the TryBoundary which
2200 // makes `predecessor` dead. Since DCE removes blocks in post order,
2201 // exception handlers of this TryBoundary were already visited and any
2202 // remaining handlers therefore must be live. We remove `predecessor` from
2203 // their list of predecessors.
2204 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2205 while (predecessor->GetSuccessors().size() > 1) {
2206 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2207 DCHECK(handler->IsCatchBlock());
2208 predecessor->RemoveSuccessor(handler);
2209 handler->RemovePredecessor(predecessor);
2210 }
2211 }
2212
David Brazdil2d7352b2015-04-20 14:52:42 +01002213 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002214 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2215 if (num_pred_successors == 1u) {
2216 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002217 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2218 // successor. Replace those with a HGoto.
2219 DCHECK(last_instruction->IsIf() ||
2220 last_instruction->IsPackedSwitch() ||
2221 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002222 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002223 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002224 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002225 // The predecessor has no remaining successors and therefore must be dead.
2226 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002227 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002228 predecessor->RemoveInstruction(last_instruction);
2229 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002230 // There are multiple successors left. The removed block might be a successor
2231 // of a PackedSwitch which will be completely removed (perhaps replaced with
2232 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2233 // case, leave `last_instruction` as is for now.
2234 DCHECK(last_instruction->IsPackedSwitch() ||
2235 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002236 }
David Brazdil46e2a392015-03-16 17:31:52 +00002237 }
Vladimir Marko60584552015-09-03 13:35:12 +00002238 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002239
David Brazdil9eeebf62016-03-24 11:18:15 +00002240 // (5) Remove the block from all loops it is included in. Skip the inner-most
2241 // loop if this is the loop header (see definition of `loop_update_start`)
2242 // because the loop header's predecessor list has been destroyed in step (4).
2243 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2244 HLoopInformation* loop_info = it.Current();
2245 loop_info->Remove(this);
2246 if (loop_info->IsBackEdge(*this)) {
2247 // If this was the last back edge of the loop, we deliberately leave the
2248 // loop in an inconsistent state and will fail GraphChecker unless the
2249 // entire loop is removed during the pass.
2250 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002251 }
2252 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002253
David Brazdil9eeebf62016-03-24 11:18:15 +00002254 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002255 dominator_->RemoveDominatedBlock(this);
2256 SetDominator(nullptr);
2257
David Brazdil9eeebf62016-03-24 11:18:15 +00002258 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002259 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002260 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002261}
2262
Aart Bik6b69e0a2017-01-11 10:20:43 -08002263void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2264 DCHECK(EndsWithControlFlowInstruction());
2265 RemoveInstruction(GetLastInstruction());
2266 instructions_.Add(other->GetInstructions());
2267 other->instructions_.SetBlockOfInstructions(this);
2268 other->instructions_.Clear();
2269}
2270
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002271void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002272 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002273 DCHECK(ContainsElement(dominated_blocks_, other));
2274 DCHECK_EQ(GetSingleSuccessor(), other);
2275 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002276 DCHECK(other->GetPhis().IsEmpty());
2277
David Brazdil2d7352b2015-04-20 14:52:42 +01002278 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002279 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002280
David Brazdil2d7352b2015-04-20 14:52:42 +01002281 // Remove `other` from the loops it is included in.
2282 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2283 HLoopInformation* loop_info = it.Current();
2284 loop_info->Remove(other);
2285 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002286 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002287 }
2288 }
2289
2290 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002291 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002292 for (HBasicBlock* successor : other->GetSuccessors()) {
2293 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002294 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002295 successors_.swap(other->successors_);
2296 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002297
David Brazdil2d7352b2015-04-20 14:52:42 +01002298 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002299 RemoveDominatedBlock(other);
2300 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002301 dominated->SetDominator(this);
2302 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002303 dominated_blocks_.insert(
2304 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002305 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002306 other->dominator_ = nullptr;
2307
2308 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002309 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002310
2311 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002312 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002313 other->SetGraph(nullptr);
2314}
2315
2316void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2317 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002318 DCHECK(GetDominatedBlocks().empty());
2319 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002320 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002321 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002322 DCHECK(other->GetPhis().IsEmpty());
2323 DCHECK(!other->IsInLoop());
2324
2325 // Move instructions from `other` to `this`.
2326 instructions_.Add(other->GetInstructions());
2327 other->instructions_.SetBlockOfInstructions(this);
2328
2329 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002330 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002331 for (HBasicBlock* successor : other->GetSuccessors()) {
2332 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002333 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002334 successors_.swap(other->successors_);
2335 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002336
2337 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002338 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002339 dominated->SetDominator(this);
2340 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002341 dominated_blocks_.insert(
2342 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002343 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002344 other->dominator_ = nullptr;
2345 other->graph_ = nullptr;
2346}
2347
2348void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002349 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002350 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002351 predecessor->ReplaceSuccessor(this, other);
2352 }
Vladimir Marko60584552015-09-03 13:35:12 +00002353 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002354 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002355 successor->ReplacePredecessor(this, other);
2356 }
Vladimir Marko60584552015-09-03 13:35:12 +00002357 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2358 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002359 }
2360 GetDominator()->ReplaceDominatedBlock(this, other);
2361 other->SetDominator(GetDominator());
2362 dominator_ = nullptr;
2363 graph_ = nullptr;
2364}
2365
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002366void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002367 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002368 DCHECK(block->GetSuccessors().empty());
2369 DCHECK(block->GetPredecessors().empty());
2370 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002371 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002372 DCHECK(block->GetInstructions().IsEmpty());
2373 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002374
David Brazdilc7af85d2015-05-26 12:05:55 +01002375 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002376 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002377 }
2378
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002379 RemoveElement(reverse_post_order_, block);
2380 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002381 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002382}
2383
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002384void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2385 HBasicBlock* reference,
2386 bool replace_if_back_edge) {
2387 if (block->IsLoopHeader()) {
2388 // Clear the information of which blocks are contained in that loop. Since the
2389 // information is stored as a bit vector based on block ids, we have to update
2390 // it, as those block ids were specific to the callee graph and we are now adding
2391 // these blocks to the caller graph.
2392 block->GetLoopInformation()->ClearAllBlocks();
2393 }
2394
2395 // If not already in a loop, update the loop information.
2396 if (!block->IsInLoop()) {
2397 block->SetLoopInformation(reference->GetLoopInformation());
2398 }
2399
2400 // If the block is in a loop, update all its outward loops.
2401 HLoopInformation* loop_info = block->GetLoopInformation();
2402 if (loop_info != nullptr) {
2403 for (HLoopInformationOutwardIterator loop_it(*block);
2404 !loop_it.Done();
2405 loop_it.Advance()) {
2406 loop_it.Current()->Add(block);
2407 }
2408 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2409 loop_info->ReplaceBackEdge(reference, block);
2410 }
2411 }
2412
2413 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2414 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2415 ? reference->GetTryCatchInformation()
2416 : nullptr;
2417 block->SetTryCatchInformation(try_catch_info);
2418}
2419
Calin Juravle2e768302015-07-28 14:41:11 +00002420HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002421 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002422 // Update the environments in this graph to have the invoke's environment
2423 // as parent.
2424 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002425 // Skip the entry block, we do not need to update the entry's suspend check.
2426 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002427 for (HInstructionIterator instr_it(block->GetInstructions());
2428 !instr_it.Done();
2429 instr_it.Advance()) {
2430 HInstruction* current = instr_it.Current();
2431 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002432 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002433 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002434 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002435 }
2436 }
2437 }
2438 }
2439 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002440
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002441 if (HasBoundsChecks()) {
2442 outer_graph->SetHasBoundsChecks(true);
2443 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002444 if (HasLoops()) {
2445 outer_graph->SetHasLoops(true);
2446 }
2447 if (HasIrreducibleLoops()) {
2448 outer_graph->SetHasIrreducibleLoops(true);
2449 }
2450 if (HasTryCatch()) {
2451 outer_graph->SetHasTryCatch(true);
2452 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002453 if (HasSIMD()) {
2454 outer_graph->SetHasSIMD(true);
2455 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002456
Calin Juravle2e768302015-07-28 14:41:11 +00002457 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002458 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002459 // Inliner already made sure we don't inline methods that always throw.
2460 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002461 // Simple case of an entry block, a body block, and an exit block.
2462 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002463 HBasicBlock* body = GetBlocks()[1];
2464 DCHECK(GetBlocks()[0]->IsEntryBlock());
2465 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002466 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002467 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002468 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002469
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002470 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2471 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002472 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002473
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002474 // Replace the invoke with the return value of the inlined graph.
2475 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002476 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002477 } else {
2478 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002479 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002480
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002481 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002482 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002483 // Need to inline multiple blocks. We split `invoke`'s block
2484 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002485 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002486 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002487 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002488 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002489 // Note that we split before the invoke only to simplify polymorphic inlining.
2490 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002491
Vladimir Markoec7802a2015-10-01 20:57:57 +01002492 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002493 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002494 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002495 exit_block_->ReplaceWith(to);
2496
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002497 // Update the meta information surrounding blocks:
2498 // (1) the graph they are now in,
2499 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002500 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002501 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002502 // Note that we do not need to update catch phi inputs because they
2503 // correspond to the register file of the outer method which the inlinee
2504 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002505
2506 // We don't add the entry block, the exit block, and the first block, which
2507 // has been merged with `at`.
2508 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2509
2510 // We add the `to` block.
2511 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002512 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002513 + kNumberOfNewBlocksInCaller;
2514
2515 // Find the location of `at` in the outer graph's reverse post order. The new
2516 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002517 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002518 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2519
David Brazdil95177982015-10-30 12:56:58 -05002520 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2521 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002522 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002523 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002524 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002525 DCHECK(current->GetGraph() == this);
2526 current->SetGraph(outer_graph);
2527 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002528 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002529 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002530 }
2531 }
2532
David Brazdil95177982015-10-30 12:56:58 -05002533 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002534 to->SetGraph(outer_graph);
2535 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002536 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002537 // Only `to` can become a back edge, as the inlined blocks
2538 // are predecessors of `to`.
2539 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002540
David Brazdil3f523062016-02-29 16:53:33 +00002541 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002542 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2543 // to now get the outer graph exit block as successor. Note that the inliner
2544 // currently doesn't support inlining methods with try/catch.
2545 HPhi* return_value_phi = nullptr;
2546 bool rerun_dominance = false;
2547 bool rerun_loop_analysis = false;
2548 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2549 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002550 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002551 if (last->IsThrow()) {
2552 DCHECK(!at->IsTryBlock());
2553 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2554 --pred;
2555 // We need to re-run dominance information, as the exit block now has
2556 // a new dominator.
2557 rerun_dominance = true;
2558 if (predecessor->GetLoopInformation() != nullptr) {
2559 // The exit block and blocks post dominated by the exit block do not belong
2560 // to any loop. Because we do not compute the post dominators, we need to re-run
2561 // loop analysis to get the loop information correct.
2562 rerun_loop_analysis = true;
2563 }
2564 } else {
2565 if (last->IsReturnVoid()) {
2566 DCHECK(return_value == nullptr);
2567 DCHECK(return_value_phi == nullptr);
2568 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002569 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002570 if (return_value_phi != nullptr) {
2571 return_value_phi->AddInput(last->InputAt(0));
2572 } else if (return_value == nullptr) {
2573 return_value = last->InputAt(0);
2574 } else {
2575 // There will be multiple returns.
2576 return_value_phi = new (allocator) HPhi(
2577 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2578 to->AddPhi(return_value_phi);
2579 return_value_phi->AddInput(return_value);
2580 return_value_phi->AddInput(last->InputAt(0));
2581 return_value = return_value_phi;
2582 }
David Brazdil3f523062016-02-29 16:53:33 +00002583 }
2584 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2585 predecessor->RemoveInstruction(last);
2586 }
2587 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002588 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002589 DCHECK(!outer_graph->HasIrreducibleLoops())
2590 << "Recomputing loop information in graphs with irreducible loops "
2591 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002592 outer_graph->ClearLoopInformation();
2593 outer_graph->ClearDominanceInformation();
2594 outer_graph->BuildDominatorTree();
2595 } else if (rerun_dominance) {
2596 outer_graph->ClearDominanceInformation();
2597 outer_graph->ComputeDominanceInformation();
2598 }
David Brazdil3f523062016-02-29 16:53:33 +00002599 }
David Brazdil05144f42015-04-16 15:18:00 +01002600
2601 // Walk over the entry block and:
2602 // - Move constants from the entry block to the outer_graph's entry block,
2603 // - Replace HParameterValue instructions with their real value.
2604 // - Remove suspend checks, that hold an environment.
2605 // We must do this after the other blocks have been inlined, otherwise ids of
2606 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002607 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002608 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2609 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002610 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002611 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002612 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002613 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002614 replacement = outer_graph->GetIntConstant(
2615 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002616 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002617 replacement = outer_graph->GetLongConstant(
2618 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002619 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002620 replacement = outer_graph->GetFloatConstant(
2621 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002622 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002623 replacement = outer_graph->GetDoubleConstant(
2624 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002625 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002626 if (kIsDebugBuild
2627 && invoke->IsInvokeStaticOrDirect()
2628 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2629 // Ensure we do not use the last input of `invoke`, as it
2630 // contains a clinit check which is not an actual argument.
2631 size_t last_input_index = invoke->InputCount() - 1;
2632 DCHECK(parameter_index != last_input_index);
2633 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002634 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002635 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002636 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002637 } else {
2638 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2639 entry_block_->RemoveInstruction(current);
2640 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002641 if (replacement != nullptr) {
2642 current->ReplaceWith(replacement);
2643 // If the current is the return value then we need to update the latter.
2644 if (current == return_value) {
2645 DCHECK_EQ(entry_block_, return_value->GetBlock());
2646 return_value = replacement;
2647 }
2648 }
2649 }
2650
Calin Juravle2e768302015-07-28 14:41:11 +00002651 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002652}
2653
Mingyao Yang3584bce2015-05-19 16:01:59 -07002654/*
2655 * Loop will be transformed to:
2656 * old_pre_header
2657 * |
2658 * if_block
2659 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002660 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002661 * \ /
2662 * new_pre_header
2663 * |
2664 * header
2665 */
2666void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2667 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002668 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002669
Aart Bik3fc7f352015-11-20 22:03:03 -08002670 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002671 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2672 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2673 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2674 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002675 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002676 AddBlock(true_block);
2677 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002678 AddBlock(new_pre_header);
2679
Aart Bik3fc7f352015-11-20 22:03:03 -08002680 header->ReplacePredecessor(old_pre_header, new_pre_header);
2681 old_pre_header->successors_.clear();
2682 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002683
Aart Bik3fc7f352015-11-20 22:03:03 -08002684 old_pre_header->AddSuccessor(if_block);
2685 if_block->AddSuccessor(true_block); // True successor
2686 if_block->AddSuccessor(false_block); // False successor
2687 true_block->AddSuccessor(new_pre_header);
2688 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002689
Aart Bik3fc7f352015-11-20 22:03:03 -08002690 old_pre_header->dominated_blocks_.push_back(if_block);
2691 if_block->SetDominator(old_pre_header);
2692 if_block->dominated_blocks_.push_back(true_block);
2693 true_block->SetDominator(if_block);
2694 if_block->dominated_blocks_.push_back(false_block);
2695 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002696 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002697 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002698 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002699 header->SetDominator(new_pre_header);
2700
Aart Bik3fc7f352015-11-20 22:03:03 -08002701 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002702 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002703 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002704 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002705 reverse_post_order_[index_of_header++] = true_block;
2706 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002707 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002708
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002709 // The pre_header can never be a back edge of a loop.
2710 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2711 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2712 UpdateLoopAndTryInformationOfNewBlock(
2713 if_block, old_pre_header, /* replace_if_back_edge */ false);
2714 UpdateLoopAndTryInformationOfNewBlock(
2715 true_block, old_pre_header, /* replace_if_back_edge */ false);
2716 UpdateLoopAndTryInformationOfNewBlock(
2717 false_block, old_pre_header, /* replace_if_back_edge */ false);
2718 UpdateLoopAndTryInformationOfNewBlock(
2719 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002720}
2721
Aart Bikf8f5a162017-02-06 15:35:29 -08002722HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2723 HBasicBlock* body,
2724 HBasicBlock* exit) {
2725 DCHECK(header->IsLoopHeader());
2726 HLoopInformation* loop = header->GetLoopInformation();
2727
2728 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002729 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2730 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2731 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002732 AddBlock(new_pre_header);
2733 AddBlock(new_header);
2734 AddBlock(new_body);
2735
2736 // Set up control flow.
2737 header->ReplaceSuccessor(exit, new_pre_header);
2738 new_pre_header->AddSuccessor(new_header);
2739 new_header->AddSuccessor(exit);
2740 new_header->AddSuccessor(new_body);
2741 new_body->AddSuccessor(new_header);
2742
2743 // Set up dominators.
2744 header->ReplaceDominatedBlock(exit, new_pre_header);
2745 new_pre_header->SetDominator(header);
2746 new_pre_header->dominated_blocks_.push_back(new_header);
2747 new_header->SetDominator(new_pre_header);
2748 new_header->dominated_blocks_.push_back(new_body);
2749 new_body->SetDominator(new_header);
2750 new_header->dominated_blocks_.push_back(exit);
2751 exit->SetDominator(new_header);
2752
2753 // Fix reverse post order.
2754 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2755 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2756 reverse_post_order_[++index_of_header] = new_pre_header;
2757 reverse_post_order_[++index_of_header] = new_header;
2758 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2759 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2760 reverse_post_order_[index_of_body] = new_body;
2761
Aart Bikb07d1bc2017-04-05 10:03:15 -07002762 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002763 new_pre_header->AddInstruction(new (allocator_) HGoto());
2764 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002765 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002766 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002767 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2768 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002769
2770 // Update loop information.
2771 new_header->AddBackEdge(new_body);
2772 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2773 new_header->GetLoopInformation()->Populate();
2774 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2775 HLoopInformationOutwardIterator it(*new_header);
2776 for (it.Advance(); !it.Done(); it.Advance()) {
2777 it.Current()->Add(new_pre_header);
2778 it.Current()->Add(new_header);
2779 it.Current()->Add(new_body);
2780 }
2781 return new_pre_header;
2782}
2783
David Brazdilf5552582015-12-27 13:36:12 +00002784static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002785 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002786 if (rti.IsValid()) {
2787 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2788 << " upper_bound_rti: " << upper_bound_rti
2789 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002790 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2791 << " upper_bound_rti: " << upper_bound_rti
2792 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002793 }
2794}
2795
Calin Juravle2e768302015-07-28 14:41:11 +00002796void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2797 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002798 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002799 ScopedObjectAccess soa(Thread::Current());
2800 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2801 if (IsBoundType()) {
2802 // Having the test here spares us from making the method virtual just for
2803 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002804 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002805 }
2806 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002807 reference_type_handle_ = rti.GetTypeHandle();
2808 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002809}
2810
Artem Serov4d277ba2018-06-05 20:54:42 +01002811bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
2812 const HBoundType* other_bt = other->AsBoundType();
2813 ScopedObjectAccess soa(Thread::Current());
2814 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
2815 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
2816 CanBeNull() == other_bt->CanBeNull();
2817}
2818
David Brazdilf5552582015-12-27 13:36:12 +00002819void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2820 if (kIsDebugBuild) {
2821 ScopedObjectAccess soa(Thread::Current());
2822 DCHECK(upper_bound.IsValid());
2823 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2824 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2825 }
2826 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002827 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002828}
2829
Vladimir Markoa1de9182016-02-25 11:37:38 +00002830ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002831 if (kIsDebugBuild) {
2832 ScopedObjectAccess soa(Thread::Current());
2833 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002834 if (!is_exact) {
2835 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2836 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2837 }
Calin Juravle2e768302015-07-28 14:41:11 +00002838 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002839 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002840}
2841
Calin Juravleacf735c2015-02-12 15:25:22 +00002842std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2843 ScopedObjectAccess soa(Thread::Current());
2844 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002845 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002846 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002847 << " is_exact=" << rhs.IsExact()
2848 << " ]";
2849 return os;
2850}
2851
Mark Mendellc4701932015-04-10 13:18:51 -04002852bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2853 // For now, assume that instructions in different blocks may use the
2854 // environment.
2855 // TODO: Use the control flow to decide if this is true.
2856 if (GetBlock() != other->GetBlock()) {
2857 return true;
2858 }
2859
2860 // We know that we are in the same block. Walk from 'this' to 'other',
2861 // checking to see if there is any instruction with an environment.
2862 HInstruction* current = this;
2863 for (; current != other && current != nullptr; current = current->GetNext()) {
2864 // This is a conservative check, as the instruction result may not be in
2865 // the referenced environment.
2866 if (current->HasEnvironment()) {
2867 return true;
2868 }
2869 }
2870
2871 // We should have been called with 'this' before 'other' in the block.
2872 // Just confirm this.
2873 DCHECK(current != nullptr);
2874 return false;
2875}
2876
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002877void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002878 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2879 IntrinsicSideEffects side_effects,
2880 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002881 intrinsic_ = intrinsic;
2882 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002883
Aart Bik5d75afe2015-12-14 11:57:01 -08002884 // Adjust method's side effects from intrinsic table.
2885 switch (side_effects) {
2886 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2887 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2888 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2889 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2890 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002891
2892 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2893 opt.SetDoesNotNeedDexCache();
2894 opt.SetDoesNotNeedEnvironment();
2895 } else {
2896 // If we need an environment, that means there will be a call, which can trigger GC.
2897 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2898 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002899 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002900 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002901}
2902
David Brazdil6de19382016-01-08 17:37:10 +00002903bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07002904 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00002905}
2906
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002907bool HInvoke::NeedsEnvironment() const {
2908 if (!IsIntrinsic()) {
2909 return true;
2910 }
2911 IntrinsicOptimizations opt(*this);
2912 return !opt.GetDoesNotNeedEnvironment();
2913}
2914
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002915const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2916 ArtMethod* caller = GetEnvironment()->GetMethod();
2917 ScopedObjectAccess soa(Thread::Current());
2918 // `caller` is null for a top-level graph representing a method whose declaring
2919 // class was not resolved.
2920 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2921}
2922
Vladimir Markodc151b22015-10-15 18:02:30 +01002923bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002924 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002925 return false;
2926 }
2927 if (!IsIntrinsic()) {
2928 return true;
2929 }
2930 IntrinsicOptimizations opt(*this);
2931 return !opt.GetDoesNotNeedDexCache();
2932}
2933
Vladimir Markof64242a2015-12-01 14:58:23 +00002934std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2935 switch (rhs) {
2936 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002937 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002938 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002939 return os << "Recursive";
2940 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2941 return os << "BootImageLinkTimePcRelative";
Vladimir Markob066d432018-01-03 13:14:37 +00002942 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageRelRo:
2943 return os << "BootImageRelRo";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002944 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2945 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002946 case HInvokeStaticOrDirect::MethodLoadKind::kJitDirectAddress:
2947 return os << "JitDirectAddress";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002948 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2949 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002950 default:
2951 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2952 UNREACHABLE();
2953 }
2954}
2955
Vladimir Markofbb184a2015-11-13 14:47:00 +00002956std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2957 switch (rhs) {
2958 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2959 return os << "explicit";
2960 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2961 return os << "implicit";
2962 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2963 return os << "none";
2964 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002965 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2966 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002967 }
2968}
2969
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002970bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2971 const HLoadClass* other_load_class = other->AsLoadClass();
2972 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2973 // names rather than type indexes. However, we shall also have to re-think the hash code.
2974 if (type_index_ != other_load_class->type_index_ ||
2975 GetPackedFields() != other_load_class->GetPackedFields()) {
2976 return false;
2977 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002978 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002979 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002980 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002981 case LoadKind::kJitTableAddress: {
2982 ScopedObjectAccess soa(Thread::Current());
2983 return GetClass().Get() == other_load_class->GetClass().Get();
2984 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002985 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002986 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002987 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002988 }
2989}
2990
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002991std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2992 switch (rhs) {
2993 case HLoadClass::LoadKind::kReferrersClass:
2994 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002995 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2996 return os << "BootImageLinkTimePcRelative";
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002997 case HLoadClass::LoadKind::kBootImageRelRo:
2998 return os << "BootImageRelRo";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002999 case HLoadClass::LoadKind::kBssEntry:
3000 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003001 case HLoadClass::LoadKind::kJitBootImageAddress:
3002 return os << "JitBootImageAddress";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00003003 case HLoadClass::LoadKind::kJitTableAddress:
3004 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01003005 case HLoadClass::LoadKind::kRuntimeCall:
3006 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003007 default:
3008 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
3009 UNREACHABLE();
3010 }
3011}
3012
Vladimir Marko372f10e2016-05-17 16:30:10 +01003013bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3014 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003015 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3016 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003017 if (string_index_ != other_load_string->string_index_ ||
3018 GetPackedFields() != other_load_string->GetPackedFields()) {
3019 return false;
3020 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003021 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003022 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003023 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003024 case LoadKind::kJitTableAddress: {
3025 ScopedObjectAccess soa(Thread::Current());
3026 return GetString().Get() == other_load_string->GetString().Get();
3027 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003028 default:
3029 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003030 }
3031}
3032
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003033std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
3034 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003035 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
3036 return os << "BootImageLinkTimePcRelative";
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003037 case HLoadString::LoadKind::kBootImageRelRo:
3038 return os << "BootImageRelRo";
Vladimir Markoaad75c62016-10-03 08:46:48 +00003039 case HLoadString::LoadKind::kBssEntry:
3040 return os << "BssEntry";
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003041 case HLoadString::LoadKind::kJitBootImageAddress:
3042 return os << "JitBootImageAddress";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08003043 case HLoadString::LoadKind::kJitTableAddress:
3044 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01003045 case HLoadString::LoadKind::kRuntimeCall:
3046 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003047 default:
3048 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
3049 UNREACHABLE();
3050 }
3051}
3052
Mark Mendellc4701932015-04-10 13:18:51 -04003053void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003054 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3055 HEnvironment* user = use.GetUser();
3056 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003057 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003058 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003059}
3060
Artem Serovcced8ba2017-07-19 18:18:09 +01003061HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3062 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3063 HBasicBlock* block = instr->GetBlock();
3064
3065 if (instr->IsPhi()) {
3066 HPhi* phi = instr->AsPhi();
3067 DCHECK(!phi->HasEnvironment());
3068 HPhi* phi_clone = clone->AsPhi();
3069 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3070 } else {
3071 block->ReplaceAndRemoveInstructionWith(instr, clone);
3072 if (instr->HasEnvironment()) {
3073 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3074 HLoopInformation* loop_info = block->GetLoopInformation();
3075 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3076 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3077 }
3078 }
3079 }
3080 return clone;
3081}
3082
Roland Levillainc9b21f82016-03-23 16:36:59 +00003083// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003084HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003085 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003086
3087 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003088 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003089 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3090 HInstruction* lhs = cond->InputAt(0);
3091 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003092 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003093 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3094 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3095 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3096 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3097 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3098 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3099 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3100 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3101 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3102 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3103 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003104 default:
3105 LOG(FATAL) << "Unexpected condition";
3106 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003107 }
3108 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3109 return replacement;
3110 } else if (cond->IsIntConstant()) {
3111 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003112 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003113 return GetIntConstant(1);
3114 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003115 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003116 return GetIntConstant(0);
3117 }
3118 } else {
3119 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3120 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3121 return replacement;
3122 }
3123}
3124
Roland Levillainc9285912015-12-18 10:38:42 +00003125std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3126 os << "["
3127 << " source=" << rhs.GetSource()
3128 << " destination=" << rhs.GetDestination()
3129 << " type=" << rhs.GetType()
3130 << " instruction=";
3131 if (rhs.GetInstruction() != nullptr) {
3132 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3133 } else {
3134 os << "null";
3135 }
3136 os << " ]";
3137 return os;
3138}
3139
Roland Levillain86503782016-02-11 19:07:30 +00003140std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3141 switch (rhs) {
3142 case TypeCheckKind::kUnresolvedCheck:
3143 return os << "unresolved_check";
3144 case TypeCheckKind::kExactCheck:
3145 return os << "exact_check";
3146 case TypeCheckKind::kClassHierarchyCheck:
3147 return os << "class_hierarchy_check";
3148 case TypeCheckKind::kAbstractClassCheck:
3149 return os << "abstract_class_check";
3150 case TypeCheckKind::kInterfaceCheck:
3151 return os << "interface_check";
3152 case TypeCheckKind::kArrayObjectCheck:
3153 return os << "array_object_check";
3154 case TypeCheckKind::kArrayCheck:
3155 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003156 case TypeCheckKind::kBitstringCheck:
3157 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003158 default:
3159 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3160 UNREACHABLE();
3161 }
3162}
3163
Andreas Gampe26de38b2016-07-27 17:53:11 -07003164std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
3165 switch (kind) {
3166 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003167 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003168 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003169 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003170 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003171 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003172 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003173 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003174 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003175 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003176
3177 default:
3178 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3179 UNREACHABLE();
3180 }
3181}
3182
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003183// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3184#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3185 static_assert( \
3186 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3187 "Instrinsics enumeration space overflow.");
3188#include "intrinsics_list.h"
3189 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3190#undef INTRINSICS_LIST
3191#undef CHECK_INTRINSICS_ENUM_VALUES
3192
3193// Function that returns whether an intrinsic needs an environment or not.
3194static inline IntrinsicNeedsEnvironmentOrCache NeedsEnvironmentOrCacheIntrinsic(Intrinsics i) {
3195 switch (i) {
3196 case Intrinsics::kNone:
3197 return kNeedsEnvironmentOrCache; // Non-sensical for intrinsic.
3198#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3199 case Intrinsics::k ## Name: \
3200 return NeedsEnvOrCache;
3201#include "intrinsics_list.h"
3202 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3203#undef INTRINSICS_LIST
3204#undef OPTIMIZING_INTRINSICS
3205 }
3206 return kNeedsEnvironmentOrCache;
3207}
3208
3209// Function that returns whether an intrinsic has side effects.
3210static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3211 switch (i) {
3212 case Intrinsics::kNone:
3213 return kAllSideEffects;
3214#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3215 case Intrinsics::k ## Name: \
3216 return SideEffects;
3217#include "intrinsics_list.h"
3218 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3219#undef INTRINSICS_LIST
3220#undef OPTIMIZING_INTRINSICS
3221 }
3222 return kAllSideEffects;
3223}
3224
3225// Function that returns whether an intrinsic can throw exceptions.
3226static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3227 switch (i) {
3228 case Intrinsics::kNone:
3229 return kCanThrow;
3230#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3231 case Intrinsics::k ## Name: \
3232 return Exceptions;
3233#include "intrinsics_list.h"
3234 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3235#undef INTRINSICS_LIST
3236#undef OPTIMIZING_INTRINSICS
3237 }
3238 return kCanThrow;
3239}
3240
3241void HInvoke::SetResolvedMethod(ArtMethod* method) {
3242 // TODO: b/65872996 The intent is that polymorphic signature methods should
3243 // be compiler intrinsics. At present, they are only interpreter intrinsics.
3244 if (method != nullptr &&
3245 method->IsIntrinsic() &&
3246 !method->IsPolymorphicSignature()) {
3247 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3248 SetIntrinsic(intrinsic,
3249 NeedsEnvironmentOrCacheIntrinsic(intrinsic),
3250 GetSideEffectsIntrinsic(intrinsic),
3251 GetExceptionsIntrinsic(intrinsic));
3252 }
3253 resolved_method_ = method;
3254}
3255
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003256} // namespace art