blob: 1a537ca47eb6d639a5c41116e764c2ed979a265e [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markoca6fff82017-10-03 14:49:14 +010059 ArenaBitVector visiting(allocator_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
Vladimir Markoca6fff82017-10-03 14:49:14 +010063 allocator_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Markoca6fff82017-10-03 14:49:14 +010065 ArenaVector<HBasicBlock*> worklist(allocator_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Artem Serov21c7e6f2017-07-27 16:04:42 +010093// Remove the environment use records of the instruction for users.
94void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010095 for (HEnvironment* environment = instruction->GetEnvironment();
96 environment != nullptr;
97 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000099 if (environment->GetInstructionAt(i) != nullptr) {
100 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000101 }
102 }
103 }
104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Return whether the instruction has an environment and it's used by others.
107bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
112 HInstruction* user = environment->GetInstructionAt(i);
113 if (user != nullptr) {
114 return true;
115 }
116 }
117 }
118 return false;
119}
120
121// Reset environment records of the instruction itself.
122void ResetEnvironmentInputRecords(HInstruction* instruction) {
123 for (HEnvironment* environment = instruction->GetEnvironment();
124 environment != nullptr;
125 environment = environment->GetParent()) {
126 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
127 DCHECK(environment->GetHolder() == instruction);
128 if (environment->GetInstructionAt(i) != nullptr) {
129 environment->SetRawEnvAt(i, nullptr);
130 }
131 }
132 }
133}
134
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000135static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100136 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000137 RemoveEnvironmentUses(instruction);
138}
139
Roland Levillainfc600dc2014-12-02 17:16:31 +0000140void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100141 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000142 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100143 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100145 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
147 RemoveAsUser(it.Current());
148 }
149 }
150 }
151}
152
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100153void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000159 for (HBasicBlock* successor : block->GetSuccessors()) {
160 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000161 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // Remove the block from the list of blocks, so that further analyses
163 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600165 if (block->IsExitBlock()) {
166 SetExitBlock(nullptr);
167 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // Mark the block as removed. This is used by the HGraphBuilder to discard
169 // the block as a branch target.
170 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172 }
173}
174
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100176 ArenaBitVector visited(allocator_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177
David Brazdil86ea7ee2016-02-16 09:26:07 +0000178 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 FindBackEdges(&visited);
180
David Brazdil86ea7ee2016-02-16 09:26:07 +0000181 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000182 // the initial DFS as users from other instructions, so that
183 // users can be safely removed before uses later.
184 RemoveInstructionsAsUsersFromDeadBlocks(visited);
185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 // predecessors list of live blocks.
189 RemoveDeadBlocks(visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 // dominators and the reverse post order.
193 SimplifyCFG();
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197
David Brazdil86ea7ee2016-02-16 09:26:07 +0000198 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000199 // set the loop information on each block.
200 GraphAnalysisResult result = AnalyzeLoops();
201 if (result != kAnalysisSuccess) {
202 return result;
203 }
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206 // which needs the information to build catch block phis from values of
207 // locals at throwing instructions inside try blocks.
208 ComputeTryBlockInformation();
209
210 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211}
212
213void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100214 for (HBasicBlock* block : GetReversePostOrder()) {
215 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100216 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100217 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100218}
219
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000220void HGraph::ClearLoopInformation() {
221 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000228 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229 dominator_ = nullptr;
230}
231
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000232HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
233 HInstruction* instruction = GetFirstInstruction();
234 while (instruction->IsParallelMove()) {
235 instruction = instruction->GetNext();
236 }
237 return instruction;
238}
239
David Brazdil3f4a5222016-05-06 12:46:21 +0100240static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
241 DCHECK(ContainsElement(block->GetSuccessors(), successor));
242
243 HBasicBlock* old_dominator = successor->GetDominator();
244 HBasicBlock* new_dominator =
245 (old_dominator == nullptr) ? block
246 : CommonDominator::ForPair(old_dominator, block);
247
248 if (old_dominator == new_dominator) {
249 return false;
250 } else {
251 successor->SetDominator(new_dominator);
252 return true;
253 }
254}
255
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100256void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100257 DCHECK(reverse_post_order_.empty());
258 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100259 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100260
261 // Number of visits of a given node, indexed by block id.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100262 ArenaVector<size_t> visits(blocks_.size(), 0u, allocator_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100263 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100264 ArenaVector<size_t> successors_visited(blocks_.size(),
265 0u,
Vladimir Markoca6fff82017-10-03 14:49:14 +0100266 allocator_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100267 // Nodes for which we need to visit successors.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100268 ArenaVector<HBasicBlock*> worklist(allocator_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100269 constexpr size_t kDefaultWorklistSize = 8;
270 worklist.reserve(kDefaultWorklistSize);
271 worklist.push_back(entry_block_);
272
273 while (!worklist.empty()) {
274 HBasicBlock* current = worklist.back();
275 uint32_t current_id = current->GetBlockId();
276 if (successors_visited[current_id] == current->GetSuccessors().size()) {
277 worklist.pop_back();
278 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100280 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100281
282 // Once all the forward edges have been visited, we know the immediate
283 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100284 if (++visits[successor->GetBlockId()] ==
285 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100286 reverse_post_order_.push_back(successor);
287 worklist.push_back(successor);
288 }
289 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000290 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000291
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 // Check if the graph has back edges not dominated by their respective headers.
293 // If so, we need to update the dominators of those headers and recursively of
294 // their successors. We do that with a fix-point iteration over all blocks.
295 // The algorithm is guaranteed to terminate because it loops only if the sum
296 // of all dominator chains has decreased in the current iteration.
297 bool must_run_fix_point = false;
298 for (HBasicBlock* block : blocks_) {
299 if (block != nullptr &&
300 block->IsLoopHeader() &&
301 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
302 must_run_fix_point = true;
303 break;
304 }
305 }
306 if (must_run_fix_point) {
307 bool update_occurred = true;
308 while (update_occurred) {
309 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100310 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100311 for (HBasicBlock* successor : block->GetSuccessors()) {
312 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
313 }
314 }
315 }
316 }
317
318 // Make sure that there are no remaining blocks whose dominator information
319 // needs to be updated.
320 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100321 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100322 for (HBasicBlock* successor : block->GetSuccessors()) {
323 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
324 }
325 }
326 }
327
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000328 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000329 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100330 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000331 if (!block->IsEntryBlock()) {
332 block->GetDominator()->AddDominatedBlock(block);
333 }
334 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000335}
336
David Brazdilfc6a86a2015-06-26 10:33:45 +0000337HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100338 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000339 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000340 // Use `InsertBetween` to ensure the predecessor index and successor index of
341 // `block` and `successor` are preserved.
342 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000343 return new_block;
344}
345
346void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
347 // Insert a new node between `block` and `successor` to split the
348 // critical edge.
349 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100350 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100351 if (successor->IsLoopHeader()) {
352 // If we split at a back edge boundary, make the new block the back edge.
353 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000354 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355 info->RemoveBackEdge(block);
356 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100357 }
358 }
359}
360
Artem Serovc73ee372017-07-31 15:08:40 +0100361// Reorder phi inputs to match reordering of the block's predecessors.
362static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
363 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
364 HPhi* phi = it.Current()->AsPhi();
365 HInstruction* first_instr = phi->InputAt(first);
366 HInstruction* second_instr = phi->InputAt(second);
367 phi->ReplaceInput(first_instr, second);
368 phi->ReplaceInput(second_instr, first);
369 }
370}
371
372// Make sure that the first predecessor of a loop header is the incoming block.
373void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
374 DCHECK(header->IsLoopHeader());
375 HLoopInformation* info = header->GetLoopInformation();
376 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
377 HBasicBlock* to_swap = header->GetPredecessors()[0];
378 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
379 HBasicBlock* predecessor = header->GetPredecessors()[pred];
380 if (!info->IsBackEdge(*predecessor)) {
381 header->predecessors_[pred] = to_swap;
382 header->predecessors_[0] = predecessor;
383 FixPhisAfterPredecessorsReodering(header, 0, pred);
384 break;
385 }
386 }
387 }
388}
389
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100390void HGraph::SimplifyLoop(HBasicBlock* header) {
391 HLoopInformation* info = header->GetLoopInformation();
392
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100393 // Make sure the loop has only one pre header. This simplifies SSA building by having
394 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000395 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
396 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000397 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000398 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100399 HBasicBlock* pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400 AddBlock(pre_header);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100401 pre_header->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402
Vladimir Marko60584552015-09-03 13:35:12 +0000403 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100404 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100405 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100406 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100407 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100408 }
409 }
410 pre_header->AddSuccessor(header);
411 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100412
Artem Serovc73ee372017-07-31 15:08:40 +0100413 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100414
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100415 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000416 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
417 // Called from DeadBlockElimination. Update SuspendCheck pointer.
418 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100419 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420}
421
David Brazdilffee3d32015-07-06 11:48:53 +0100422void HGraph::ComputeTryBlockInformation() {
423 // Iterate in reverse post order to propagate try membership information from
424 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100425 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100426 if (block->IsEntryBlock() || block->IsCatchBlock()) {
427 // Catch blocks after simplification have only exceptional predecessors
428 // and hence are never in tries.
429 continue;
430 }
431
432 // Infer try membership from the first predecessor. Having simplified loops,
433 // the first predecessor can never be a back edge and therefore it must have
434 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100435 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100436 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100437 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000438 if (try_entry != nullptr &&
439 (block->GetTryCatchInformation() == nullptr ||
440 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
441 // We are either setting try block membership for the first time or it
442 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100443 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100444 }
David Brazdilffee3d32015-07-06 11:48:53 +0100445 }
446}
447
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000449// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100450 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000451 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100452 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
453 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
454 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
455 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100456 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000457 if (block->GetSuccessors().size() > 1) {
458 // Only split normal-flow edges. We cannot split exceptional edges as they
459 // are synthesized (approximate real control flow), and we do not need to
460 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000461 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
462 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
463 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100464 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000465 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000466 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
467 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000468 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000469 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000471 // SplitCriticalEdge could have invalidated the `normal_successors`
472 // ArrayRef. We must re-acquire it.
473 normal_successors = block->GetNormalSuccessors();
474 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
475 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100476 }
477 }
478 }
479 if (block->IsLoopHeader()) {
480 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000481 } else if (!block->IsEntryBlock() &&
482 block->GetFirstInstruction() != nullptr &&
483 block->GetFirstInstruction()->IsSuspendCheck()) {
484 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000485 // a loop got dismantled. Just remove the suspend check.
486 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100487 }
488 }
489}
490
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000491GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100492 // We iterate post order to ensure we visit inner loops before outer loops.
493 // `PopulateRecursive` needs this guarantee to know whether a natural loop
494 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100495 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100496 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100497 if (block->IsCatchBlock()) {
498 // TODO: Dealing with exceptional back edges could be tricky because
499 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000500 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100501 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000502 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100503 }
504 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000505 return kAnalysisSuccess;
506}
507
508void HLoopInformation::Dump(std::ostream& os) {
509 os << "header: " << header_->GetBlockId() << std::endl;
510 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
511 for (HBasicBlock* block : back_edges_) {
512 os << "back edge: " << block->GetBlockId() << std::endl;
513 }
514 for (HBasicBlock* block : header_->GetPredecessors()) {
515 os << "predecessor: " << block->GetBlockId() << std::endl;
516 }
517 for (uint32_t idx : blocks_.Indexes()) {
518 os << " in loop: " << idx << std::endl;
519 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100520}
521
David Brazdil8d5b8b22015-03-24 10:51:52 +0000522void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000523 // New constants are inserted before the SuspendCheck at the bottom of the
524 // entry block. Note that this method can be called from the graph builder and
525 // the entry block therefore may not end with SuspendCheck->Goto yet.
526 HInstruction* insert_before = nullptr;
527
528 HInstruction* gota = entry_block_->GetLastInstruction();
529 if (gota != nullptr && gota->IsGoto()) {
530 HInstruction* suspend_check = gota->GetPrevious();
531 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
532 insert_before = suspend_check;
533 } else {
534 insert_before = gota;
535 }
536 }
537
538 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000539 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000540 } else {
541 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000542 }
543}
544
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600545HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100546 // For simplicity, don't bother reviving the cached null constant if it is
547 // not null and not in a block. Otherwise, we need to clear the instruction
548 // id and/or any invariants the graph is assuming when adding new instructions.
549 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100550 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000551 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000553 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000554 if (kIsDebugBuild) {
555 ScopedObjectAccess soa(Thread::Current());
556 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
557 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000558 return cached_null_constant_;
559}
560
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100561HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100562 // For simplicity, don't bother reviving the cached current method if it is
563 // not null and not in a block. Otherwise, we need to clear the instruction
564 // id and/or any invariants the graph is assuming when adding new instructions.
565 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100566 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100567 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600568 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100569 if (entry_block_->GetFirstInstruction() == nullptr) {
570 entry_block_->AddInstruction(cached_current_method_);
571 } else {
572 entry_block_->InsertInstructionBefore(
573 cached_current_method_, entry_block_->GetFirstInstruction());
574 }
575 }
576 return cached_current_method_;
577}
578
Igor Murashkind01745e2017-04-05 16:40:31 -0700579const char* HGraph::GetMethodName() const {
580 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
581 return dex_file_.GetMethodName(method_id);
582}
583
584std::string HGraph::PrettyMethod(bool with_signature) const {
585 return dex_file_.PrettyMethod(method_idx_, with_signature);
586}
587
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100588HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000589 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100590 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000591 DCHECK(IsUint<1>(value));
592 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100593 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100594 case DataType::Type::kInt8:
595 case DataType::Type::kUint16:
596 case DataType::Type::kInt16:
597 case DataType::Type::kInt32:
598 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600599 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000600
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100601 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600602 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000603
604 default:
605 LOG(FATAL) << "Unsupported constant type";
606 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000607 }
David Brazdil46e2a392015-03-16 17:31:52 +0000608}
609
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000610void HGraph::CacheFloatConstant(HFloatConstant* constant) {
611 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
612 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
613 cached_float_constants_.Overwrite(value, constant);
614}
615
616void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
617 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
618 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
619 cached_double_constants_.Overwrite(value, constant);
620}
621
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000622void HLoopInformation::Add(HBasicBlock* block) {
623 blocks_.SetBit(block->GetBlockId());
624}
625
David Brazdil46e2a392015-03-16 17:31:52 +0000626void HLoopInformation::Remove(HBasicBlock* block) {
627 blocks_.ClearBit(block->GetBlockId());
628}
629
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100630void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
631 if (blocks_.IsBitSet(block->GetBlockId())) {
632 return;
633 }
634
635 blocks_.SetBit(block->GetBlockId());
636 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100637 if (block->IsLoopHeader()) {
638 // We're visiting loops in post-order, so inner loops must have been
639 // populated already.
640 DCHECK(block->GetLoopInformation()->IsPopulated());
641 if (block->GetLoopInformation()->IsIrreducible()) {
642 contains_irreducible_loop_ = true;
643 }
644 }
Vladimir Marko60584552015-09-03 13:35:12 +0000645 for (HBasicBlock* predecessor : block->GetPredecessors()) {
646 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100647 }
648}
649
David Brazdilc2e8af92016-04-05 17:15:19 +0100650void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
651 size_t block_id = block->GetBlockId();
652
653 // If `block` is in `finalized`, we know its membership in the loop has been
654 // decided and it does not need to be revisited.
655 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000656 return;
657 }
658
David Brazdilc2e8af92016-04-05 17:15:19 +0100659 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000660 if (block->IsLoopHeader()) {
661 // If we hit a loop header in an irreducible loop, we first check if the
662 // pre header of that loop belongs to the currently analyzed loop. If it does,
663 // then we visit the back edges.
664 // Note that we cannot use GetPreHeader, as the loop may have not been populated
665 // yet.
666 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100667 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000668 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000669 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100670 blocks_.SetBit(block_id);
671 finalized->SetBit(block_id);
672 is_finalized = true;
673
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000674 HLoopInformation* info = block->GetLoopInformation();
675 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100676 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000677 }
678 }
679 } else {
680 // Visit all predecessors. If one predecessor is part of the loop, this
681 // block is also part of this loop.
682 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100683 PopulateIrreducibleRecursive(predecessor, finalized);
684 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000685 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100686 blocks_.SetBit(block_id);
687 finalized->SetBit(block_id);
688 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000689 }
690 }
691 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100692
693 // All predecessors have been recursively visited. Mark finalized if not marked yet.
694 if (!is_finalized) {
695 finalized->SetBit(block_id);
696 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000697}
698
699void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100700 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000701 // Populate this loop: starting with the back edge, recursively add predecessors
702 // that are not already part of that loop. Set the header as part of the loop
703 // to end the recursion.
704 // This is a recursive implementation of the algorithm described in
705 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100706 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000707 blocks_.SetBit(header_->GetBlockId());
708 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100709
David Brazdil3f4a5222016-05-06 12:46:21 +0100710 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100711
712 if (is_irreducible_loop) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100713 ArenaBitVector visited(graph->GetAllocator(),
David Brazdilc2e8af92016-04-05 17:15:19 +0100714 graph->GetBlocks().size(),
715 /* expandable */ false,
716 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100717 // Stop marking blocks at the loop header.
718 visited.SetBit(header_->GetBlockId());
719
David Brazdilc2e8af92016-04-05 17:15:19 +0100720 for (HBasicBlock* back_edge : GetBackEdges()) {
721 PopulateIrreducibleRecursive(back_edge, &visited);
722 }
723 } else {
724 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000725 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100726 }
David Brazdila4b8c212015-05-07 09:59:30 +0100727 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100728
Vladimir Markofd66c502016-04-18 15:37:01 +0100729 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
730 // When compiling in OSR mode, all loops in the compiled method may be entered
731 // from the interpreter. We treat this OSR entry point just like an extra entry
732 // to an irreducible loop, so we need to mark the method's loops as irreducible.
733 // This does not apply to inlined loops which do not act as OSR entry points.
734 if (suspend_check_ == nullptr) {
735 // Just building the graph in OSR mode, this loop is not inlined. We never build an
736 // inner graph in OSR mode as we can do OSR transition only from the outer method.
737 is_irreducible_loop = true;
738 } else {
739 // Look at the suspend check's environment to determine if the loop was inlined.
740 DCHECK(suspend_check_->HasEnvironment());
741 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
742 is_irreducible_loop = true;
743 }
744 }
745 }
746 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100747 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100748 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100749 graph->SetHasIrreducibleLoops(true);
750 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800751 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100752}
753
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100754HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000755 HBasicBlock* block = header_->GetPredecessors()[0];
756 DCHECK(irreducible_ || (block == header_->GetDominator()));
757 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100758}
759
760bool HLoopInformation::Contains(const HBasicBlock& block) const {
761 return blocks_.IsBitSet(block.GetBlockId());
762}
763
764bool HLoopInformation::IsIn(const HLoopInformation& other) const {
765 return other.blocks_.IsBitSet(header_->GetBlockId());
766}
767
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800768bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
769 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700770}
771
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100772size_t HLoopInformation::GetLifetimeEnd() const {
773 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100774 for (HBasicBlock* back_edge : GetBackEdges()) {
775 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100776 }
777 return last_position;
778}
779
David Brazdil3f4a5222016-05-06 12:46:21 +0100780bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
781 for (HBasicBlock* back_edge : GetBackEdges()) {
782 DCHECK(back_edge->GetDominator() != nullptr);
783 if (!header_->Dominates(back_edge)) {
784 return true;
785 }
786 }
787 return false;
788}
789
Anton Shaminf89381f2016-05-16 16:44:13 +0600790bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
791 for (HBasicBlock* back_edge : GetBackEdges()) {
792 if (!block->Dominates(back_edge)) {
793 return false;
794 }
795 }
796 return true;
797}
798
David Sehrc757dec2016-11-04 15:48:34 -0700799
800bool HLoopInformation::HasExitEdge() const {
801 // Determine if this loop has at least one exit edge.
802 HBlocksInLoopReversePostOrderIterator it_loop(*this);
803 for (; !it_loop.Done(); it_loop.Advance()) {
804 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
805 if (!Contains(*successor)) {
806 return true;
807 }
808 }
809 }
810 return false;
811}
812
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100813bool HBasicBlock::Dominates(HBasicBlock* other) const {
814 // Walk up the dominator tree from `other`, to find out if `this`
815 // is an ancestor.
816 HBasicBlock* current = other;
817 while (current != nullptr) {
818 if (current == this) {
819 return true;
820 }
821 current = current->GetDominator();
822 }
823 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100824}
825
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100826static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100827 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100828 for (size_t i = 0; i < inputs.size(); ++i) {
829 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100830 }
831 // Environment should be created later.
832 DCHECK(!instruction->HasEnvironment());
833}
834
Roland Levillainccc07a92014-09-16 14:48:16 +0100835void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
836 HInstruction* replacement) {
837 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400838 if (initial->IsControlFlow()) {
839 // We can only replace a control flow instruction with another control flow instruction.
840 DCHECK(replacement->IsControlFlow());
841 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100842 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400843 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100844 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100845 DCHECK(initial->GetUses().empty());
846 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400847 replacement->SetBlock(this);
848 replacement->SetId(GetGraph()->GetNextInstructionId());
849 instructions_.InsertInstructionBefore(replacement, initial);
850 UpdateInputsUsers(replacement);
851 } else {
852 InsertInstructionBefore(replacement, initial);
853 initial->ReplaceWith(replacement);
854 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100855 RemoveInstruction(initial);
856}
857
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100858static void Add(HInstructionList* instruction_list,
859 HBasicBlock* block,
860 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000861 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000862 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100863 instruction->SetBlock(block);
864 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100865 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100866 instruction_list->AddInstruction(instruction);
867}
868
869void HBasicBlock::AddInstruction(HInstruction* instruction) {
870 Add(&instructions_, this, instruction);
871}
872
873void HBasicBlock::AddPhi(HPhi* phi) {
874 Add(&phis_, this, phi);
875}
876
David Brazdilc3d743f2015-04-22 13:40:50 +0100877void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
878 DCHECK(!cursor->IsPhi());
879 DCHECK(!instruction->IsPhi());
880 DCHECK_EQ(instruction->GetId(), -1);
881 DCHECK_NE(cursor->GetId(), -1);
882 DCHECK_EQ(cursor->GetBlock(), this);
883 DCHECK(!instruction->IsControlFlow());
884 instruction->SetBlock(this);
885 instruction->SetId(GetGraph()->GetNextInstructionId());
886 UpdateInputsUsers(instruction);
887 instructions_.InsertInstructionBefore(instruction, cursor);
888}
889
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100890void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
891 DCHECK(!cursor->IsPhi());
892 DCHECK(!instruction->IsPhi());
893 DCHECK_EQ(instruction->GetId(), -1);
894 DCHECK_NE(cursor->GetId(), -1);
895 DCHECK_EQ(cursor->GetBlock(), this);
896 DCHECK(!instruction->IsControlFlow());
897 DCHECK(!cursor->IsControlFlow());
898 instruction->SetBlock(this);
899 instruction->SetId(GetGraph()->GetNextInstructionId());
900 UpdateInputsUsers(instruction);
901 instructions_.InsertInstructionAfter(instruction, cursor);
902}
903
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100904void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
905 DCHECK_EQ(phi->GetId(), -1);
906 DCHECK_NE(cursor->GetId(), -1);
907 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100908 phi->SetBlock(this);
909 phi->SetId(GetGraph()->GetNextInstructionId());
910 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100911 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100912}
913
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100914static void Remove(HInstructionList* instruction_list,
915 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000916 HInstruction* instruction,
917 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100918 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100919 instruction->SetBlock(nullptr);
920 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000921 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100922 DCHECK(instruction->GetUses().empty());
923 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000924 RemoveAsUser(instruction);
925 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100926}
927
David Brazdil1abb4192015-02-17 18:33:36 +0000928void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100929 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000930 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931}
932
David Brazdil1abb4192015-02-17 18:33:36 +0000933void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
934 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100935}
936
David Brazdilc7508e92015-04-27 13:28:57 +0100937void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
938 if (instruction->IsPhi()) {
939 RemovePhi(instruction->AsPhi(), ensure_safety);
940 } else {
941 RemoveInstruction(instruction, ensure_safety);
942 }
943}
944
Vladimir Marko71bf8092015-09-15 15:33:14 +0100945void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
946 for (size_t i = 0; i < locals.size(); i++) {
947 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100948 SetRawEnvAt(i, instruction);
949 if (instruction != nullptr) {
950 instruction->AddEnvUseAt(this, i);
951 }
952 }
953}
954
David Brazdiled596192015-01-23 10:39:45 +0000955void HEnvironment::CopyFrom(HEnvironment* env) {
956 for (size_t i = 0; i < env->Size(); i++) {
957 HInstruction* instruction = env->GetInstructionAt(i);
958 SetRawEnvAt(i, instruction);
959 if (instruction != nullptr) {
960 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100961 }
David Brazdiled596192015-01-23 10:39:45 +0000962 }
963}
964
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700965void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
966 HBasicBlock* loop_header) {
967 DCHECK(loop_header->IsLoopHeader());
968 for (size_t i = 0; i < env->Size(); i++) {
969 HInstruction* instruction = env->GetInstructionAt(i);
970 SetRawEnvAt(i, instruction);
971 if (instruction == nullptr) {
972 continue;
973 }
974 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
975 // At the end of the loop pre-header, the corresponding value for instruction
976 // is the first input of the phi.
977 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700978 SetRawEnvAt(i, initial);
979 initial->AddEnvUseAt(this, i);
980 } else {
981 instruction->AddEnvUseAt(this, i);
982 }
983 }
984}
985
David Brazdil1abb4192015-02-17 18:33:36 +0000986void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100987 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
988 HInstruction* user = env_use.GetInstruction();
989 auto before_env_use_node = env_use.GetBeforeUseNode();
990 user->env_uses_.erase_after(before_env_use_node);
991 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100992}
993
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000994HInstruction::InstructionKind HInstruction::GetKind() const {
995 return GetKindInternal();
996}
997
Calin Juravle77520bc2015-01-12 18:45:46 +0000998HInstruction* HInstruction::GetNextDisregardingMoves() const {
999 HInstruction* next = GetNext();
1000 while (next != nullptr && next->IsParallelMove()) {
1001 next = next->GetNext();
1002 }
1003 return next;
1004}
1005
1006HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1007 HInstruction* previous = GetPrevious();
1008 while (previous != nullptr && previous->IsParallelMove()) {
1009 previous = previous->GetPrevious();
1010 }
1011 return previous;
1012}
1013
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001014void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001015 if (first_instruction_ == nullptr) {
1016 DCHECK(last_instruction_ == nullptr);
1017 first_instruction_ = last_instruction_ = instruction;
1018 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001019 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001020 last_instruction_->next_ = instruction;
1021 instruction->previous_ = last_instruction_;
1022 last_instruction_ = instruction;
1023 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001024}
1025
David Brazdilc3d743f2015-04-22 13:40:50 +01001026void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1027 DCHECK(Contains(cursor));
1028 if (cursor == first_instruction_) {
1029 cursor->previous_ = instruction;
1030 instruction->next_ = cursor;
1031 first_instruction_ = instruction;
1032 } else {
1033 instruction->previous_ = cursor->previous_;
1034 instruction->next_ = cursor;
1035 cursor->previous_ = instruction;
1036 instruction->previous_->next_ = instruction;
1037 }
1038}
1039
1040void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1041 DCHECK(Contains(cursor));
1042 if (cursor == last_instruction_) {
1043 cursor->next_ = instruction;
1044 instruction->previous_ = cursor;
1045 last_instruction_ = instruction;
1046 } else {
1047 instruction->next_ = cursor->next_;
1048 instruction->previous_ = cursor;
1049 cursor->next_ = instruction;
1050 instruction->next_->previous_ = instruction;
1051 }
1052}
1053
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001054void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1055 if (instruction->previous_ != nullptr) {
1056 instruction->previous_->next_ = instruction->next_;
1057 }
1058 if (instruction->next_ != nullptr) {
1059 instruction->next_->previous_ = instruction->previous_;
1060 }
1061 if (instruction == first_instruction_) {
1062 first_instruction_ = instruction->next_;
1063 }
1064 if (instruction == last_instruction_) {
1065 last_instruction_ = instruction->previous_;
1066 }
1067}
1068
Roland Levillain6b469232014-09-25 10:10:38 +01001069bool HInstructionList::Contains(HInstruction* instruction) const {
1070 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1071 if (it.Current() == instruction) {
1072 return true;
1073 }
1074 }
1075 return false;
1076}
1077
Roland Levillainccc07a92014-09-16 14:48:16 +01001078bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1079 const HInstruction* instruction2) const {
1080 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1081 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1082 if (it.Current() == instruction1) {
1083 return true;
1084 }
1085 if (it.Current() == instruction2) {
1086 return false;
1087 }
1088 }
1089 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1090 return true;
1091}
1092
Roland Levillain6c82d402014-10-13 16:10:27 +01001093bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1094 if (other_instruction == this) {
1095 // An instruction does not strictly dominate itself.
1096 return false;
1097 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001098 HBasicBlock* block = GetBlock();
1099 HBasicBlock* other_block = other_instruction->GetBlock();
1100 if (block != other_block) {
1101 return GetBlock()->Dominates(other_instruction->GetBlock());
1102 } else {
1103 // If both instructions are in the same block, ensure this
1104 // instruction comes before `other_instruction`.
1105 if (IsPhi()) {
1106 if (!other_instruction->IsPhi()) {
1107 // Phis appear before non phi-instructions so this instruction
1108 // dominates `other_instruction`.
1109 return true;
1110 } else {
1111 // There is no order among phis.
1112 LOG(FATAL) << "There is no dominance between phis of a same block.";
1113 return false;
1114 }
1115 } else {
1116 // `this` is not a phi.
1117 if (other_instruction->IsPhi()) {
1118 // Phis appear before non phi-instructions so this instruction
1119 // does not dominate `other_instruction`.
1120 return false;
1121 } else {
1122 // Check whether this instruction comes before
1123 // `other_instruction` in the instruction list.
1124 return block->GetInstructions().FoundBefore(this, other_instruction);
1125 }
1126 }
1127 }
1128}
1129
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001130void HInstruction::RemoveEnvironment() {
1131 RemoveEnvironmentUses(this);
1132 environment_ = nullptr;
1133}
1134
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001135void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001136 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001137 // Note: fixup_end remains valid across splice_after().
1138 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1139 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1140 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001141
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001142 // Note: env_fixup_end remains valid across splice_after().
1143 auto env_fixup_end =
1144 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1145 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1146 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001147
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001148 DCHECK(uses_.empty());
1149 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001150}
1151
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001152void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1153 const HUseList<HInstruction*>& uses = GetUses();
1154 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1155 HInstruction* user = it->GetUser();
1156 size_t index = it->GetIndex();
1157 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1158 ++it;
1159 if (dominator->StrictlyDominates(user)) {
1160 user->ReplaceInput(replacement, index);
1161 }
1162 }
1163}
1164
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001165void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001166 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001167 if (input_use.GetInstruction() == replacement) {
1168 // Nothing to do.
1169 return;
1170 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001171 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001172 // Note: fixup_end remains valid across splice_after().
1173 auto fixup_end =
1174 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1175 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1176 input_use.GetInstruction()->uses_,
1177 before_use_node);
1178 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1179 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001180}
1181
Nicolas Geoffray39468442014-09-02 15:17:15 +01001182size_t HInstruction::EnvironmentSize() const {
1183 return HasEnvironment() ? environment_->Size() : 0;
1184}
1185
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001186void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001187 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001188 inputs_.push_back(HUserRecord<HInstruction*>(input));
1189 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001190}
1191
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001192void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1193 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1194 input->AddUseAt(this, index);
1195 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1196 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1197 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1198 inputs_[i].GetUseNode()->SetIndex(i);
1199 }
1200}
1201
1202void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001203 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001204 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001205 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1206 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1207 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1208 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001209 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001210}
1211
Igor Murashkind01745e2017-04-05 16:40:31 -07001212void HVariableInputSizeInstruction::RemoveAllInputs() {
1213 RemoveAsUserOfAllInputs();
1214 DCHECK(!HasNonEnvironmentUses());
1215
1216 inputs_.clear();
1217 DCHECK_EQ(0u, InputCount());
1218}
1219
Igor Murashkin6ef45672017-08-08 13:59:55 -07001220size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001221 DCHECK(instruction->GetBlock() != nullptr);
1222 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001223 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001224
Igor Murashkin6ef45672017-08-08 13:59:55 -07001225 // Return how many instructions were removed for statistic purposes.
1226 size_t remove_count = 0;
1227
Igor Murashkind01745e2017-04-05 16:40:31 -07001228 // Efficient implementation that simultaneously (in one pass):
1229 // * Scans the uses list for all constructor fences.
1230 // * Deletes that constructor fence from the uses list of `instruction`.
1231 // * Deletes `instruction` from the constructor fence's inputs.
1232 // * Deletes the constructor fence if it now has 0 inputs.
1233
1234 const HUseList<HInstruction*>& uses = instruction->GetUses();
1235 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1236 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1237 const HUseListNode<HInstruction*>& use_node = *it;
1238 HInstruction* const use_instruction = use_node.GetUser();
1239
1240 // Advance the iterator immediately once we fetch the use_node.
1241 // Warning: If the input is removed, the current iterator becomes invalid.
1242 ++it;
1243
1244 if (use_instruction->IsConstructorFence()) {
1245 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1246 size_t input_index = use_node.GetIndex();
1247
1248 // Process the candidate instruction for removal
1249 // from the graph.
1250
1251 // Constructor fence instructions are never
1252 // used by other instructions.
1253 //
1254 // If we wanted to make this more generic, it
1255 // could be a runtime if statement.
1256 DCHECK(!ctor_fence->HasUses());
1257
1258 // A constructor fence's return type is "kPrimVoid"
1259 // and therefore it can't have any environment uses.
1260 DCHECK(!ctor_fence->HasEnvironmentUses());
1261
1262 // Remove the inputs first, otherwise removing the instruction
1263 // will try to remove its uses while we are already removing uses
1264 // and this operation will fail.
1265 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1266
1267 // Removing the input will also remove the `use_node`.
1268 // (Do not look at `use_node` after this, it will be a dangling reference).
1269 ctor_fence->RemoveInputAt(input_index);
1270
1271 // Once all inputs are removed, the fence is considered dead and
1272 // is removed.
1273 if (ctor_fence->InputCount() == 0u) {
1274 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001275 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001276 }
1277 }
1278 }
1279
1280 if (kIsDebugBuild) {
1281 // Post-condition checks:
1282 // * None of the uses of `instruction` are a constructor fence.
1283 // * The `instruction` itself did not get removed from a block.
1284 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1285 CHECK(!use_node.GetUser()->IsConstructorFence());
1286 }
1287 CHECK(instruction->GetBlock() != nullptr);
1288 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001289
1290 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001291}
1292
Igor Murashkindd018df2017-08-09 10:38:31 -07001293void HConstructorFence::Merge(HConstructorFence* other) {
1294 // Do not delete yourself from the graph.
1295 DCHECK(this != other);
1296 // Don't try to merge with an instruction not associated with a block.
1297 DCHECK(other->GetBlock() != nullptr);
1298 // A constructor fence's return type is "kPrimVoid"
1299 // and therefore it cannot have any environment uses.
1300 DCHECK(!other->HasEnvironmentUses());
1301
1302 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1303 // Check if `haystack` has `needle` as any of its inputs.
1304 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1305 if (haystack->InputAt(input_count) == needle) {
1306 return true;
1307 }
1308 }
1309 return false;
1310 };
1311
1312 // Add any inputs from `other` into `this` if it wasn't already an input.
1313 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1314 HInstruction* other_input = other->InputAt(input_count);
1315 if (!has_input(this, other_input)) {
1316 AddInput(other_input);
1317 }
1318 }
1319
1320 other->GetBlock()->RemoveInstruction(other);
1321}
1322
1323HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001324 HInstruction* new_instance_inst = GetPrevious();
1325 // Check if the immediately preceding instruction is a new-instance/new-array.
1326 // Otherwise this fence is for protecting final fields.
1327 if (new_instance_inst != nullptr &&
1328 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001329 if (ignore_inputs) {
1330 // If inputs are ignored, simply check if the predecessor is
1331 // *any* HNewInstance/HNewArray.
1332 //
1333 // Inputs are normally only ignored for prepare_for_register_allocation,
1334 // at which point *any* prior HNewInstance/Array can be considered
1335 // associated.
1336 return new_instance_inst;
1337 } else {
1338 // Normal case: There must be exactly 1 input and the previous instruction
1339 // must be that input.
1340 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1341 return new_instance_inst;
1342 }
1343 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001344 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001345 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001346}
1347
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001348#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001349void H##name::Accept(HGraphVisitor* visitor) { \
1350 visitor->Visit##name(this); \
1351}
1352
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001353FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001354
1355#undef DEFINE_ACCEPT
1356
1357void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001358 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1359 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001360 if (block != nullptr) {
1361 VisitBasicBlock(block);
1362 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001363 }
1364}
1365
Roland Levillain633021e2014-10-01 14:12:25 +01001366void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001367 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1368 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001369 }
1370}
1371
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001372void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001373 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001374 it.Current()->Accept(this);
1375 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001376 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001377 it.Current()->Accept(this);
1378 }
1379}
1380
Mark Mendelle82549b2015-05-06 10:55:34 -04001381HConstant* HTypeConversion::TryStaticEvaluation() const {
1382 HGraph* graph = GetBlock()->GetGraph();
1383 if (GetInput()->IsIntConstant()) {
1384 int32_t value = GetInput()->AsIntConstant()->GetValue();
1385 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001386 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001387 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001388 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001389 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001390 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001391 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001392 default:
1393 return nullptr;
1394 }
1395 } else if (GetInput()->IsLongConstant()) {
1396 int64_t value = GetInput()->AsLongConstant()->GetValue();
1397 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001399 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001400 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001401 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001402 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001403 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001404 default:
1405 return nullptr;
1406 }
1407 } else if (GetInput()->IsFloatConstant()) {
1408 float value = GetInput()->AsFloatConstant()->GetValue();
1409 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001410 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001411 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001412 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001413 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001414 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001415 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001416 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1417 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001419 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001420 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001421 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001422 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001423 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001424 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1425 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001427 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001428 default:
1429 return nullptr;
1430 }
1431 } else if (GetInput()->IsDoubleConstant()) {
1432 double value = GetInput()->AsDoubleConstant()->GetValue();
1433 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001434 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001435 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001436 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001437 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001438 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001439 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001440 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1441 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001442 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001443 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001444 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001445 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001446 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001447 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001448 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1449 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001450 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001451 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001452 default:
1453 return nullptr;
1454 }
1455 }
1456 return nullptr;
1457}
1458
Roland Levillain9240d6a2014-10-20 16:47:04 +01001459HConstant* HUnaryOperation::TryStaticEvaluation() const {
1460 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001461 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001462 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001463 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001464 } else if (kEnableFloatingPointStaticEvaluation) {
1465 if (GetInput()->IsFloatConstant()) {
1466 return Evaluate(GetInput()->AsFloatConstant());
1467 } else if (GetInput()->IsDoubleConstant()) {
1468 return Evaluate(GetInput()->AsDoubleConstant());
1469 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001470 }
1471 return nullptr;
1472}
1473
1474HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001475 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1476 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001477 } else if (GetLeft()->IsLongConstant()) {
1478 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001479 // The binop(long, int) case is only valid for shifts and rotations.
1480 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001481 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1482 } else if (GetRight()->IsLongConstant()) {
1483 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001484 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001485 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001486 // The binop(null, null) case is only valid for equal and not-equal conditions.
1487 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001488 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001489 } else if (kEnableFloatingPointStaticEvaluation) {
1490 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1491 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1492 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1493 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1494 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001495 }
1496 return nullptr;
1497}
Dave Allison20dfc792014-06-16 20:44:29 -07001498
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001499HConstant* HBinaryOperation::GetConstantRight() const {
1500 if (GetRight()->IsConstant()) {
1501 return GetRight()->AsConstant();
1502 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1503 return GetLeft()->AsConstant();
1504 } else {
1505 return nullptr;
1506 }
1507}
1508
1509// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001510// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001511HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1512 HInstruction* most_constant_right = GetConstantRight();
1513 if (most_constant_right == nullptr) {
1514 return nullptr;
1515 } else if (most_constant_right == GetLeft()) {
1516 return GetRight();
1517 } else {
1518 return GetLeft();
1519 }
1520}
1521
Roland Levillain31dd3d62016-02-16 12:21:02 +00001522std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1523 switch (rhs) {
1524 case ComparisonBias::kNoBias:
1525 return os << "no_bias";
1526 case ComparisonBias::kGtBias:
1527 return os << "gt_bias";
1528 case ComparisonBias::kLtBias:
1529 return os << "lt_bias";
1530 default:
1531 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1532 UNREACHABLE();
1533 }
1534}
1535
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001536bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1537 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001538}
1539
Vladimir Marko372f10e2016-05-17 16:30:10 +01001540bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001541 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001542 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001543 if (!InstructionDataEquals(other)) return false;
1544 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001545 HConstInputsRef inputs = GetInputs();
1546 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001547 if (inputs.size() != other_inputs.size()) return false;
1548 for (size_t i = 0; i != inputs.size(); ++i) {
1549 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001550 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001551
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001552 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001553 return true;
1554}
1555
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001556std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1557#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1558 switch (rhs) {
1559 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1560 default:
1561 os << "Unknown instruction kind " << static_cast<int>(rhs);
1562 break;
1563 }
1564#undef DECLARE_CASE
1565 return os;
1566}
1567
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001568void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1569 if (do_checks) {
1570 DCHECK(!IsPhi());
1571 DCHECK(!IsControlFlow());
1572 DCHECK(CanBeMoved() ||
1573 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1574 IsShouldDeoptimizeFlag());
1575 DCHECK(!cursor->IsPhi());
1576 }
David Brazdild6c205e2016-06-07 14:20:52 +01001577
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001578 next_->previous_ = previous_;
1579 if (previous_ != nullptr) {
1580 previous_->next_ = next_;
1581 }
1582 if (block_->instructions_.first_instruction_ == this) {
1583 block_->instructions_.first_instruction_ = next_;
1584 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001585 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001586
1587 previous_ = cursor->previous_;
1588 if (previous_ != nullptr) {
1589 previous_->next_ = this;
1590 }
1591 next_ = cursor;
1592 cursor->previous_ = this;
1593 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001594
1595 if (block_->instructions_.first_instruction_ == cursor) {
1596 block_->instructions_.first_instruction_ = this;
1597 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001598}
1599
Vladimir Markofb337ea2015-11-25 15:25:10 +00001600void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1601 DCHECK(!CanThrow());
1602 DCHECK(!HasSideEffects());
1603 DCHECK(!HasEnvironmentUses());
1604 DCHECK(HasNonEnvironmentUses());
1605 DCHECK(!IsPhi()); // Makes no sense for Phi.
1606 DCHECK_EQ(InputCount(), 0u);
1607
1608 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001609 auto uses_it = GetUses().begin();
1610 auto uses_end = GetUses().end();
1611 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1612 ++uses_it;
1613 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1614 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001615 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001616 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001617 // This instruction has uses in two or more blocks. Find the common dominator.
1618 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001619 for (; uses_it != uses_end; ++uses_it) {
1620 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001621 }
1622 target_block = finder.Get();
1623 DCHECK(target_block != nullptr);
1624 }
1625 // Move to the first dominator not in a loop.
1626 while (target_block->IsInLoop()) {
1627 target_block = target_block->GetDominator();
1628 DCHECK(target_block != nullptr);
1629 }
1630
1631 // Find insertion position.
1632 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001633 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1634 if (use.GetUser()->GetBlock() == target_block &&
1635 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1636 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001637 }
1638 }
1639 if (insert_pos == nullptr) {
1640 // No user in `target_block`, insert before the control flow instruction.
1641 insert_pos = target_block->GetLastInstruction();
1642 DCHECK(insert_pos->IsControlFlow());
1643 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1644 if (insert_pos->IsIf()) {
1645 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1646 if (if_input == insert_pos->GetPrevious()) {
1647 insert_pos = if_input;
1648 }
1649 }
1650 }
1651 MoveBefore(insert_pos);
1652}
1653
David Brazdilfc6a86a2015-06-26 10:33:45 +00001654HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001655 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001656 DCHECK_EQ(cursor->GetBlock(), this);
1657
Vladimir Markoca6fff82017-10-03 14:49:14 +01001658 HBasicBlock* new_block =
1659 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001660 new_block->instructions_.first_instruction_ = cursor;
1661 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1662 instructions_.last_instruction_ = cursor->previous_;
1663 if (cursor->previous_ == nullptr) {
1664 instructions_.first_instruction_ = nullptr;
1665 } else {
1666 cursor->previous_->next_ = nullptr;
1667 cursor->previous_ = nullptr;
1668 }
1669
1670 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001671 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001672
Vladimir Marko60584552015-09-03 13:35:12 +00001673 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001674 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001675 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001676 new_block->successors_.swap(successors_);
1677 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001678 AddSuccessor(new_block);
1679
David Brazdil56e1acc2015-06-30 15:41:36 +01001680 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001681 return new_block;
1682}
1683
David Brazdild7558da2015-09-22 13:04:14 +01001684HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001685 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001686 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1687
Vladimir Markoca6fff82017-10-03 14:49:14 +01001688 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001689
1690 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001691 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1692 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001693 new_block->predecessors_.swap(predecessors_);
1694 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001695 AddPredecessor(new_block);
1696
1697 GetGraph()->AddBlock(new_block);
1698 return new_block;
1699}
1700
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001701HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1702 DCHECK_EQ(cursor->GetBlock(), this);
1703
Vladimir Markoca6fff82017-10-03 14:49:14 +01001704 HBasicBlock* new_block =
1705 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001706 new_block->instructions_.first_instruction_ = cursor;
1707 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1708 instructions_.last_instruction_ = cursor->previous_;
1709 if (cursor->previous_ == nullptr) {
1710 instructions_.first_instruction_ = nullptr;
1711 } else {
1712 cursor->previous_->next_ = nullptr;
1713 cursor->previous_ = nullptr;
1714 }
1715
1716 new_block->instructions_.SetBlockOfInstructions(new_block);
1717
1718 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001719 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1720 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001721 new_block->successors_.swap(successors_);
1722 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001723
1724 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1725 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001726 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001727 new_block->dominated_blocks_.swap(dominated_blocks_);
1728 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001729 return new_block;
1730}
1731
1732HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001733 DCHECK(!cursor->IsControlFlow());
1734 DCHECK_NE(instructions_.last_instruction_, cursor);
1735 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001736
Vladimir Markoca6fff82017-10-03 14:49:14 +01001737 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001738 new_block->instructions_.first_instruction_ = cursor->GetNext();
1739 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1740 cursor->next_->previous_ = nullptr;
1741 cursor->next_ = nullptr;
1742 instructions_.last_instruction_ = cursor;
1743
1744 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001745 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001746 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001747 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001748 new_block->successors_.swap(successors_);
1749 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001750
Vladimir Marko60584552015-09-03 13:35:12 +00001751 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001752 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001753 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001754 new_block->dominated_blocks_.swap(dominated_blocks_);
1755 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001756 return new_block;
1757}
1758
David Brazdilec16f792015-08-19 15:04:01 +01001759const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001760 if (EndsWithTryBoundary()) {
1761 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1762 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001763 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001764 return try_boundary;
1765 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001766 DCHECK(IsTryBlock());
1767 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001768 return nullptr;
1769 }
David Brazdilec16f792015-08-19 15:04:01 +01001770 } else if (IsTryBlock()) {
1771 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001772 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001773 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001774 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001775}
1776
David Brazdild7558da2015-09-22 13:04:14 +01001777bool HBasicBlock::HasThrowingInstructions() const {
1778 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1779 if (it.Current()->CanThrow()) {
1780 return true;
1781 }
1782 }
1783 return false;
1784}
1785
David Brazdilfc6a86a2015-06-26 10:33:45 +00001786static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1787 return block.GetPhis().IsEmpty()
1788 && !block.GetInstructions().IsEmpty()
1789 && block.GetFirstInstruction() == block.GetLastInstruction();
1790}
1791
David Brazdil46e2a392015-03-16 17:31:52 +00001792bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001793 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1794}
1795
Mads Ager16e52892017-07-14 13:11:37 +02001796bool HBasicBlock::IsSingleReturn() const {
1797 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1798}
1799
David Brazdilfc6a86a2015-06-26 10:33:45 +00001800bool HBasicBlock::IsSingleTryBoundary() const {
1801 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001802}
1803
David Brazdil8d5b8b22015-03-24 10:51:52 +00001804bool HBasicBlock::EndsWithControlFlowInstruction() const {
1805 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1806}
1807
David Brazdilb2bd1c52015-03-25 11:17:37 +00001808bool HBasicBlock::EndsWithIf() const {
1809 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1810}
1811
David Brazdilffee3d32015-07-06 11:48:53 +01001812bool HBasicBlock::EndsWithTryBoundary() const {
1813 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1814}
1815
David Brazdilb2bd1c52015-03-25 11:17:37 +00001816bool HBasicBlock::HasSinglePhi() const {
1817 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1818}
1819
David Brazdild26a4112015-11-10 11:07:31 +00001820ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1821 if (EndsWithTryBoundary()) {
1822 // The normal-flow successor of HTryBoundary is always stored at index zero.
1823 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1824 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1825 } else {
1826 // All successors of blocks not ending with TryBoundary are normal.
1827 return ArrayRef<HBasicBlock* const>(successors_);
1828 }
1829}
1830
1831ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1832 if (EndsWithTryBoundary()) {
1833 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1834 } else {
1835 // Blocks not ending with TryBoundary do not have exceptional successors.
1836 return ArrayRef<HBasicBlock* const>();
1837 }
1838}
1839
David Brazdilffee3d32015-07-06 11:48:53 +01001840bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001841 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1842 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1843
1844 size_t length = handlers1.size();
1845 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001846 return false;
1847 }
1848
David Brazdilb618ade2015-07-29 10:31:29 +01001849 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001850 for (size_t i = 0; i < length; ++i) {
1851 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001852 return false;
1853 }
1854 }
1855 return true;
1856}
1857
David Brazdil2d7352b2015-04-20 14:52:42 +01001858size_t HInstructionList::CountSize() const {
1859 size_t size = 0;
1860 HInstruction* current = first_instruction_;
1861 for (; current != nullptr; current = current->GetNext()) {
1862 size++;
1863 }
1864 return size;
1865}
1866
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001867void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1868 for (HInstruction* current = first_instruction_;
1869 current != nullptr;
1870 current = current->GetNext()) {
1871 current->SetBlock(block);
1872 }
1873}
1874
1875void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1876 DCHECK(Contains(cursor));
1877 if (!instruction_list.IsEmpty()) {
1878 if (cursor == last_instruction_) {
1879 last_instruction_ = instruction_list.last_instruction_;
1880 } else {
1881 cursor->next_->previous_ = instruction_list.last_instruction_;
1882 }
1883 instruction_list.last_instruction_->next_ = cursor->next_;
1884 cursor->next_ = instruction_list.first_instruction_;
1885 instruction_list.first_instruction_->previous_ = cursor;
1886 }
1887}
1888
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001889void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1890 DCHECK(Contains(cursor));
1891 if (!instruction_list.IsEmpty()) {
1892 if (cursor == first_instruction_) {
1893 first_instruction_ = instruction_list.first_instruction_;
1894 } else {
1895 cursor->previous_->next_ = instruction_list.first_instruction_;
1896 }
1897 instruction_list.last_instruction_->next_ = cursor;
1898 instruction_list.first_instruction_->previous_ = cursor->previous_;
1899 cursor->previous_ = instruction_list.last_instruction_;
1900 }
1901}
1902
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001904 if (IsEmpty()) {
1905 first_instruction_ = instruction_list.first_instruction_;
1906 last_instruction_ = instruction_list.last_instruction_;
1907 } else {
1908 AddAfter(last_instruction_, instruction_list);
1909 }
1910}
1911
David Brazdil04ff4e82015-12-10 13:54:52 +00001912// Should be called on instructions in a dead block in post order. This method
1913// assumes `insn` has been removed from all users with the exception of catch
1914// phis because of missing exceptional edges in the graph. It removes the
1915// instruction from catch phi uses, together with inputs of other catch phis in
1916// the catch block at the same index, as these must be dead too.
1917static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1918 DCHECK(!insn->HasEnvironmentUses());
1919 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001920 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1921 size_t use_index = use.GetIndex();
1922 HBasicBlock* user_block = use.GetUser()->GetBlock();
1923 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001924 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1925 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1926 }
1927 }
1928}
1929
David Brazdil2d7352b2015-04-20 14:52:42 +01001930void HBasicBlock::DisconnectAndDelete() {
1931 // Dominators must be removed after all the blocks they dominate. This way
1932 // a loop header is removed last, a requirement for correct loop information
1933 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001934 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001935
David Brazdil9eeebf62016-03-24 11:18:15 +00001936 // The following steps gradually remove the block from all its dependants in
1937 // post order (b/27683071).
1938
1939 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1940 // We need to do this before step (4) which destroys the predecessor list.
1941 HBasicBlock* loop_update_start = this;
1942 if (IsLoopHeader()) {
1943 HLoopInformation* loop_info = GetLoopInformation();
1944 // All other blocks in this loop should have been removed because the header
1945 // was their dominator.
1946 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1947 DCHECK(!loop_info->IsIrreducible());
1948 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1949 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1950 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001951 }
1952
David Brazdil9eeebf62016-03-24 11:18:15 +00001953 // (2) Disconnect the block from its successors and update their phis.
1954 for (HBasicBlock* successor : successors_) {
1955 // Delete this block from the list of predecessors.
1956 size_t this_index = successor->GetPredecessorIndexOf(this);
1957 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1958
1959 // Check that `successor` has other predecessors, otherwise `this` is the
1960 // dominator of `successor` which violates the order DCHECKed at the top.
1961 DCHECK(!successor->predecessors_.empty());
1962
1963 // Remove this block's entries in the successor's phis. Skip exceptional
1964 // successors because catch phi inputs do not correspond to predecessor
1965 // blocks but throwing instructions. The inputs of the catch phis will be
1966 // updated in step (3).
1967 if (!successor->IsCatchBlock()) {
1968 if (successor->predecessors_.size() == 1u) {
1969 // The successor has just one predecessor left. Replace phis with the only
1970 // remaining input.
1971 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1972 HPhi* phi = phi_it.Current()->AsPhi();
1973 phi->ReplaceWith(phi->InputAt(1 - this_index));
1974 successor->RemovePhi(phi);
1975 }
1976 } else {
1977 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1978 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1979 }
1980 }
1981 }
1982 }
1983 successors_.clear();
1984
1985 // (3) Remove instructions and phis. Instructions should have no remaining uses
1986 // except in catch phis. If an instruction is used by a catch phi at `index`,
1987 // remove `index`-th input of all phis in the catch block since they are
1988 // guaranteed dead. Note that we may miss dead inputs this way but the
1989 // graph will always remain consistent.
1990 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1991 HInstruction* insn = it.Current();
1992 RemoveUsesOfDeadInstruction(insn);
1993 RemoveInstruction(insn);
1994 }
1995 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1996 HPhi* insn = it.Current()->AsPhi();
1997 RemoveUsesOfDeadInstruction(insn);
1998 RemovePhi(insn);
1999 }
2000
2001 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002002 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002003 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002004 // We should not see any back edges as they would have been removed by step (3).
2005 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2006
David Brazdil2d7352b2015-04-20 14:52:42 +01002007 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002008 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2009 // This block is the only normal-flow successor of the TryBoundary which
2010 // makes `predecessor` dead. Since DCE removes blocks in post order,
2011 // exception handlers of this TryBoundary were already visited and any
2012 // remaining handlers therefore must be live. We remove `predecessor` from
2013 // their list of predecessors.
2014 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2015 while (predecessor->GetSuccessors().size() > 1) {
2016 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2017 DCHECK(handler->IsCatchBlock());
2018 predecessor->RemoveSuccessor(handler);
2019 handler->RemovePredecessor(predecessor);
2020 }
2021 }
2022
David Brazdil2d7352b2015-04-20 14:52:42 +01002023 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002024 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2025 if (num_pred_successors == 1u) {
2026 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002027 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2028 // successor. Replace those with a HGoto.
2029 DCHECK(last_instruction->IsIf() ||
2030 last_instruction->IsPackedSwitch() ||
2031 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002032 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002033 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002034 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002035 // The predecessor has no remaining successors and therefore must be dead.
2036 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002037 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002038 predecessor->RemoveInstruction(last_instruction);
2039 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002040 // There are multiple successors left. The removed block might be a successor
2041 // of a PackedSwitch which will be completely removed (perhaps replaced with
2042 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2043 // case, leave `last_instruction` as is for now.
2044 DCHECK(last_instruction->IsPackedSwitch() ||
2045 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002046 }
David Brazdil46e2a392015-03-16 17:31:52 +00002047 }
Vladimir Marko60584552015-09-03 13:35:12 +00002048 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002049
David Brazdil9eeebf62016-03-24 11:18:15 +00002050 // (5) Remove the block from all loops it is included in. Skip the inner-most
2051 // loop if this is the loop header (see definition of `loop_update_start`)
2052 // because the loop header's predecessor list has been destroyed in step (4).
2053 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2054 HLoopInformation* loop_info = it.Current();
2055 loop_info->Remove(this);
2056 if (loop_info->IsBackEdge(*this)) {
2057 // If this was the last back edge of the loop, we deliberately leave the
2058 // loop in an inconsistent state and will fail GraphChecker unless the
2059 // entire loop is removed during the pass.
2060 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002061 }
2062 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002063
David Brazdil9eeebf62016-03-24 11:18:15 +00002064 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002065 dominator_->RemoveDominatedBlock(this);
2066 SetDominator(nullptr);
2067
David Brazdil9eeebf62016-03-24 11:18:15 +00002068 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002069 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002070 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002071}
2072
Aart Bik6b69e0a2017-01-11 10:20:43 -08002073void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2074 DCHECK(EndsWithControlFlowInstruction());
2075 RemoveInstruction(GetLastInstruction());
2076 instructions_.Add(other->GetInstructions());
2077 other->instructions_.SetBlockOfInstructions(this);
2078 other->instructions_.Clear();
2079}
2080
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002081void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002082 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002083 DCHECK(ContainsElement(dominated_blocks_, other));
2084 DCHECK_EQ(GetSingleSuccessor(), other);
2085 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002086 DCHECK(other->GetPhis().IsEmpty());
2087
David Brazdil2d7352b2015-04-20 14:52:42 +01002088 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002089 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002090
David Brazdil2d7352b2015-04-20 14:52:42 +01002091 // Remove `other` from the loops it is included in.
2092 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2093 HLoopInformation* loop_info = it.Current();
2094 loop_info->Remove(other);
2095 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002096 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002097 }
2098 }
2099
2100 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002101 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002102 for (HBasicBlock* successor : other->GetSuccessors()) {
2103 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002104 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002105 successors_.swap(other->successors_);
2106 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002107
David Brazdil2d7352b2015-04-20 14:52:42 +01002108 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002109 RemoveDominatedBlock(other);
2110 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002111 dominated->SetDominator(this);
2112 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002113 dominated_blocks_.insert(
2114 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002115 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002116 other->dominator_ = nullptr;
2117
2118 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002119 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002120
2121 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002122 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002123 other->SetGraph(nullptr);
2124}
2125
2126void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2127 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002128 DCHECK(GetDominatedBlocks().empty());
2129 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002130 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002131 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002132 DCHECK(other->GetPhis().IsEmpty());
2133 DCHECK(!other->IsInLoop());
2134
2135 // Move instructions from `other` to `this`.
2136 instructions_.Add(other->GetInstructions());
2137 other->instructions_.SetBlockOfInstructions(this);
2138
2139 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002140 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002141 for (HBasicBlock* successor : other->GetSuccessors()) {
2142 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002143 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002144 successors_.swap(other->successors_);
2145 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002146
2147 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002148 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002149 dominated->SetDominator(this);
2150 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002151 dominated_blocks_.insert(
2152 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002153 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002154 other->dominator_ = nullptr;
2155 other->graph_ = nullptr;
2156}
2157
2158void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002159 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002160 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002161 predecessor->ReplaceSuccessor(this, other);
2162 }
Vladimir Marko60584552015-09-03 13:35:12 +00002163 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002164 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002165 successor->ReplacePredecessor(this, other);
2166 }
Vladimir Marko60584552015-09-03 13:35:12 +00002167 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2168 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002169 }
2170 GetDominator()->ReplaceDominatedBlock(this, other);
2171 other->SetDominator(GetDominator());
2172 dominator_ = nullptr;
2173 graph_ = nullptr;
2174}
2175
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002176void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002177 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002178 DCHECK(block->GetSuccessors().empty());
2179 DCHECK(block->GetPredecessors().empty());
2180 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002181 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002182 DCHECK(block->GetInstructions().IsEmpty());
2183 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002184
David Brazdilc7af85d2015-05-26 12:05:55 +01002185 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002186 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002187 }
2188
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002189 RemoveElement(reverse_post_order_, block);
2190 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002191 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002192}
2193
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002194void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2195 HBasicBlock* reference,
2196 bool replace_if_back_edge) {
2197 if (block->IsLoopHeader()) {
2198 // Clear the information of which blocks are contained in that loop. Since the
2199 // information is stored as a bit vector based on block ids, we have to update
2200 // it, as those block ids were specific to the callee graph and we are now adding
2201 // these blocks to the caller graph.
2202 block->GetLoopInformation()->ClearAllBlocks();
2203 }
2204
2205 // If not already in a loop, update the loop information.
2206 if (!block->IsInLoop()) {
2207 block->SetLoopInformation(reference->GetLoopInformation());
2208 }
2209
2210 // If the block is in a loop, update all its outward loops.
2211 HLoopInformation* loop_info = block->GetLoopInformation();
2212 if (loop_info != nullptr) {
2213 for (HLoopInformationOutwardIterator loop_it(*block);
2214 !loop_it.Done();
2215 loop_it.Advance()) {
2216 loop_it.Current()->Add(block);
2217 }
2218 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2219 loop_info->ReplaceBackEdge(reference, block);
2220 }
2221 }
2222
2223 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2224 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2225 ? reference->GetTryCatchInformation()
2226 : nullptr;
2227 block->SetTryCatchInformation(try_catch_info);
2228}
2229
Calin Juravle2e768302015-07-28 14:41:11 +00002230HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002231 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002232 // Update the environments in this graph to have the invoke's environment
2233 // as parent.
2234 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002235 // Skip the entry block, we do not need to update the entry's suspend check.
2236 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002237 for (HInstructionIterator instr_it(block->GetInstructions());
2238 !instr_it.Done();
2239 instr_it.Advance()) {
2240 HInstruction* current = instr_it.Current();
2241 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002242 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002243 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002244 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002245 }
2246 }
2247 }
2248 }
2249 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002250
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002251 if (HasBoundsChecks()) {
2252 outer_graph->SetHasBoundsChecks(true);
2253 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002254 if (HasLoops()) {
2255 outer_graph->SetHasLoops(true);
2256 }
2257 if (HasIrreducibleLoops()) {
2258 outer_graph->SetHasIrreducibleLoops(true);
2259 }
2260 if (HasTryCatch()) {
2261 outer_graph->SetHasTryCatch(true);
2262 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002263 if (HasSIMD()) {
2264 outer_graph->SetHasSIMD(true);
2265 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002266
Calin Juravle2e768302015-07-28 14:41:11 +00002267 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002268 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002269 // Inliner already made sure we don't inline methods that always throw.
2270 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002271 // Simple case of an entry block, a body block, and an exit block.
2272 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002273 HBasicBlock* body = GetBlocks()[1];
2274 DCHECK(GetBlocks()[0]->IsEntryBlock());
2275 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002276 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002277 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002278 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002279
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002280 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2281 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002282 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002283
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002284 // Replace the invoke with the return value of the inlined graph.
2285 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002286 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002287 } else {
2288 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002289 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002290
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002291 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002292 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002293 // Need to inline multiple blocks. We split `invoke`'s block
2294 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002295 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002296 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002297 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002298 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002299 // Note that we split before the invoke only to simplify polymorphic inlining.
2300 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002301
Vladimir Markoec7802a2015-10-01 20:57:57 +01002302 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002303 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002304 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002305 exit_block_->ReplaceWith(to);
2306
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002307 // Update the meta information surrounding blocks:
2308 // (1) the graph they are now in,
2309 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002310 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002311 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002312 // Note that we do not need to update catch phi inputs because they
2313 // correspond to the register file of the outer method which the inlinee
2314 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002315
2316 // We don't add the entry block, the exit block, and the first block, which
2317 // has been merged with `at`.
2318 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2319
2320 // We add the `to` block.
2321 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002322 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002323 + kNumberOfNewBlocksInCaller;
2324
2325 // Find the location of `at` in the outer graph's reverse post order. The new
2326 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002327 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002328 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2329
David Brazdil95177982015-10-30 12:56:58 -05002330 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2331 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002332 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002333 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002334 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002335 DCHECK(current->GetGraph() == this);
2336 current->SetGraph(outer_graph);
2337 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002338 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002339 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002340 }
2341 }
2342
David Brazdil95177982015-10-30 12:56:58 -05002343 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002344 to->SetGraph(outer_graph);
2345 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002346 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002347 // Only `to` can become a back edge, as the inlined blocks
2348 // are predecessors of `to`.
2349 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002350
David Brazdil3f523062016-02-29 16:53:33 +00002351 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002352 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2353 // to now get the outer graph exit block as successor. Note that the inliner
2354 // currently doesn't support inlining methods with try/catch.
2355 HPhi* return_value_phi = nullptr;
2356 bool rerun_dominance = false;
2357 bool rerun_loop_analysis = false;
2358 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2359 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002360 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002361 if (last->IsThrow()) {
2362 DCHECK(!at->IsTryBlock());
2363 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2364 --pred;
2365 // We need to re-run dominance information, as the exit block now has
2366 // a new dominator.
2367 rerun_dominance = true;
2368 if (predecessor->GetLoopInformation() != nullptr) {
2369 // The exit block and blocks post dominated by the exit block do not belong
2370 // to any loop. Because we do not compute the post dominators, we need to re-run
2371 // loop analysis to get the loop information correct.
2372 rerun_loop_analysis = true;
2373 }
2374 } else {
2375 if (last->IsReturnVoid()) {
2376 DCHECK(return_value == nullptr);
2377 DCHECK(return_value_phi == nullptr);
2378 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002379 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002380 if (return_value_phi != nullptr) {
2381 return_value_phi->AddInput(last->InputAt(0));
2382 } else if (return_value == nullptr) {
2383 return_value = last->InputAt(0);
2384 } else {
2385 // There will be multiple returns.
2386 return_value_phi = new (allocator) HPhi(
2387 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2388 to->AddPhi(return_value_phi);
2389 return_value_phi->AddInput(return_value);
2390 return_value_phi->AddInput(last->InputAt(0));
2391 return_value = return_value_phi;
2392 }
David Brazdil3f523062016-02-29 16:53:33 +00002393 }
2394 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2395 predecessor->RemoveInstruction(last);
2396 }
2397 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002398 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002399 DCHECK(!outer_graph->HasIrreducibleLoops())
2400 << "Recomputing loop information in graphs with irreducible loops "
2401 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002402 outer_graph->ClearLoopInformation();
2403 outer_graph->ClearDominanceInformation();
2404 outer_graph->BuildDominatorTree();
2405 } else if (rerun_dominance) {
2406 outer_graph->ClearDominanceInformation();
2407 outer_graph->ComputeDominanceInformation();
2408 }
David Brazdil3f523062016-02-29 16:53:33 +00002409 }
David Brazdil05144f42015-04-16 15:18:00 +01002410
2411 // Walk over the entry block and:
2412 // - Move constants from the entry block to the outer_graph's entry block,
2413 // - Replace HParameterValue instructions with their real value.
2414 // - Remove suspend checks, that hold an environment.
2415 // We must do this after the other blocks have been inlined, otherwise ids of
2416 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002417 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002418 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2419 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002420 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002421 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002422 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002423 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002424 replacement = outer_graph->GetIntConstant(
2425 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002426 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002427 replacement = outer_graph->GetLongConstant(
2428 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002429 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002430 replacement = outer_graph->GetFloatConstant(
2431 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002432 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002433 replacement = outer_graph->GetDoubleConstant(
2434 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002435 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002436 if (kIsDebugBuild
2437 && invoke->IsInvokeStaticOrDirect()
2438 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2439 // Ensure we do not use the last input of `invoke`, as it
2440 // contains a clinit check which is not an actual argument.
2441 size_t last_input_index = invoke->InputCount() - 1;
2442 DCHECK(parameter_index != last_input_index);
2443 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002444 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002445 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002446 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002447 } else {
2448 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2449 entry_block_->RemoveInstruction(current);
2450 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002451 if (replacement != nullptr) {
2452 current->ReplaceWith(replacement);
2453 // If the current is the return value then we need to update the latter.
2454 if (current == return_value) {
2455 DCHECK_EQ(entry_block_, return_value->GetBlock());
2456 return_value = replacement;
2457 }
2458 }
2459 }
2460
Calin Juravle2e768302015-07-28 14:41:11 +00002461 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002462}
2463
Mingyao Yang3584bce2015-05-19 16:01:59 -07002464/*
2465 * Loop will be transformed to:
2466 * old_pre_header
2467 * |
2468 * if_block
2469 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002470 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002471 * \ /
2472 * new_pre_header
2473 * |
2474 * header
2475 */
2476void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2477 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002478 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002479
Aart Bik3fc7f352015-11-20 22:03:03 -08002480 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002481 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2482 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2483 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2484 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002485 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002486 AddBlock(true_block);
2487 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002488 AddBlock(new_pre_header);
2489
Aart Bik3fc7f352015-11-20 22:03:03 -08002490 header->ReplacePredecessor(old_pre_header, new_pre_header);
2491 old_pre_header->successors_.clear();
2492 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002493
Aart Bik3fc7f352015-11-20 22:03:03 -08002494 old_pre_header->AddSuccessor(if_block);
2495 if_block->AddSuccessor(true_block); // True successor
2496 if_block->AddSuccessor(false_block); // False successor
2497 true_block->AddSuccessor(new_pre_header);
2498 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002499
Aart Bik3fc7f352015-11-20 22:03:03 -08002500 old_pre_header->dominated_blocks_.push_back(if_block);
2501 if_block->SetDominator(old_pre_header);
2502 if_block->dominated_blocks_.push_back(true_block);
2503 true_block->SetDominator(if_block);
2504 if_block->dominated_blocks_.push_back(false_block);
2505 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002506 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002507 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002508 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002509 header->SetDominator(new_pre_header);
2510
Aart Bik3fc7f352015-11-20 22:03:03 -08002511 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002512 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002513 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002514 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002515 reverse_post_order_[index_of_header++] = true_block;
2516 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002517 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002518
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002519 // The pre_header can never be a back edge of a loop.
2520 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2521 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2522 UpdateLoopAndTryInformationOfNewBlock(
2523 if_block, old_pre_header, /* replace_if_back_edge */ false);
2524 UpdateLoopAndTryInformationOfNewBlock(
2525 true_block, old_pre_header, /* replace_if_back_edge */ false);
2526 UpdateLoopAndTryInformationOfNewBlock(
2527 false_block, old_pre_header, /* replace_if_back_edge */ false);
2528 UpdateLoopAndTryInformationOfNewBlock(
2529 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002530}
2531
Aart Bikf8f5a162017-02-06 15:35:29 -08002532HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2533 HBasicBlock* body,
2534 HBasicBlock* exit) {
2535 DCHECK(header->IsLoopHeader());
2536 HLoopInformation* loop = header->GetLoopInformation();
2537
2538 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002539 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2540 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2541 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002542 AddBlock(new_pre_header);
2543 AddBlock(new_header);
2544 AddBlock(new_body);
2545
2546 // Set up control flow.
2547 header->ReplaceSuccessor(exit, new_pre_header);
2548 new_pre_header->AddSuccessor(new_header);
2549 new_header->AddSuccessor(exit);
2550 new_header->AddSuccessor(new_body);
2551 new_body->AddSuccessor(new_header);
2552
2553 // Set up dominators.
2554 header->ReplaceDominatedBlock(exit, new_pre_header);
2555 new_pre_header->SetDominator(header);
2556 new_pre_header->dominated_blocks_.push_back(new_header);
2557 new_header->SetDominator(new_pre_header);
2558 new_header->dominated_blocks_.push_back(new_body);
2559 new_body->SetDominator(new_header);
2560 new_header->dominated_blocks_.push_back(exit);
2561 exit->SetDominator(new_header);
2562
2563 // Fix reverse post order.
2564 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2565 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2566 reverse_post_order_[++index_of_header] = new_pre_header;
2567 reverse_post_order_[++index_of_header] = new_header;
2568 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2569 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2570 reverse_post_order_[index_of_body] = new_body;
2571
Aart Bikb07d1bc2017-04-05 10:03:15 -07002572 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002573 new_pre_header->AddInstruction(new (allocator_) HGoto());
2574 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002575 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002576 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002577 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2578 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002579
2580 // Update loop information.
2581 new_header->AddBackEdge(new_body);
2582 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2583 new_header->GetLoopInformation()->Populate();
2584 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2585 HLoopInformationOutwardIterator it(*new_header);
2586 for (it.Advance(); !it.Done(); it.Advance()) {
2587 it.Current()->Add(new_pre_header);
2588 it.Current()->Add(new_header);
2589 it.Current()->Add(new_body);
2590 }
2591 return new_pre_header;
2592}
2593
David Brazdilf5552582015-12-27 13:36:12 +00002594static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002595 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002596 if (rti.IsValid()) {
2597 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2598 << " upper_bound_rti: " << upper_bound_rti
2599 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002600 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2601 << " upper_bound_rti: " << upper_bound_rti
2602 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002603 }
2604}
2605
Calin Juravle2e768302015-07-28 14:41:11 +00002606void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2607 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002608 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002609 ScopedObjectAccess soa(Thread::Current());
2610 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2611 if (IsBoundType()) {
2612 // Having the test here spares us from making the method virtual just for
2613 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002614 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002615 }
2616 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002617 reference_type_handle_ = rti.GetTypeHandle();
2618 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002619}
2620
David Brazdilf5552582015-12-27 13:36:12 +00002621void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2622 if (kIsDebugBuild) {
2623 ScopedObjectAccess soa(Thread::Current());
2624 DCHECK(upper_bound.IsValid());
2625 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2626 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2627 }
2628 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002629 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002630}
2631
Vladimir Markoa1de9182016-02-25 11:37:38 +00002632ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002633 if (kIsDebugBuild) {
2634 ScopedObjectAccess soa(Thread::Current());
2635 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002636 if (!is_exact) {
2637 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2638 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2639 }
Calin Juravle2e768302015-07-28 14:41:11 +00002640 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002641 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002642}
2643
Calin Juravleacf735c2015-02-12 15:25:22 +00002644std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2645 ScopedObjectAccess soa(Thread::Current());
2646 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002647 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002648 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002649 << " is_exact=" << rhs.IsExact()
2650 << " ]";
2651 return os;
2652}
2653
Mark Mendellc4701932015-04-10 13:18:51 -04002654bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2655 // For now, assume that instructions in different blocks may use the
2656 // environment.
2657 // TODO: Use the control flow to decide if this is true.
2658 if (GetBlock() != other->GetBlock()) {
2659 return true;
2660 }
2661
2662 // We know that we are in the same block. Walk from 'this' to 'other',
2663 // checking to see if there is any instruction with an environment.
2664 HInstruction* current = this;
2665 for (; current != other && current != nullptr; current = current->GetNext()) {
2666 // This is a conservative check, as the instruction result may not be in
2667 // the referenced environment.
2668 if (current->HasEnvironment()) {
2669 return true;
2670 }
2671 }
2672
2673 // We should have been called with 'this' before 'other' in the block.
2674 // Just confirm this.
2675 DCHECK(current != nullptr);
2676 return false;
2677}
2678
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002679void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002680 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2681 IntrinsicSideEffects side_effects,
2682 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002683 intrinsic_ = intrinsic;
2684 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002685
Aart Bik5d75afe2015-12-14 11:57:01 -08002686 // Adjust method's side effects from intrinsic table.
2687 switch (side_effects) {
2688 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2689 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2690 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2691 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2692 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002693
2694 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2695 opt.SetDoesNotNeedDexCache();
2696 opt.SetDoesNotNeedEnvironment();
2697 } else {
2698 // If we need an environment, that means there will be a call, which can trigger GC.
2699 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2700 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002701 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002702 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002703}
2704
David Brazdil6de19382016-01-08 17:37:10 +00002705bool HNewInstance::IsStringAlloc() const {
2706 ScopedObjectAccess soa(Thread::Current());
2707 return GetReferenceTypeInfo().IsStringClass();
2708}
2709
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002710bool HInvoke::NeedsEnvironment() const {
2711 if (!IsIntrinsic()) {
2712 return true;
2713 }
2714 IntrinsicOptimizations opt(*this);
2715 return !opt.GetDoesNotNeedEnvironment();
2716}
2717
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002718const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2719 ArtMethod* caller = GetEnvironment()->GetMethod();
2720 ScopedObjectAccess soa(Thread::Current());
2721 // `caller` is null for a top-level graph representing a method whose declaring
2722 // class was not resolved.
2723 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2724}
2725
Vladimir Markodc151b22015-10-15 18:02:30 +01002726bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002727 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002728 return false;
2729 }
2730 if (!IsIntrinsic()) {
2731 return true;
2732 }
2733 IntrinsicOptimizations opt(*this);
2734 return !opt.GetDoesNotNeedDexCache();
2735}
2736
Vladimir Markof64242a2015-12-01 14:58:23 +00002737std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2738 switch (rhs) {
2739 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002740 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002741 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002742 return os << "Recursive";
2743 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2744 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002745 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002746 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002747 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2748 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002749 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2750 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002751 default:
2752 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2753 UNREACHABLE();
2754 }
2755}
2756
Vladimir Markofbb184a2015-11-13 14:47:00 +00002757std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2758 switch (rhs) {
2759 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2760 return os << "explicit";
2761 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2762 return os << "implicit";
2763 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2764 return os << "none";
2765 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002766 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2767 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002768 }
2769}
2770
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002771bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2772 const HLoadClass* other_load_class = other->AsLoadClass();
2773 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2774 // names rather than type indexes. However, we shall also have to re-think the hash code.
2775 if (type_index_ != other_load_class->type_index_ ||
2776 GetPackedFields() != other_load_class->GetPackedFields()) {
2777 return false;
2778 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002779 switch (GetLoadKind()) {
2780 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002781 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002782 case LoadKind::kJitTableAddress: {
2783 ScopedObjectAccess soa(Thread::Current());
2784 return GetClass().Get() == other_load_class->GetClass().Get();
2785 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002786 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002787 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002788 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002789 }
2790}
2791
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002792void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002793 SetPackedField<LoadKindField>(load_kind);
2794
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002795 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002796 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002797 RemoveAsUserOfInput(0u);
2798 SetRawInputAt(0u, nullptr);
2799 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002800
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002801 if (!NeedsEnvironment()) {
2802 RemoveEnvironment();
2803 SetSideEffects(SideEffects::None());
2804 }
2805}
2806
2807std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2808 switch (rhs) {
2809 case HLoadClass::LoadKind::kReferrersClass:
2810 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002811 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2812 return os << "BootImageLinkTimePcRelative";
2813 case HLoadClass::LoadKind::kBootImageAddress:
2814 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002815 case HLoadClass::LoadKind::kBootImageClassTable:
2816 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002817 case HLoadClass::LoadKind::kBssEntry:
2818 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002819 case HLoadClass::LoadKind::kJitTableAddress:
2820 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002821 case HLoadClass::LoadKind::kRuntimeCall:
2822 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002823 default:
2824 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2825 UNREACHABLE();
2826 }
2827}
2828
Vladimir Marko372f10e2016-05-17 16:30:10 +01002829bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2830 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002831 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2832 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002833 if (string_index_ != other_load_string->string_index_ ||
2834 GetPackedFields() != other_load_string->GetPackedFields()) {
2835 return false;
2836 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002837 switch (GetLoadKind()) {
2838 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002839 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002840 case LoadKind::kJitTableAddress: {
2841 ScopedObjectAccess soa(Thread::Current());
2842 return GetString().Get() == other_load_string->GetString().Get();
2843 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002844 default:
2845 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002846 }
2847}
2848
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002849void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002850 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002851 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002852 SetPackedField<LoadKindField>(load_kind);
2853
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002854 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002855 RemoveAsUserOfInput(0u);
2856 SetRawInputAt(0u, nullptr);
2857 }
2858 if (!NeedsEnvironment()) {
2859 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002860 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002861 }
2862}
2863
2864std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2865 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002866 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2867 return os << "BootImageLinkTimePcRelative";
2868 case HLoadString::LoadKind::kBootImageAddress:
2869 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002870 case HLoadString::LoadKind::kBootImageInternTable:
2871 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002872 case HLoadString::LoadKind::kBssEntry:
2873 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002874 case HLoadString::LoadKind::kJitTableAddress:
2875 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002876 case HLoadString::LoadKind::kRuntimeCall:
2877 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002878 default:
2879 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2880 UNREACHABLE();
2881 }
2882}
2883
Mark Mendellc4701932015-04-10 13:18:51 -04002884void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002885 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2886 HEnvironment* user = use.GetUser();
2887 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002888 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002889 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002890}
2891
Roland Levillainc9b21f82016-03-23 16:36:59 +00002892// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002893HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01002894 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05002895
2896 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002897 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05002898 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2899 HInstruction* lhs = cond->InputAt(0);
2900 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002901 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002902 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2903 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2904 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2905 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2906 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2907 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2908 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2909 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2910 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2911 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2912 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002913 default:
2914 LOG(FATAL) << "Unexpected condition";
2915 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002916 }
2917 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2918 return replacement;
2919 } else if (cond->IsIntConstant()) {
2920 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002921 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002922 return GetIntConstant(1);
2923 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002924 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002925 return GetIntConstant(0);
2926 }
2927 } else {
2928 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2929 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2930 return replacement;
2931 }
2932}
2933
Roland Levillainc9285912015-12-18 10:38:42 +00002934std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2935 os << "["
2936 << " source=" << rhs.GetSource()
2937 << " destination=" << rhs.GetDestination()
2938 << " type=" << rhs.GetType()
2939 << " instruction=";
2940 if (rhs.GetInstruction() != nullptr) {
2941 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2942 } else {
2943 os << "null";
2944 }
2945 os << " ]";
2946 return os;
2947}
2948
Roland Levillain86503782016-02-11 19:07:30 +00002949std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2950 switch (rhs) {
2951 case TypeCheckKind::kUnresolvedCheck:
2952 return os << "unresolved_check";
2953 case TypeCheckKind::kExactCheck:
2954 return os << "exact_check";
2955 case TypeCheckKind::kClassHierarchyCheck:
2956 return os << "class_hierarchy_check";
2957 case TypeCheckKind::kAbstractClassCheck:
2958 return os << "abstract_class_check";
2959 case TypeCheckKind::kInterfaceCheck:
2960 return os << "interface_check";
2961 case TypeCheckKind::kArrayObjectCheck:
2962 return os << "array_object_check";
2963 case TypeCheckKind::kArrayCheck:
2964 return os << "array_check";
2965 default:
2966 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2967 UNREACHABLE();
2968 }
2969}
2970
Andreas Gampe26de38b2016-07-27 17:53:11 -07002971std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2972 switch (kind) {
2973 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002974 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002975 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002976 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002977 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002978 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002979 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002980 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002981 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002982 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002983
2984 default:
2985 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2986 UNREACHABLE();
2987 }
2988}
2989
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002990} // namespace art