blob: 727431a49379731a0b69cb4808f550338802cc6e [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
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
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100868HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000869 HBasicBlock* block = header_->GetPredecessors()[0];
870 DCHECK(irreducible_ || (block == header_->GetDominator()));
871 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100872}
873
874bool HLoopInformation::Contains(const HBasicBlock& block) const {
875 return blocks_.IsBitSet(block.GetBlockId());
876}
877
878bool HLoopInformation::IsIn(const HLoopInformation& other) const {
879 return other.blocks_.IsBitSet(header_->GetBlockId());
880}
881
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800882bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
883 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700884}
885
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100886size_t HLoopInformation::GetLifetimeEnd() const {
887 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100888 for (HBasicBlock* back_edge : GetBackEdges()) {
889 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100890 }
891 return last_position;
892}
893
David Brazdil3f4a5222016-05-06 12:46:21 +0100894bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
895 for (HBasicBlock* back_edge : GetBackEdges()) {
896 DCHECK(back_edge->GetDominator() != nullptr);
897 if (!header_->Dominates(back_edge)) {
898 return true;
899 }
900 }
901 return false;
902}
903
Anton Shaminf89381f2016-05-16 16:44:13 +0600904bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
905 for (HBasicBlock* back_edge : GetBackEdges()) {
906 if (!block->Dominates(back_edge)) {
907 return false;
908 }
909 }
910 return true;
911}
912
David Sehrc757dec2016-11-04 15:48:34 -0700913
914bool HLoopInformation::HasExitEdge() const {
915 // Determine if this loop has at least one exit edge.
916 HBlocksInLoopReversePostOrderIterator it_loop(*this);
917 for (; !it_loop.Done(); it_loop.Advance()) {
918 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
919 if (!Contains(*successor)) {
920 return true;
921 }
922 }
923 }
924 return false;
925}
926
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100927bool HBasicBlock::Dominates(HBasicBlock* other) const {
928 // Walk up the dominator tree from `other`, to find out if `this`
929 // is an ancestor.
930 HBasicBlock* current = other;
931 while (current != nullptr) {
932 if (current == this) {
933 return true;
934 }
935 current = current->GetDominator();
936 }
937 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938}
939
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100940static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100941 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100942 for (size_t i = 0; i < inputs.size(); ++i) {
943 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100944 }
945 // Environment should be created later.
946 DCHECK(!instruction->HasEnvironment());
947}
948
Artem Serovcced8ba2017-07-19 18:18:09 +0100949void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
950 DCHECK(initial->GetBlock() == this);
951 InsertPhiAfter(replacement, initial);
952 initial->ReplaceWith(replacement);
953 RemovePhi(initial);
954}
955
Roland Levillainccc07a92014-09-16 14:48:16 +0100956void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
957 HInstruction* replacement) {
958 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400959 if (initial->IsControlFlow()) {
960 // We can only replace a control flow instruction with another control flow instruction.
961 DCHECK(replacement->IsControlFlow());
962 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100963 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400964 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100965 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100966 DCHECK(initial->GetUses().empty());
967 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400968 replacement->SetBlock(this);
969 replacement->SetId(GetGraph()->GetNextInstructionId());
970 instructions_.InsertInstructionBefore(replacement, initial);
971 UpdateInputsUsers(replacement);
972 } else {
973 InsertInstructionBefore(replacement, initial);
974 initial->ReplaceWith(replacement);
975 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100976 RemoveInstruction(initial);
977}
978
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100979static void Add(HInstructionList* instruction_list,
980 HBasicBlock* block,
981 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000982 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000983 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100984 instruction->SetBlock(block);
985 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100986 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100987 instruction_list->AddInstruction(instruction);
988}
989
990void HBasicBlock::AddInstruction(HInstruction* instruction) {
991 Add(&instructions_, this, instruction);
992}
993
994void HBasicBlock::AddPhi(HPhi* phi) {
995 Add(&phis_, this, phi);
996}
997
David Brazdilc3d743f2015-04-22 13:40:50 +0100998void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
999 DCHECK(!cursor->IsPhi());
1000 DCHECK(!instruction->IsPhi());
1001 DCHECK_EQ(instruction->GetId(), -1);
1002 DCHECK_NE(cursor->GetId(), -1);
1003 DCHECK_EQ(cursor->GetBlock(), this);
1004 DCHECK(!instruction->IsControlFlow());
1005 instruction->SetBlock(this);
1006 instruction->SetId(GetGraph()->GetNextInstructionId());
1007 UpdateInputsUsers(instruction);
1008 instructions_.InsertInstructionBefore(instruction, cursor);
1009}
1010
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001011void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1012 DCHECK(!cursor->IsPhi());
1013 DCHECK(!instruction->IsPhi());
1014 DCHECK_EQ(instruction->GetId(), -1);
1015 DCHECK_NE(cursor->GetId(), -1);
1016 DCHECK_EQ(cursor->GetBlock(), this);
1017 DCHECK(!instruction->IsControlFlow());
1018 DCHECK(!cursor->IsControlFlow());
1019 instruction->SetBlock(this);
1020 instruction->SetId(GetGraph()->GetNextInstructionId());
1021 UpdateInputsUsers(instruction);
1022 instructions_.InsertInstructionAfter(instruction, cursor);
1023}
1024
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001025void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1026 DCHECK_EQ(phi->GetId(), -1);
1027 DCHECK_NE(cursor->GetId(), -1);
1028 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001029 phi->SetBlock(this);
1030 phi->SetId(GetGraph()->GetNextInstructionId());
1031 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001032 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001033}
1034
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001035static void Remove(HInstructionList* instruction_list,
1036 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001037 HInstruction* instruction,
1038 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001040 instruction->SetBlock(nullptr);
1041 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001042 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001043 DCHECK(instruction->GetUses().empty());
1044 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001045 RemoveAsUser(instruction);
1046 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001047}
1048
David Brazdil1abb4192015-02-17 18:33:36 +00001049void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001050 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001051 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001052}
1053
David Brazdil1abb4192015-02-17 18:33:36 +00001054void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1055 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001056}
1057
David Brazdilc7508e92015-04-27 13:28:57 +01001058void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1059 if (instruction->IsPhi()) {
1060 RemovePhi(instruction->AsPhi(), ensure_safety);
1061 } else {
1062 RemoveInstruction(instruction, ensure_safety);
1063 }
1064}
1065
Vladimir Marko69d310e2017-10-09 14:12:23 +01001066void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001067 for (size_t i = 0; i < locals.size(); i++) {
1068 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001069 SetRawEnvAt(i, instruction);
1070 if (instruction != nullptr) {
1071 instruction->AddEnvUseAt(this, i);
1072 }
1073 }
1074}
1075
David Brazdiled596192015-01-23 10:39:45 +00001076void HEnvironment::CopyFrom(HEnvironment* env) {
1077 for (size_t i = 0; i < env->Size(); i++) {
1078 HInstruction* instruction = env->GetInstructionAt(i);
1079 SetRawEnvAt(i, instruction);
1080 if (instruction != nullptr) {
1081 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001082 }
David Brazdiled596192015-01-23 10:39:45 +00001083 }
1084}
1085
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001086void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1087 HBasicBlock* loop_header) {
1088 DCHECK(loop_header->IsLoopHeader());
1089 for (size_t i = 0; i < env->Size(); i++) {
1090 HInstruction* instruction = env->GetInstructionAt(i);
1091 SetRawEnvAt(i, instruction);
1092 if (instruction == nullptr) {
1093 continue;
1094 }
1095 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1096 // At the end of the loop pre-header, the corresponding value for instruction
1097 // is the first input of the phi.
1098 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001099 SetRawEnvAt(i, initial);
1100 initial->AddEnvUseAt(this, i);
1101 } else {
1102 instruction->AddEnvUseAt(this, i);
1103 }
1104 }
1105}
1106
David Brazdil1abb4192015-02-17 18:33:36 +00001107void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001108 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1109 HInstruction* user = env_use.GetInstruction();
1110 auto before_env_use_node = env_use.GetBeforeUseNode();
1111 user->env_uses_.erase_after(before_env_use_node);
1112 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001113}
1114
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001115HInstruction::InstructionKind HInstruction::GetKind() const {
1116 return GetKindInternal();
1117}
1118
Calin Juravle77520bc2015-01-12 18:45:46 +00001119HInstruction* HInstruction::GetNextDisregardingMoves() const {
1120 HInstruction* next = GetNext();
1121 while (next != nullptr && next->IsParallelMove()) {
1122 next = next->GetNext();
1123 }
1124 return next;
1125}
1126
1127HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1128 HInstruction* previous = GetPrevious();
1129 while (previous != nullptr && previous->IsParallelMove()) {
1130 previous = previous->GetPrevious();
1131 }
1132 return previous;
1133}
1134
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001135void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001136 if (first_instruction_ == nullptr) {
1137 DCHECK(last_instruction_ == nullptr);
1138 first_instruction_ = last_instruction_ = instruction;
1139 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001140 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001141 last_instruction_->next_ = instruction;
1142 instruction->previous_ = last_instruction_;
1143 last_instruction_ = instruction;
1144 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001145}
1146
David Brazdilc3d743f2015-04-22 13:40:50 +01001147void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1148 DCHECK(Contains(cursor));
1149 if (cursor == first_instruction_) {
1150 cursor->previous_ = instruction;
1151 instruction->next_ = cursor;
1152 first_instruction_ = instruction;
1153 } else {
1154 instruction->previous_ = cursor->previous_;
1155 instruction->next_ = cursor;
1156 cursor->previous_ = instruction;
1157 instruction->previous_->next_ = instruction;
1158 }
1159}
1160
1161void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1162 DCHECK(Contains(cursor));
1163 if (cursor == last_instruction_) {
1164 cursor->next_ = instruction;
1165 instruction->previous_ = cursor;
1166 last_instruction_ = instruction;
1167 } else {
1168 instruction->next_ = cursor->next_;
1169 instruction->previous_ = cursor;
1170 cursor->next_ = instruction;
1171 instruction->next_->previous_ = instruction;
1172 }
1173}
1174
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001175void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1176 if (instruction->previous_ != nullptr) {
1177 instruction->previous_->next_ = instruction->next_;
1178 }
1179 if (instruction->next_ != nullptr) {
1180 instruction->next_->previous_ = instruction->previous_;
1181 }
1182 if (instruction == first_instruction_) {
1183 first_instruction_ = instruction->next_;
1184 }
1185 if (instruction == last_instruction_) {
1186 last_instruction_ = instruction->previous_;
1187 }
1188}
1189
Roland Levillain6b469232014-09-25 10:10:38 +01001190bool HInstructionList::Contains(HInstruction* instruction) const {
1191 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1192 if (it.Current() == instruction) {
1193 return true;
1194 }
1195 }
1196 return false;
1197}
1198
Roland Levillainccc07a92014-09-16 14:48:16 +01001199bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1200 const HInstruction* instruction2) const {
1201 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1202 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1203 if (it.Current() == instruction1) {
1204 return true;
1205 }
1206 if (it.Current() == instruction2) {
1207 return false;
1208 }
1209 }
1210 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1211 return true;
1212}
1213
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001214bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001215 if (other_instruction == this) {
1216 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001217 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001218 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001219 HBasicBlock* block = GetBlock();
1220 HBasicBlock* other_block = other_instruction->GetBlock();
1221 if (block != other_block) {
1222 return GetBlock()->Dominates(other_instruction->GetBlock());
1223 } else {
1224 // If both instructions are in the same block, ensure this
1225 // instruction comes before `other_instruction`.
1226 if (IsPhi()) {
1227 if (!other_instruction->IsPhi()) {
1228 // Phis appear before non phi-instructions so this instruction
1229 // dominates `other_instruction`.
1230 return true;
1231 } else {
1232 // There is no order among phis.
1233 LOG(FATAL) << "There is no dominance between phis of a same block.";
1234 return false;
1235 }
1236 } else {
1237 // `this` is not a phi.
1238 if (other_instruction->IsPhi()) {
1239 // Phis appear before non phi-instructions so this instruction
1240 // does not dominate `other_instruction`.
1241 return false;
1242 } else {
1243 // Check whether this instruction comes before
1244 // `other_instruction` in the instruction list.
1245 return block->GetInstructions().FoundBefore(this, other_instruction);
1246 }
1247 }
1248 }
1249}
1250
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001251void HInstruction::RemoveEnvironment() {
1252 RemoveEnvironmentUses(this);
1253 environment_ = nullptr;
1254}
1255
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001256void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001257 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001258 // Note: fixup_end remains valid across splice_after().
1259 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1260 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1261 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001262
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001263 // Note: env_fixup_end remains valid across splice_after().
1264 auto env_fixup_end =
1265 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1266 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1267 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001268
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001269 DCHECK(uses_.empty());
1270 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001271}
1272
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001273void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001274 const HUseList<HInstruction*>& uses = GetUses();
1275 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1276 HInstruction* user = it->GetUser();
1277 size_t index = it->GetIndex();
1278 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1279 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001280 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001281 user->ReplaceInput(replacement, index);
1282 }
1283 }
1284}
1285
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001286void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001287 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001288 if (input_use.GetInstruction() == replacement) {
1289 // Nothing to do.
1290 return;
1291 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001292 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001293 // Note: fixup_end remains valid across splice_after().
1294 auto fixup_end =
1295 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1296 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1297 input_use.GetInstruction()->uses_,
1298 before_use_node);
1299 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1300 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001301}
1302
Nicolas Geoffray39468442014-09-02 15:17:15 +01001303size_t HInstruction::EnvironmentSize() const {
1304 return HasEnvironment() ? environment_->Size() : 0;
1305}
1306
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001307void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001308 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001309 inputs_.push_back(HUserRecord<HInstruction*>(input));
1310 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001311}
1312
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001313void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1314 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1315 input->AddUseAt(this, index);
1316 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1317 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1318 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1319 inputs_[i].GetUseNode()->SetIndex(i);
1320 }
1321}
1322
1323void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001324 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001325 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001326 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1327 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1328 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1329 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001330 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001331}
1332
Igor Murashkind01745e2017-04-05 16:40:31 -07001333void HVariableInputSizeInstruction::RemoveAllInputs() {
1334 RemoveAsUserOfAllInputs();
1335 DCHECK(!HasNonEnvironmentUses());
1336
1337 inputs_.clear();
1338 DCHECK_EQ(0u, InputCount());
1339}
1340
Igor Murashkin6ef45672017-08-08 13:59:55 -07001341size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001342 DCHECK(instruction->GetBlock() != nullptr);
1343 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001344 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001345
Igor Murashkin6ef45672017-08-08 13:59:55 -07001346 // Return how many instructions were removed for statistic purposes.
1347 size_t remove_count = 0;
1348
Igor Murashkind01745e2017-04-05 16:40:31 -07001349 // Efficient implementation that simultaneously (in one pass):
1350 // * Scans the uses list for all constructor fences.
1351 // * Deletes that constructor fence from the uses list of `instruction`.
1352 // * Deletes `instruction` from the constructor fence's inputs.
1353 // * Deletes the constructor fence if it now has 0 inputs.
1354
1355 const HUseList<HInstruction*>& uses = instruction->GetUses();
1356 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1357 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1358 const HUseListNode<HInstruction*>& use_node = *it;
1359 HInstruction* const use_instruction = use_node.GetUser();
1360
1361 // Advance the iterator immediately once we fetch the use_node.
1362 // Warning: If the input is removed, the current iterator becomes invalid.
1363 ++it;
1364
1365 if (use_instruction->IsConstructorFence()) {
1366 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1367 size_t input_index = use_node.GetIndex();
1368
1369 // Process the candidate instruction for removal
1370 // from the graph.
1371
1372 // Constructor fence instructions are never
1373 // used by other instructions.
1374 //
1375 // If we wanted to make this more generic, it
1376 // could be a runtime if statement.
1377 DCHECK(!ctor_fence->HasUses());
1378
1379 // A constructor fence's return type is "kPrimVoid"
1380 // and therefore it can't have any environment uses.
1381 DCHECK(!ctor_fence->HasEnvironmentUses());
1382
1383 // Remove the inputs first, otherwise removing the instruction
1384 // will try to remove its uses while we are already removing uses
1385 // and this operation will fail.
1386 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1387
1388 // Removing the input will also remove the `use_node`.
1389 // (Do not look at `use_node` after this, it will be a dangling reference).
1390 ctor_fence->RemoveInputAt(input_index);
1391
1392 // Once all inputs are removed, the fence is considered dead and
1393 // is removed.
1394 if (ctor_fence->InputCount() == 0u) {
1395 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001396 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001397 }
1398 }
1399 }
1400
1401 if (kIsDebugBuild) {
1402 // Post-condition checks:
1403 // * None of the uses of `instruction` are a constructor fence.
1404 // * The `instruction` itself did not get removed from a block.
1405 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1406 CHECK(!use_node.GetUser()->IsConstructorFence());
1407 }
1408 CHECK(instruction->GetBlock() != nullptr);
1409 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001410
1411 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001412}
1413
Igor Murashkindd018df2017-08-09 10:38:31 -07001414void HConstructorFence::Merge(HConstructorFence* other) {
1415 // Do not delete yourself from the graph.
1416 DCHECK(this != other);
1417 // Don't try to merge with an instruction not associated with a block.
1418 DCHECK(other->GetBlock() != nullptr);
1419 // A constructor fence's return type is "kPrimVoid"
1420 // and therefore it cannot have any environment uses.
1421 DCHECK(!other->HasEnvironmentUses());
1422
1423 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1424 // Check if `haystack` has `needle` as any of its inputs.
1425 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1426 if (haystack->InputAt(input_count) == needle) {
1427 return true;
1428 }
1429 }
1430 return false;
1431 };
1432
1433 // Add any inputs from `other` into `this` if it wasn't already an input.
1434 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1435 HInstruction* other_input = other->InputAt(input_count);
1436 if (!has_input(this, other_input)) {
1437 AddInput(other_input);
1438 }
1439 }
1440
1441 other->GetBlock()->RemoveInstruction(other);
1442}
1443
1444HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001445 HInstruction* new_instance_inst = GetPrevious();
1446 // Check if the immediately preceding instruction is a new-instance/new-array.
1447 // Otherwise this fence is for protecting final fields.
1448 if (new_instance_inst != nullptr &&
1449 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001450 if (ignore_inputs) {
1451 // If inputs are ignored, simply check if the predecessor is
1452 // *any* HNewInstance/HNewArray.
1453 //
1454 // Inputs are normally only ignored for prepare_for_register_allocation,
1455 // at which point *any* prior HNewInstance/Array can be considered
1456 // associated.
1457 return new_instance_inst;
1458 } else {
1459 // Normal case: There must be exactly 1 input and the previous instruction
1460 // must be that input.
1461 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1462 return new_instance_inst;
1463 }
1464 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001465 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001466 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001467}
1468
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001469#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001470void H##name::Accept(HGraphVisitor* visitor) { \
1471 visitor->Visit##name(this); \
1472}
1473
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001474FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001475
1476#undef DEFINE_ACCEPT
1477
1478void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001479 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1480 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001481 if (block != nullptr) {
1482 VisitBasicBlock(block);
1483 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001484 }
1485}
1486
Roland Levillain633021e2014-10-01 14:12:25 +01001487void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001488 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1489 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001490 }
1491}
1492
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001493void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001494 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001495 it.Current()->Accept(this);
1496 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001497 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001498 it.Current()->Accept(this);
1499 }
1500}
1501
Mark Mendelle82549b2015-05-06 10:55:34 -04001502HConstant* HTypeConversion::TryStaticEvaluation() const {
1503 HGraph* graph = GetBlock()->GetGraph();
1504 if (GetInput()->IsIntConstant()) {
1505 int32_t value = GetInput()->AsIntConstant()->GetValue();
1506 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001507 case DataType::Type::kInt8:
1508 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1509 case DataType::Type::kUint8:
1510 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1511 case DataType::Type::kInt16:
1512 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1513 case DataType::Type::kUint16:
1514 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001515 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001516 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001518 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001520 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001521 default:
1522 return nullptr;
1523 }
1524 } else if (GetInput()->IsLongConstant()) {
1525 int64_t value = GetInput()->AsLongConstant()->GetValue();
1526 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001527 case DataType::Type::kInt8:
1528 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1529 case DataType::Type::kUint8:
1530 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1531 case DataType::Type::kInt16:
1532 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1533 case DataType::Type::kUint16:
1534 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001535 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001536 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001537 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001538 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001539 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001540 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001541 default:
1542 return nullptr;
1543 }
1544 } else if (GetInput()->IsFloatConstant()) {
1545 float value = GetInput()->AsFloatConstant()->GetValue();
1546 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001547 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001548 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001549 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001550 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001551 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001552 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001553 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1554 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001555 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001556 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001557 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001558 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001559 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001560 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001561 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1562 return graph->GetLongConstant(static_cast<int64_t>(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()->IsDoubleConstant()) {
1569 double value = GetInput()->AsDoubleConstant()->GetValue();
1570 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001571 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001572 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001573 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001574 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001575 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001576 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001577 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1578 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001580 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001581 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001582 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001583 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001584 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001585 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1586 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001588 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001589 default:
1590 return nullptr;
1591 }
1592 }
1593 return nullptr;
1594}
1595
Roland Levillain9240d6a2014-10-20 16:47:04 +01001596HConstant* HUnaryOperation::TryStaticEvaluation() const {
1597 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001598 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001599 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001600 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001601 } else if (kEnableFloatingPointStaticEvaluation) {
1602 if (GetInput()->IsFloatConstant()) {
1603 return Evaluate(GetInput()->AsFloatConstant());
1604 } else if (GetInput()->IsDoubleConstant()) {
1605 return Evaluate(GetInput()->AsDoubleConstant());
1606 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001607 }
1608 return nullptr;
1609}
1610
1611HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001612 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1613 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001614 } else if (GetLeft()->IsLongConstant()) {
1615 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001616 // The binop(long, int) case is only valid for shifts and rotations.
1617 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001618 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1619 } else if (GetRight()->IsLongConstant()) {
1620 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001621 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001622 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001623 // The binop(null, null) case is only valid for equal and not-equal conditions.
1624 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001625 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001626 } else if (kEnableFloatingPointStaticEvaluation) {
1627 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1628 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1629 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1630 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1631 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001632 }
1633 return nullptr;
1634}
Dave Allison20dfc792014-06-16 20:44:29 -07001635
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001636HConstant* HBinaryOperation::GetConstantRight() const {
1637 if (GetRight()->IsConstant()) {
1638 return GetRight()->AsConstant();
1639 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1640 return GetLeft()->AsConstant();
1641 } else {
1642 return nullptr;
1643 }
1644}
1645
1646// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001647// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001648HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1649 HInstruction* most_constant_right = GetConstantRight();
1650 if (most_constant_right == nullptr) {
1651 return nullptr;
1652 } else if (most_constant_right == GetLeft()) {
1653 return GetRight();
1654 } else {
1655 return GetLeft();
1656 }
1657}
1658
Roland Levillain31dd3d62016-02-16 12:21:02 +00001659std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1660 switch (rhs) {
1661 case ComparisonBias::kNoBias:
1662 return os << "no_bias";
1663 case ComparisonBias::kGtBias:
1664 return os << "gt_bias";
1665 case ComparisonBias::kLtBias:
1666 return os << "lt_bias";
1667 default:
1668 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1669 UNREACHABLE();
1670 }
1671}
1672
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001673bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1674 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001675}
1676
Vladimir Marko372f10e2016-05-17 16:30:10 +01001677bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001678 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001679 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001680 if (!InstructionDataEquals(other)) return false;
1681 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001682 HConstInputsRef inputs = GetInputs();
1683 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001684 if (inputs.size() != other_inputs.size()) return false;
1685 for (size_t i = 0; i != inputs.size(); ++i) {
1686 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001687 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001688
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001689 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001690 return true;
1691}
1692
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001693std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1694#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1695 switch (rhs) {
1696 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1697 default:
1698 os << "Unknown instruction kind " << static_cast<int>(rhs);
1699 break;
1700 }
1701#undef DECLARE_CASE
1702 return os;
1703}
1704
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001705void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1706 if (do_checks) {
1707 DCHECK(!IsPhi());
1708 DCHECK(!IsControlFlow());
1709 DCHECK(CanBeMoved() ||
1710 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1711 IsShouldDeoptimizeFlag());
1712 DCHECK(!cursor->IsPhi());
1713 }
David Brazdild6c205e2016-06-07 14:20:52 +01001714
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001715 next_->previous_ = previous_;
1716 if (previous_ != nullptr) {
1717 previous_->next_ = next_;
1718 }
1719 if (block_->instructions_.first_instruction_ == this) {
1720 block_->instructions_.first_instruction_ = next_;
1721 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001722 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001723
1724 previous_ = cursor->previous_;
1725 if (previous_ != nullptr) {
1726 previous_->next_ = this;
1727 }
1728 next_ = cursor;
1729 cursor->previous_ = this;
1730 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001731
1732 if (block_->instructions_.first_instruction_ == cursor) {
1733 block_->instructions_.first_instruction_ = this;
1734 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001735}
1736
Vladimir Markofb337ea2015-11-25 15:25:10 +00001737void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1738 DCHECK(!CanThrow());
1739 DCHECK(!HasSideEffects());
1740 DCHECK(!HasEnvironmentUses());
1741 DCHECK(HasNonEnvironmentUses());
1742 DCHECK(!IsPhi()); // Makes no sense for Phi.
1743 DCHECK_EQ(InputCount(), 0u);
1744
1745 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001746 auto uses_it = GetUses().begin();
1747 auto uses_end = GetUses().end();
1748 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1749 ++uses_it;
1750 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1751 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001752 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001753 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001754 // This instruction has uses in two or more blocks. Find the common dominator.
1755 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001756 for (; uses_it != uses_end; ++uses_it) {
1757 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001758 }
1759 target_block = finder.Get();
1760 DCHECK(target_block != nullptr);
1761 }
1762 // Move to the first dominator not in a loop.
1763 while (target_block->IsInLoop()) {
1764 target_block = target_block->GetDominator();
1765 DCHECK(target_block != nullptr);
1766 }
1767
1768 // Find insertion position.
1769 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001770 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1771 if (use.GetUser()->GetBlock() == target_block &&
1772 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1773 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001774 }
1775 }
1776 if (insert_pos == nullptr) {
1777 // No user in `target_block`, insert before the control flow instruction.
1778 insert_pos = target_block->GetLastInstruction();
1779 DCHECK(insert_pos->IsControlFlow());
1780 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1781 if (insert_pos->IsIf()) {
1782 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1783 if (if_input == insert_pos->GetPrevious()) {
1784 insert_pos = if_input;
1785 }
1786 }
1787 }
1788 MoveBefore(insert_pos);
1789}
1790
David Brazdilfc6a86a2015-06-26 10:33:45 +00001791HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001792 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001793 DCHECK_EQ(cursor->GetBlock(), this);
1794
Vladimir Markoca6fff82017-10-03 14:49:14 +01001795 HBasicBlock* new_block =
1796 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001797 new_block->instructions_.first_instruction_ = cursor;
1798 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1799 instructions_.last_instruction_ = cursor->previous_;
1800 if (cursor->previous_ == nullptr) {
1801 instructions_.first_instruction_ = nullptr;
1802 } else {
1803 cursor->previous_->next_ = nullptr;
1804 cursor->previous_ = nullptr;
1805 }
1806
1807 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001808 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001809
Vladimir Marko60584552015-09-03 13:35:12 +00001810 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001811 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001812 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001813 new_block->successors_.swap(successors_);
1814 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001815 AddSuccessor(new_block);
1816
David Brazdil56e1acc2015-06-30 15:41:36 +01001817 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001818 return new_block;
1819}
1820
David Brazdild7558da2015-09-22 13:04:14 +01001821HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001822 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001823 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1824
Vladimir Markoca6fff82017-10-03 14:49:14 +01001825 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001826
1827 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001828 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1829 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001830 new_block->predecessors_.swap(predecessors_);
1831 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001832 AddPredecessor(new_block);
1833
1834 GetGraph()->AddBlock(new_block);
1835 return new_block;
1836}
1837
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001838HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1839 DCHECK_EQ(cursor->GetBlock(), this);
1840
Vladimir Markoca6fff82017-10-03 14:49:14 +01001841 HBasicBlock* new_block =
1842 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001843 new_block->instructions_.first_instruction_ = cursor;
1844 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1845 instructions_.last_instruction_ = cursor->previous_;
1846 if (cursor->previous_ == nullptr) {
1847 instructions_.first_instruction_ = nullptr;
1848 } else {
1849 cursor->previous_->next_ = nullptr;
1850 cursor->previous_ = nullptr;
1851 }
1852
1853 new_block->instructions_.SetBlockOfInstructions(new_block);
1854
1855 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001856 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1857 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001858 new_block->successors_.swap(successors_);
1859 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001860
1861 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1862 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001863 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001864 new_block->dominated_blocks_.swap(dominated_blocks_);
1865 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001866 return new_block;
1867}
1868
1869HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001870 DCHECK(!cursor->IsControlFlow());
1871 DCHECK_NE(instructions_.last_instruction_, cursor);
1872 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001873
Vladimir Markoca6fff82017-10-03 14:49:14 +01001874 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001875 new_block->instructions_.first_instruction_ = cursor->GetNext();
1876 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1877 cursor->next_->previous_ = nullptr;
1878 cursor->next_ = nullptr;
1879 instructions_.last_instruction_ = cursor;
1880
1881 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001882 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001883 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001885 new_block->successors_.swap(successors_);
1886 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001887
Vladimir Marko60584552015-09-03 13:35:12 +00001888 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001889 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001890 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001891 new_block->dominated_blocks_.swap(dominated_blocks_);
1892 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 return new_block;
1894}
1895
David Brazdilec16f792015-08-19 15:04:01 +01001896const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001897 if (EndsWithTryBoundary()) {
1898 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1899 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001900 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001901 return try_boundary;
1902 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001903 DCHECK(IsTryBlock());
1904 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001905 return nullptr;
1906 }
David Brazdilec16f792015-08-19 15:04:01 +01001907 } else if (IsTryBlock()) {
1908 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001909 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001910 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001911 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001912}
1913
David Brazdild7558da2015-09-22 13:04:14 +01001914bool HBasicBlock::HasThrowingInstructions() const {
1915 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1916 if (it.Current()->CanThrow()) {
1917 return true;
1918 }
1919 }
1920 return false;
1921}
1922
David Brazdilfc6a86a2015-06-26 10:33:45 +00001923static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1924 return block.GetPhis().IsEmpty()
1925 && !block.GetInstructions().IsEmpty()
1926 && block.GetFirstInstruction() == block.GetLastInstruction();
1927}
1928
David Brazdil46e2a392015-03-16 17:31:52 +00001929bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001930 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1931}
1932
Mads Ager16e52892017-07-14 13:11:37 +02001933bool HBasicBlock::IsSingleReturn() const {
1934 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1935}
1936
Mingyao Yang46721ef2017-10-05 14:45:17 -07001937bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1938 return (GetFirstInstruction() == GetLastInstruction()) &&
1939 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1940}
1941
David Brazdilfc6a86a2015-06-26 10:33:45 +00001942bool HBasicBlock::IsSingleTryBoundary() const {
1943 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001944}
1945
David Brazdil8d5b8b22015-03-24 10:51:52 +00001946bool HBasicBlock::EndsWithControlFlowInstruction() const {
1947 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1948}
1949
David Brazdilb2bd1c52015-03-25 11:17:37 +00001950bool HBasicBlock::EndsWithIf() const {
1951 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1952}
1953
David Brazdilffee3d32015-07-06 11:48:53 +01001954bool HBasicBlock::EndsWithTryBoundary() const {
1955 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1956}
1957
David Brazdilb2bd1c52015-03-25 11:17:37 +00001958bool HBasicBlock::HasSinglePhi() const {
1959 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1960}
1961
David Brazdild26a4112015-11-10 11:07:31 +00001962ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1963 if (EndsWithTryBoundary()) {
1964 // The normal-flow successor of HTryBoundary is always stored at index zero.
1965 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1966 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1967 } else {
1968 // All successors of blocks not ending with TryBoundary are normal.
1969 return ArrayRef<HBasicBlock* const>(successors_);
1970 }
1971}
1972
1973ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1974 if (EndsWithTryBoundary()) {
1975 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1976 } else {
1977 // Blocks not ending with TryBoundary do not have exceptional successors.
1978 return ArrayRef<HBasicBlock* const>();
1979 }
1980}
1981
David Brazdilffee3d32015-07-06 11:48:53 +01001982bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001983 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1984 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1985
1986 size_t length = handlers1.size();
1987 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001988 return false;
1989 }
1990
David Brazdilb618ade2015-07-29 10:31:29 +01001991 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001992 for (size_t i = 0; i < length; ++i) {
1993 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001994 return false;
1995 }
1996 }
1997 return true;
1998}
1999
David Brazdil2d7352b2015-04-20 14:52:42 +01002000size_t HInstructionList::CountSize() const {
2001 size_t size = 0;
2002 HInstruction* current = first_instruction_;
2003 for (; current != nullptr; current = current->GetNext()) {
2004 size++;
2005 }
2006 return size;
2007}
2008
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002009void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2010 for (HInstruction* current = first_instruction_;
2011 current != nullptr;
2012 current = current->GetNext()) {
2013 current->SetBlock(block);
2014 }
2015}
2016
2017void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2018 DCHECK(Contains(cursor));
2019 if (!instruction_list.IsEmpty()) {
2020 if (cursor == last_instruction_) {
2021 last_instruction_ = instruction_list.last_instruction_;
2022 } else {
2023 cursor->next_->previous_ = instruction_list.last_instruction_;
2024 }
2025 instruction_list.last_instruction_->next_ = cursor->next_;
2026 cursor->next_ = instruction_list.first_instruction_;
2027 instruction_list.first_instruction_->previous_ = cursor;
2028 }
2029}
2030
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002031void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2032 DCHECK(Contains(cursor));
2033 if (!instruction_list.IsEmpty()) {
2034 if (cursor == first_instruction_) {
2035 first_instruction_ = instruction_list.first_instruction_;
2036 } else {
2037 cursor->previous_->next_ = instruction_list.first_instruction_;
2038 }
2039 instruction_list.last_instruction_->next_ = cursor;
2040 instruction_list.first_instruction_->previous_ = cursor->previous_;
2041 cursor->previous_ = instruction_list.last_instruction_;
2042 }
2043}
2044
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002045void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002046 if (IsEmpty()) {
2047 first_instruction_ = instruction_list.first_instruction_;
2048 last_instruction_ = instruction_list.last_instruction_;
2049 } else {
2050 AddAfter(last_instruction_, instruction_list);
2051 }
2052}
2053
David Brazdil04ff4e82015-12-10 13:54:52 +00002054// Should be called on instructions in a dead block in post order. This method
2055// assumes `insn` has been removed from all users with the exception of catch
2056// phis because of missing exceptional edges in the graph. It removes the
2057// instruction from catch phi uses, together with inputs of other catch phis in
2058// the catch block at the same index, as these must be dead too.
2059static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2060 DCHECK(!insn->HasEnvironmentUses());
2061 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002062 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2063 size_t use_index = use.GetIndex();
2064 HBasicBlock* user_block = use.GetUser()->GetBlock();
2065 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002066 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2067 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2068 }
2069 }
2070}
2071
David Brazdil2d7352b2015-04-20 14:52:42 +01002072void HBasicBlock::DisconnectAndDelete() {
2073 // Dominators must be removed after all the blocks they dominate. This way
2074 // a loop header is removed last, a requirement for correct loop information
2075 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002076 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002077
David Brazdil9eeebf62016-03-24 11:18:15 +00002078 // The following steps gradually remove the block from all its dependants in
2079 // post order (b/27683071).
2080
2081 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2082 // We need to do this before step (4) which destroys the predecessor list.
2083 HBasicBlock* loop_update_start = this;
2084 if (IsLoopHeader()) {
2085 HLoopInformation* loop_info = GetLoopInformation();
2086 // All other blocks in this loop should have been removed because the header
2087 // was their dominator.
2088 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2089 DCHECK(!loop_info->IsIrreducible());
2090 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2091 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2092 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002093 }
2094
David Brazdil9eeebf62016-03-24 11:18:15 +00002095 // (2) Disconnect the block from its successors and update their phis.
2096 for (HBasicBlock* successor : successors_) {
2097 // Delete this block from the list of predecessors.
2098 size_t this_index = successor->GetPredecessorIndexOf(this);
2099 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2100
2101 // Check that `successor` has other predecessors, otherwise `this` is the
2102 // dominator of `successor` which violates the order DCHECKed at the top.
2103 DCHECK(!successor->predecessors_.empty());
2104
2105 // Remove this block's entries in the successor's phis. Skip exceptional
2106 // successors because catch phi inputs do not correspond to predecessor
2107 // blocks but throwing instructions. The inputs of the catch phis will be
2108 // updated in step (3).
2109 if (!successor->IsCatchBlock()) {
2110 if (successor->predecessors_.size() == 1u) {
2111 // The successor has just one predecessor left. Replace phis with the only
2112 // remaining input.
2113 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2114 HPhi* phi = phi_it.Current()->AsPhi();
2115 phi->ReplaceWith(phi->InputAt(1 - this_index));
2116 successor->RemovePhi(phi);
2117 }
2118 } else {
2119 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2120 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2121 }
2122 }
2123 }
2124 }
2125 successors_.clear();
2126
2127 // (3) Remove instructions and phis. Instructions should have no remaining uses
2128 // except in catch phis. If an instruction is used by a catch phi at `index`,
2129 // remove `index`-th input of all phis in the catch block since they are
2130 // guaranteed dead. Note that we may miss dead inputs this way but the
2131 // graph will always remain consistent.
2132 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2133 HInstruction* insn = it.Current();
2134 RemoveUsesOfDeadInstruction(insn);
2135 RemoveInstruction(insn);
2136 }
2137 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2138 HPhi* insn = it.Current()->AsPhi();
2139 RemoveUsesOfDeadInstruction(insn);
2140 RemovePhi(insn);
2141 }
2142
2143 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002144 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002145 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002146 // We should not see any back edges as they would have been removed by step (3).
2147 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2148
David Brazdil2d7352b2015-04-20 14:52:42 +01002149 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002150 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2151 // This block is the only normal-flow successor of the TryBoundary which
2152 // makes `predecessor` dead. Since DCE removes blocks in post order,
2153 // exception handlers of this TryBoundary were already visited and any
2154 // remaining handlers therefore must be live. We remove `predecessor` from
2155 // their list of predecessors.
2156 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2157 while (predecessor->GetSuccessors().size() > 1) {
2158 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2159 DCHECK(handler->IsCatchBlock());
2160 predecessor->RemoveSuccessor(handler);
2161 handler->RemovePredecessor(predecessor);
2162 }
2163 }
2164
David Brazdil2d7352b2015-04-20 14:52:42 +01002165 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002166 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2167 if (num_pred_successors == 1u) {
2168 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002169 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2170 // successor. Replace those with a HGoto.
2171 DCHECK(last_instruction->IsIf() ||
2172 last_instruction->IsPackedSwitch() ||
2173 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002174 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002175 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002176 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002177 // The predecessor has no remaining successors and therefore must be dead.
2178 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002179 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002180 predecessor->RemoveInstruction(last_instruction);
2181 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002182 // There are multiple successors left. The removed block might be a successor
2183 // of a PackedSwitch which will be completely removed (perhaps replaced with
2184 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2185 // case, leave `last_instruction` as is for now.
2186 DCHECK(last_instruction->IsPackedSwitch() ||
2187 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002188 }
David Brazdil46e2a392015-03-16 17:31:52 +00002189 }
Vladimir Marko60584552015-09-03 13:35:12 +00002190 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002191
David Brazdil9eeebf62016-03-24 11:18:15 +00002192 // (5) Remove the block from all loops it is included in. Skip the inner-most
2193 // loop if this is the loop header (see definition of `loop_update_start`)
2194 // because the loop header's predecessor list has been destroyed in step (4).
2195 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2196 HLoopInformation* loop_info = it.Current();
2197 loop_info->Remove(this);
2198 if (loop_info->IsBackEdge(*this)) {
2199 // If this was the last back edge of the loop, we deliberately leave the
2200 // loop in an inconsistent state and will fail GraphChecker unless the
2201 // entire loop is removed during the pass.
2202 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002203 }
2204 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002205
David Brazdil9eeebf62016-03-24 11:18:15 +00002206 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002207 dominator_->RemoveDominatedBlock(this);
2208 SetDominator(nullptr);
2209
David Brazdil9eeebf62016-03-24 11:18:15 +00002210 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002211 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002212 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002213}
2214
Aart Bik6b69e0a2017-01-11 10:20:43 -08002215void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2216 DCHECK(EndsWithControlFlowInstruction());
2217 RemoveInstruction(GetLastInstruction());
2218 instructions_.Add(other->GetInstructions());
2219 other->instructions_.SetBlockOfInstructions(this);
2220 other->instructions_.Clear();
2221}
2222
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002223void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002224 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002225 DCHECK(ContainsElement(dominated_blocks_, other));
2226 DCHECK_EQ(GetSingleSuccessor(), other);
2227 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002228 DCHECK(other->GetPhis().IsEmpty());
2229
David Brazdil2d7352b2015-04-20 14:52:42 +01002230 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002231 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002232
David Brazdil2d7352b2015-04-20 14:52:42 +01002233 // Remove `other` from the loops it is included in.
2234 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2235 HLoopInformation* loop_info = it.Current();
2236 loop_info->Remove(other);
2237 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002238 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002239 }
2240 }
2241
2242 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002243 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002244 for (HBasicBlock* successor : other->GetSuccessors()) {
2245 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002246 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002247 successors_.swap(other->successors_);
2248 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002249
David Brazdil2d7352b2015-04-20 14:52:42 +01002250 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002251 RemoveDominatedBlock(other);
2252 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002253 dominated->SetDominator(this);
2254 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002255 dominated_blocks_.insert(
2256 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002257 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002258 other->dominator_ = nullptr;
2259
2260 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002261 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002262
2263 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002264 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002265 other->SetGraph(nullptr);
2266}
2267
2268void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2269 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002270 DCHECK(GetDominatedBlocks().empty());
2271 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002272 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002273 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002274 DCHECK(other->GetPhis().IsEmpty());
2275 DCHECK(!other->IsInLoop());
2276
2277 // Move instructions from `other` to `this`.
2278 instructions_.Add(other->GetInstructions());
2279 other->instructions_.SetBlockOfInstructions(this);
2280
2281 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002282 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002283 for (HBasicBlock* successor : other->GetSuccessors()) {
2284 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002285 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002286 successors_.swap(other->successors_);
2287 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002288
2289 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002290 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002291 dominated->SetDominator(this);
2292 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002293 dominated_blocks_.insert(
2294 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002295 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002296 other->dominator_ = nullptr;
2297 other->graph_ = nullptr;
2298}
2299
2300void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002301 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002302 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002303 predecessor->ReplaceSuccessor(this, other);
2304 }
Vladimir Marko60584552015-09-03 13:35:12 +00002305 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002306 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002307 successor->ReplacePredecessor(this, other);
2308 }
Vladimir Marko60584552015-09-03 13:35:12 +00002309 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2310 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002311 }
2312 GetDominator()->ReplaceDominatedBlock(this, other);
2313 other->SetDominator(GetDominator());
2314 dominator_ = nullptr;
2315 graph_ = nullptr;
2316}
2317
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002318void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002319 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002320 DCHECK(block->GetSuccessors().empty());
2321 DCHECK(block->GetPredecessors().empty());
2322 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002323 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002324 DCHECK(block->GetInstructions().IsEmpty());
2325 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002326
David Brazdilc7af85d2015-05-26 12:05:55 +01002327 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002328 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002329 }
2330
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002331 RemoveElement(reverse_post_order_, block);
2332 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002333 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002334}
2335
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002336void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2337 HBasicBlock* reference,
2338 bool replace_if_back_edge) {
2339 if (block->IsLoopHeader()) {
2340 // Clear the information of which blocks are contained in that loop. Since the
2341 // information is stored as a bit vector based on block ids, we have to update
2342 // it, as those block ids were specific to the callee graph and we are now adding
2343 // these blocks to the caller graph.
2344 block->GetLoopInformation()->ClearAllBlocks();
2345 }
2346
2347 // If not already in a loop, update the loop information.
2348 if (!block->IsInLoop()) {
2349 block->SetLoopInformation(reference->GetLoopInformation());
2350 }
2351
2352 // If the block is in a loop, update all its outward loops.
2353 HLoopInformation* loop_info = block->GetLoopInformation();
2354 if (loop_info != nullptr) {
2355 for (HLoopInformationOutwardIterator loop_it(*block);
2356 !loop_it.Done();
2357 loop_it.Advance()) {
2358 loop_it.Current()->Add(block);
2359 }
2360 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2361 loop_info->ReplaceBackEdge(reference, block);
2362 }
2363 }
2364
2365 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2366 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2367 ? reference->GetTryCatchInformation()
2368 : nullptr;
2369 block->SetTryCatchInformation(try_catch_info);
2370}
2371
Calin Juravle2e768302015-07-28 14:41:11 +00002372HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002373 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002374 // Update the environments in this graph to have the invoke's environment
2375 // as parent.
2376 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002377 // Skip the entry block, we do not need to update the entry's suspend check.
2378 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002379 for (HInstructionIterator instr_it(block->GetInstructions());
2380 !instr_it.Done();
2381 instr_it.Advance()) {
2382 HInstruction* current = instr_it.Current();
2383 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002384 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002385 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002386 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002387 }
2388 }
2389 }
2390 }
2391 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002392
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002393 if (HasBoundsChecks()) {
2394 outer_graph->SetHasBoundsChecks(true);
2395 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002396 if (HasLoops()) {
2397 outer_graph->SetHasLoops(true);
2398 }
2399 if (HasIrreducibleLoops()) {
2400 outer_graph->SetHasIrreducibleLoops(true);
2401 }
2402 if (HasTryCatch()) {
2403 outer_graph->SetHasTryCatch(true);
2404 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002405 if (HasSIMD()) {
2406 outer_graph->SetHasSIMD(true);
2407 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002408
Calin Juravle2e768302015-07-28 14:41:11 +00002409 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002410 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002411 // Inliner already made sure we don't inline methods that always throw.
2412 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002413 // Simple case of an entry block, a body block, and an exit block.
2414 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002415 HBasicBlock* body = GetBlocks()[1];
2416 DCHECK(GetBlocks()[0]->IsEntryBlock());
2417 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002418 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002419 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002420 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002421
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002422 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2423 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002424 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002425
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002426 // Replace the invoke with the return value of the inlined graph.
2427 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002428 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002429 } else {
2430 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002431 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002432
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002433 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002434 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002435 // Need to inline multiple blocks. We split `invoke`'s block
2436 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002437 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002438 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002439 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002440 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002441 // Note that we split before the invoke only to simplify polymorphic inlining.
2442 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002443
Vladimir Markoec7802a2015-10-01 20:57:57 +01002444 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002445 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002446 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002447 exit_block_->ReplaceWith(to);
2448
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002449 // Update the meta information surrounding blocks:
2450 // (1) the graph they are now in,
2451 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002452 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002453 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002454 // Note that we do not need to update catch phi inputs because they
2455 // correspond to the register file of the outer method which the inlinee
2456 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002457
2458 // We don't add the entry block, the exit block, and the first block, which
2459 // has been merged with `at`.
2460 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2461
2462 // We add the `to` block.
2463 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002464 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002465 + kNumberOfNewBlocksInCaller;
2466
2467 // Find the location of `at` in the outer graph's reverse post order. The new
2468 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002469 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002470 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2471
David Brazdil95177982015-10-30 12:56:58 -05002472 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2473 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002474 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002475 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002476 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002477 DCHECK(current->GetGraph() == this);
2478 current->SetGraph(outer_graph);
2479 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002480 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002481 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002482 }
2483 }
2484
David Brazdil95177982015-10-30 12:56:58 -05002485 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002486 to->SetGraph(outer_graph);
2487 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002488 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002489 // Only `to` can become a back edge, as the inlined blocks
2490 // are predecessors of `to`.
2491 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002492
David Brazdil3f523062016-02-29 16:53:33 +00002493 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002494 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2495 // to now get the outer graph exit block as successor. Note that the inliner
2496 // currently doesn't support inlining methods with try/catch.
2497 HPhi* return_value_phi = nullptr;
2498 bool rerun_dominance = false;
2499 bool rerun_loop_analysis = false;
2500 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2501 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002502 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002503 if (last->IsThrow()) {
2504 DCHECK(!at->IsTryBlock());
2505 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2506 --pred;
2507 // We need to re-run dominance information, as the exit block now has
2508 // a new dominator.
2509 rerun_dominance = true;
2510 if (predecessor->GetLoopInformation() != nullptr) {
2511 // The exit block and blocks post dominated by the exit block do not belong
2512 // to any loop. Because we do not compute the post dominators, we need to re-run
2513 // loop analysis to get the loop information correct.
2514 rerun_loop_analysis = true;
2515 }
2516 } else {
2517 if (last->IsReturnVoid()) {
2518 DCHECK(return_value == nullptr);
2519 DCHECK(return_value_phi == nullptr);
2520 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002521 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002522 if (return_value_phi != nullptr) {
2523 return_value_phi->AddInput(last->InputAt(0));
2524 } else if (return_value == nullptr) {
2525 return_value = last->InputAt(0);
2526 } else {
2527 // There will be multiple returns.
2528 return_value_phi = new (allocator) HPhi(
2529 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2530 to->AddPhi(return_value_phi);
2531 return_value_phi->AddInput(return_value);
2532 return_value_phi->AddInput(last->InputAt(0));
2533 return_value = return_value_phi;
2534 }
David Brazdil3f523062016-02-29 16:53:33 +00002535 }
2536 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2537 predecessor->RemoveInstruction(last);
2538 }
2539 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002540 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002541 DCHECK(!outer_graph->HasIrreducibleLoops())
2542 << "Recomputing loop information in graphs with irreducible loops "
2543 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002544 outer_graph->ClearLoopInformation();
2545 outer_graph->ClearDominanceInformation();
2546 outer_graph->BuildDominatorTree();
2547 } else if (rerun_dominance) {
2548 outer_graph->ClearDominanceInformation();
2549 outer_graph->ComputeDominanceInformation();
2550 }
David Brazdil3f523062016-02-29 16:53:33 +00002551 }
David Brazdil05144f42015-04-16 15:18:00 +01002552
2553 // Walk over the entry block and:
2554 // - Move constants from the entry block to the outer_graph's entry block,
2555 // - Replace HParameterValue instructions with their real value.
2556 // - Remove suspend checks, that hold an environment.
2557 // We must do this after the other blocks have been inlined, otherwise ids of
2558 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002559 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002560 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2561 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002562 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002563 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002564 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002565 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002566 replacement = outer_graph->GetIntConstant(
2567 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002568 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002569 replacement = outer_graph->GetLongConstant(
2570 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002571 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002572 replacement = outer_graph->GetFloatConstant(
2573 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002574 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002575 replacement = outer_graph->GetDoubleConstant(
2576 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002577 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002578 if (kIsDebugBuild
2579 && invoke->IsInvokeStaticOrDirect()
2580 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2581 // Ensure we do not use the last input of `invoke`, as it
2582 // contains a clinit check which is not an actual argument.
2583 size_t last_input_index = invoke->InputCount() - 1;
2584 DCHECK(parameter_index != last_input_index);
2585 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002586 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002587 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002588 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002589 } else {
2590 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2591 entry_block_->RemoveInstruction(current);
2592 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002593 if (replacement != nullptr) {
2594 current->ReplaceWith(replacement);
2595 // If the current is the return value then we need to update the latter.
2596 if (current == return_value) {
2597 DCHECK_EQ(entry_block_, return_value->GetBlock());
2598 return_value = replacement;
2599 }
2600 }
2601 }
2602
Calin Juravle2e768302015-07-28 14:41:11 +00002603 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002604}
2605
Mingyao Yang3584bce2015-05-19 16:01:59 -07002606/*
2607 * Loop will be transformed to:
2608 * old_pre_header
2609 * |
2610 * if_block
2611 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002612 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002613 * \ /
2614 * new_pre_header
2615 * |
2616 * header
2617 */
2618void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2619 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002620 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002621
Aart Bik3fc7f352015-11-20 22:03:03 -08002622 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002623 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2624 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2625 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2626 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002627 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002628 AddBlock(true_block);
2629 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002630 AddBlock(new_pre_header);
2631
Aart Bik3fc7f352015-11-20 22:03:03 -08002632 header->ReplacePredecessor(old_pre_header, new_pre_header);
2633 old_pre_header->successors_.clear();
2634 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002635
Aart Bik3fc7f352015-11-20 22:03:03 -08002636 old_pre_header->AddSuccessor(if_block);
2637 if_block->AddSuccessor(true_block); // True successor
2638 if_block->AddSuccessor(false_block); // False successor
2639 true_block->AddSuccessor(new_pre_header);
2640 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002641
Aart Bik3fc7f352015-11-20 22:03:03 -08002642 old_pre_header->dominated_blocks_.push_back(if_block);
2643 if_block->SetDominator(old_pre_header);
2644 if_block->dominated_blocks_.push_back(true_block);
2645 true_block->SetDominator(if_block);
2646 if_block->dominated_blocks_.push_back(false_block);
2647 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002648 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002649 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002650 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002651 header->SetDominator(new_pre_header);
2652
Aart Bik3fc7f352015-11-20 22:03:03 -08002653 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002654 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002655 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002656 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002657 reverse_post_order_[index_of_header++] = true_block;
2658 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002659 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002660
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002661 // The pre_header can never be a back edge of a loop.
2662 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2663 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2664 UpdateLoopAndTryInformationOfNewBlock(
2665 if_block, old_pre_header, /* replace_if_back_edge */ false);
2666 UpdateLoopAndTryInformationOfNewBlock(
2667 true_block, old_pre_header, /* replace_if_back_edge */ false);
2668 UpdateLoopAndTryInformationOfNewBlock(
2669 false_block, old_pre_header, /* replace_if_back_edge */ false);
2670 UpdateLoopAndTryInformationOfNewBlock(
2671 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002672}
2673
Aart Bikf8f5a162017-02-06 15:35:29 -08002674HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2675 HBasicBlock* body,
2676 HBasicBlock* exit) {
2677 DCHECK(header->IsLoopHeader());
2678 HLoopInformation* loop = header->GetLoopInformation();
2679
2680 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002681 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2682 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2683 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002684 AddBlock(new_pre_header);
2685 AddBlock(new_header);
2686 AddBlock(new_body);
2687
2688 // Set up control flow.
2689 header->ReplaceSuccessor(exit, new_pre_header);
2690 new_pre_header->AddSuccessor(new_header);
2691 new_header->AddSuccessor(exit);
2692 new_header->AddSuccessor(new_body);
2693 new_body->AddSuccessor(new_header);
2694
2695 // Set up dominators.
2696 header->ReplaceDominatedBlock(exit, new_pre_header);
2697 new_pre_header->SetDominator(header);
2698 new_pre_header->dominated_blocks_.push_back(new_header);
2699 new_header->SetDominator(new_pre_header);
2700 new_header->dominated_blocks_.push_back(new_body);
2701 new_body->SetDominator(new_header);
2702 new_header->dominated_blocks_.push_back(exit);
2703 exit->SetDominator(new_header);
2704
2705 // Fix reverse post order.
2706 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2707 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2708 reverse_post_order_[++index_of_header] = new_pre_header;
2709 reverse_post_order_[++index_of_header] = new_header;
2710 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2711 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2712 reverse_post_order_[index_of_body] = new_body;
2713
Aart Bikb07d1bc2017-04-05 10:03:15 -07002714 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002715 new_pre_header->AddInstruction(new (allocator_) HGoto());
2716 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002717 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002718 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002719 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2720 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002721
2722 // Update loop information.
2723 new_header->AddBackEdge(new_body);
2724 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2725 new_header->GetLoopInformation()->Populate();
2726 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2727 HLoopInformationOutwardIterator it(*new_header);
2728 for (it.Advance(); !it.Done(); it.Advance()) {
2729 it.Current()->Add(new_pre_header);
2730 it.Current()->Add(new_header);
2731 it.Current()->Add(new_body);
2732 }
2733 return new_pre_header;
2734}
2735
David Brazdilf5552582015-12-27 13:36:12 +00002736static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002737 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002738 if (rti.IsValid()) {
2739 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2740 << " upper_bound_rti: " << upper_bound_rti
2741 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002742 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2743 << " upper_bound_rti: " << upper_bound_rti
2744 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002745 }
2746}
2747
Calin Juravle2e768302015-07-28 14:41:11 +00002748void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2749 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002750 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002751 ScopedObjectAccess soa(Thread::Current());
2752 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2753 if (IsBoundType()) {
2754 // Having the test here spares us from making the method virtual just for
2755 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002756 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002757 }
2758 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002759 reference_type_handle_ = rti.GetTypeHandle();
2760 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002761}
2762
David Brazdilf5552582015-12-27 13:36:12 +00002763void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2764 if (kIsDebugBuild) {
2765 ScopedObjectAccess soa(Thread::Current());
2766 DCHECK(upper_bound.IsValid());
2767 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2768 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2769 }
2770 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002771 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002772}
2773
Vladimir Markoa1de9182016-02-25 11:37:38 +00002774ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002775 if (kIsDebugBuild) {
2776 ScopedObjectAccess soa(Thread::Current());
2777 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002778 if (!is_exact) {
2779 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2780 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2781 }
Calin Juravle2e768302015-07-28 14:41:11 +00002782 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002783 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002784}
2785
Calin Juravleacf735c2015-02-12 15:25:22 +00002786std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2787 ScopedObjectAccess soa(Thread::Current());
2788 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002789 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002790 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002791 << " is_exact=" << rhs.IsExact()
2792 << " ]";
2793 return os;
2794}
2795
Mark Mendellc4701932015-04-10 13:18:51 -04002796bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2797 // For now, assume that instructions in different blocks may use the
2798 // environment.
2799 // TODO: Use the control flow to decide if this is true.
2800 if (GetBlock() != other->GetBlock()) {
2801 return true;
2802 }
2803
2804 // We know that we are in the same block. Walk from 'this' to 'other',
2805 // checking to see if there is any instruction with an environment.
2806 HInstruction* current = this;
2807 for (; current != other && current != nullptr; current = current->GetNext()) {
2808 // This is a conservative check, as the instruction result may not be in
2809 // the referenced environment.
2810 if (current->HasEnvironment()) {
2811 return true;
2812 }
2813 }
2814
2815 // We should have been called with 'this' before 'other' in the block.
2816 // Just confirm this.
2817 DCHECK(current != nullptr);
2818 return false;
2819}
2820
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002821void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002822 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2823 IntrinsicSideEffects side_effects,
2824 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002825 intrinsic_ = intrinsic;
2826 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002827
Aart Bik5d75afe2015-12-14 11:57:01 -08002828 // Adjust method's side effects from intrinsic table.
2829 switch (side_effects) {
2830 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2831 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2832 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2833 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2834 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002835
2836 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2837 opt.SetDoesNotNeedDexCache();
2838 opt.SetDoesNotNeedEnvironment();
2839 } else {
2840 // If we need an environment, that means there will be a call, which can trigger GC.
2841 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2842 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002843 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002844 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002845}
2846
David Brazdil6de19382016-01-08 17:37:10 +00002847bool HNewInstance::IsStringAlloc() const {
2848 ScopedObjectAccess soa(Thread::Current());
2849 return GetReferenceTypeInfo().IsStringClass();
2850}
2851
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002852bool HInvoke::NeedsEnvironment() const {
2853 if (!IsIntrinsic()) {
2854 return true;
2855 }
2856 IntrinsicOptimizations opt(*this);
2857 return !opt.GetDoesNotNeedEnvironment();
2858}
2859
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002860const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2861 ArtMethod* caller = GetEnvironment()->GetMethod();
2862 ScopedObjectAccess soa(Thread::Current());
2863 // `caller` is null for a top-level graph representing a method whose declaring
2864 // class was not resolved.
2865 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2866}
2867
Vladimir Markodc151b22015-10-15 18:02:30 +01002868bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002869 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002870 return false;
2871 }
2872 if (!IsIntrinsic()) {
2873 return true;
2874 }
2875 IntrinsicOptimizations opt(*this);
2876 return !opt.GetDoesNotNeedDexCache();
2877}
2878
Vladimir Markof64242a2015-12-01 14:58:23 +00002879std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2880 switch (rhs) {
2881 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002882 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002883 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002884 return os << "Recursive";
2885 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2886 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002887 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002888 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002889 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2890 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002891 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2892 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002893 default:
2894 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2895 UNREACHABLE();
2896 }
2897}
2898
Vladimir Markofbb184a2015-11-13 14:47:00 +00002899std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2900 switch (rhs) {
2901 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2902 return os << "explicit";
2903 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2904 return os << "implicit";
2905 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2906 return os << "none";
2907 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002908 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2909 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002910 }
2911}
2912
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002913bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2914 const HLoadClass* other_load_class = other->AsLoadClass();
2915 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2916 // names rather than type indexes. However, we shall also have to re-think the hash code.
2917 if (type_index_ != other_load_class->type_index_ ||
2918 GetPackedFields() != other_load_class->GetPackedFields()) {
2919 return false;
2920 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002921 switch (GetLoadKind()) {
2922 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002923 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002924 case LoadKind::kJitTableAddress: {
2925 ScopedObjectAccess soa(Thread::Current());
2926 return GetClass().Get() == other_load_class->GetClass().Get();
2927 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002928 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002929 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002930 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002931 }
2932}
2933
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002934std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2935 switch (rhs) {
2936 case HLoadClass::LoadKind::kReferrersClass:
2937 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002938 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2939 return os << "BootImageLinkTimePcRelative";
2940 case HLoadClass::LoadKind::kBootImageAddress:
2941 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002942 case HLoadClass::LoadKind::kBootImageClassTable:
2943 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002944 case HLoadClass::LoadKind::kBssEntry:
2945 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002946 case HLoadClass::LoadKind::kJitTableAddress:
2947 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002948 case HLoadClass::LoadKind::kRuntimeCall:
2949 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002950 default:
2951 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2952 UNREACHABLE();
2953 }
2954}
2955
Vladimir Marko372f10e2016-05-17 16:30:10 +01002956bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2957 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002958 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2959 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002960 if (string_index_ != other_load_string->string_index_ ||
2961 GetPackedFields() != other_load_string->GetPackedFields()) {
2962 return false;
2963 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002964 switch (GetLoadKind()) {
2965 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002966 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002967 case LoadKind::kJitTableAddress: {
2968 ScopedObjectAccess soa(Thread::Current());
2969 return GetString().Get() == other_load_string->GetString().Get();
2970 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002971 default:
2972 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002973 }
2974}
2975
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002976std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2977 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002978 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2979 return os << "BootImageLinkTimePcRelative";
2980 case HLoadString::LoadKind::kBootImageAddress:
2981 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002982 case HLoadString::LoadKind::kBootImageInternTable:
2983 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002984 case HLoadString::LoadKind::kBssEntry:
2985 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002986 case HLoadString::LoadKind::kJitTableAddress:
2987 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002988 case HLoadString::LoadKind::kRuntimeCall:
2989 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002990 default:
2991 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2992 UNREACHABLE();
2993 }
2994}
2995
Mark Mendellc4701932015-04-10 13:18:51 -04002996void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002997 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2998 HEnvironment* user = use.GetUser();
2999 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003000 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003001 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003002}
3003
Artem Serovcced8ba2017-07-19 18:18:09 +01003004HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3005 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3006 HBasicBlock* block = instr->GetBlock();
3007
3008 if (instr->IsPhi()) {
3009 HPhi* phi = instr->AsPhi();
3010 DCHECK(!phi->HasEnvironment());
3011 HPhi* phi_clone = clone->AsPhi();
3012 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3013 } else {
3014 block->ReplaceAndRemoveInstructionWith(instr, clone);
3015 if (instr->HasEnvironment()) {
3016 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3017 HLoopInformation* loop_info = block->GetLoopInformation();
3018 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3019 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3020 }
3021 }
3022 }
3023 return clone;
3024}
3025
Roland Levillainc9b21f82016-03-23 16:36:59 +00003026// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003027HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003028 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003029
3030 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003031 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003032 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3033 HInstruction* lhs = cond->InputAt(0);
3034 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003035 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003036 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3037 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3038 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3039 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3040 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3041 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3042 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3043 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3044 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3045 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3046 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003047 default:
3048 LOG(FATAL) << "Unexpected condition";
3049 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003050 }
3051 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3052 return replacement;
3053 } else if (cond->IsIntConstant()) {
3054 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003055 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003056 return GetIntConstant(1);
3057 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003058 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003059 return GetIntConstant(0);
3060 }
3061 } else {
3062 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3063 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3064 return replacement;
3065 }
3066}
3067
Roland Levillainc9285912015-12-18 10:38:42 +00003068std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3069 os << "["
3070 << " source=" << rhs.GetSource()
3071 << " destination=" << rhs.GetDestination()
3072 << " type=" << rhs.GetType()
3073 << " instruction=";
3074 if (rhs.GetInstruction() != nullptr) {
3075 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3076 } else {
3077 os << "null";
3078 }
3079 os << " ]";
3080 return os;
3081}
3082
Roland Levillain86503782016-02-11 19:07:30 +00003083std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3084 switch (rhs) {
3085 case TypeCheckKind::kUnresolvedCheck:
3086 return os << "unresolved_check";
3087 case TypeCheckKind::kExactCheck:
3088 return os << "exact_check";
3089 case TypeCheckKind::kClassHierarchyCheck:
3090 return os << "class_hierarchy_check";
3091 case TypeCheckKind::kAbstractClassCheck:
3092 return os << "abstract_class_check";
3093 case TypeCheckKind::kInterfaceCheck:
3094 return os << "interface_check";
3095 case TypeCheckKind::kArrayObjectCheck:
3096 return os << "array_object_check";
3097 case TypeCheckKind::kArrayCheck:
3098 return os << "array_check";
3099 default:
3100 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3101 UNREACHABLE();
3102 }
3103}
3104
Andreas Gampe26de38b2016-07-27 17:53:11 -07003105std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
3106 switch (kind) {
3107 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003108 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003109 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003110 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003111 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003112 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003113 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003114 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003115 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003116 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003117
3118 default:
3119 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3120 UNREACHABLE();
3121 }
3122}
3123
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003124} // namespace art