blob: 689991010e2b35b63a1ca36cabd6a7ce7989d1f7 [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"
21#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040022#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000023#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010024#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010025#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010027#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010029#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Vladimir Markocac5a7e2016-02-22 10:39:50 +000093static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010094 for (HEnvironment* environment = instruction->GetEnvironment();
95 environment != nullptr;
96 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000097 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000098 if (environment->GetInstructionAt(i) != nullptr) {
99 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000100 }
101 }
102 }
103}
104
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000105static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100106 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000107 RemoveEnvironmentUses(instruction);
108}
109
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100113 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000114 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100115 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
117 RemoveAsUser(it.Current());
118 }
119 }
120 }
121}
122
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100123void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100124 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000125 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100126 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000127 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100128 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000129 for (HBasicBlock* successor : block->GetSuccessors()) {
130 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000131 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100132 // Remove the block from the list of blocks, so that further analyses
133 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100134 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600135 if (block->IsExitBlock()) {
136 SetExitBlock(nullptr);
137 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000138 // Mark the block as removed. This is used by the HGraphBuilder to discard
139 // the block as a branch target.
140 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 }
142 }
143}
144
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000145GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000146 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147
David Brazdil86ea7ee2016-02-16 09:26:07 +0000148 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000149 FindBackEdges(&visited);
150
David Brazdil86ea7ee2016-02-16 09:26:07 +0000151 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000152 // the initial DFS as users from other instructions, so that
153 // users can be safely removed before uses later.
154 RemoveInstructionsAsUsersFromDeadBlocks(visited);
155
David Brazdil86ea7ee2016-02-16 09:26:07 +0000156 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000158 // predecessors list of live blocks.
159 RemoveDeadBlocks(visited);
160
David Brazdil86ea7ee2016-02-16 09:26:07 +0000161 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 // dominators and the reverse post order.
163 SimplifyCFG();
164
David Brazdil86ea7ee2016-02-16 09:26:07 +0000165 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100166 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000169 // set the loop information on each block.
170 GraphAnalysisResult result = AnalyzeLoops();
171 if (result != kAnalysisSuccess) {
172 return result;
173 }
174
David Brazdil86ea7ee2016-02-16 09:26:07 +0000175 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000176 // which needs the information to build catch block phis from values of
177 // locals at throwing instructions inside try blocks.
178 ComputeTryBlockInformation();
179
180 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100181}
182
183void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100184 for (HBasicBlock* block : GetReversePostOrder()) {
185 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100186 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100187 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100188}
189
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000190void HGraph::ClearLoopInformation() {
191 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100192 for (HBasicBlock* block : GetReversePostOrder()) {
193 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000194 }
195}
196
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100197void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000198 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100199 dominator_ = nullptr;
200}
201
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000202HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
203 HInstruction* instruction = GetFirstInstruction();
204 while (instruction->IsParallelMove()) {
205 instruction = instruction->GetNext();
206 }
207 return instruction;
208}
209
David Brazdil3f4a5222016-05-06 12:46:21 +0100210static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
211 DCHECK(ContainsElement(block->GetSuccessors(), successor));
212
213 HBasicBlock* old_dominator = successor->GetDominator();
214 HBasicBlock* new_dominator =
215 (old_dominator == nullptr) ? block
216 : CommonDominator::ForPair(old_dominator, block);
217
218 if (old_dominator == new_dominator) {
219 return false;
220 } else {
221 successor->SetDominator(new_dominator);
222 return true;
223 }
224}
225
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 DCHECK(reverse_post_order_.empty());
228 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100229 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100230
231 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100232 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100233 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100234 ArenaVector<size_t> successors_visited(blocks_.size(),
235 0u,
236 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100238 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100239 constexpr size_t kDefaultWorklistSize = 8;
240 worklist.reserve(kDefaultWorklistSize);
241 worklist.push_back(entry_block_);
242
243 while (!worklist.empty()) {
244 HBasicBlock* current = worklist.back();
245 uint32_t current_id = current->GetBlockId();
246 if (successors_visited[current_id] == current->GetSuccessors().size()) {
247 worklist.pop_back();
248 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100249 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100250 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100251
252 // Once all the forward edges have been visited, we know the immediate
253 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100254 if (++visits[successor->GetBlockId()] ==
255 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100256 reverse_post_order_.push_back(successor);
257 worklist.push_back(successor);
258 }
259 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000260 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000261
David Brazdil3f4a5222016-05-06 12:46:21 +0100262 // Check if the graph has back edges not dominated by their respective headers.
263 // If so, we need to update the dominators of those headers and recursively of
264 // their successors. We do that with a fix-point iteration over all blocks.
265 // The algorithm is guaranteed to terminate because it loops only if the sum
266 // of all dominator chains has decreased in the current iteration.
267 bool must_run_fix_point = false;
268 for (HBasicBlock* block : blocks_) {
269 if (block != nullptr &&
270 block->IsLoopHeader() &&
271 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
272 must_run_fix_point = true;
273 break;
274 }
275 }
276 if (must_run_fix_point) {
277 bool update_occurred = true;
278 while (update_occurred) {
279 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100280 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100281 for (HBasicBlock* successor : block->GetSuccessors()) {
282 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
283 }
284 }
285 }
286 }
287
288 // Make sure that there are no remaining blocks whose dominator information
289 // needs to be updated.
290 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100291 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 for (HBasicBlock* successor : block->GetSuccessors()) {
293 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
294 }
295 }
296 }
297
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000298 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000299 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100300 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301 if (!block->IsEntryBlock()) {
302 block->GetDominator()->AddDominatedBlock(block);
303 }
304 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000305}
306
David Brazdilfc6a86a2015-06-26 10:33:45 +0000307HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000308 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
309 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000310 // Use `InsertBetween` to ensure the predecessor index and successor index of
311 // `block` and `successor` are preserved.
312 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000313 return new_block;
314}
315
316void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
317 // Insert a new node between `block` and `successor` to split the
318 // critical edge.
319 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600320 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100321 if (successor->IsLoopHeader()) {
322 // If we split at a back edge boundary, make the new block the back edge.
323 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000324 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 info->RemoveBackEdge(block);
326 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100327 }
328 }
329}
330
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100331void HGraph::SimplifyLoop(HBasicBlock* header) {
332 HLoopInformation* info = header->GetLoopInformation();
333
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100334 // Make sure the loop has only one pre header. This simplifies SSA building by having
335 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000336 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
337 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000338 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000339 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100340 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100341 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600342 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100343
Vladimir Marko60584552015-09-03 13:35:12 +0000344 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100345 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100346 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100347 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100348 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100349 }
350 }
351 pre_header->AddSuccessor(header);
352 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100353
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100354 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100355 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
356 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000357 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100358 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100359 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000360 header->predecessors_[pred] = to_swap;
361 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100362 break;
363 }
364 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100365 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100366
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100367 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000368 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
369 // Called from DeadBlockElimination. Update SuspendCheck pointer.
370 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100371 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100372}
373
David Brazdilffee3d32015-07-06 11:48:53 +0100374void HGraph::ComputeTryBlockInformation() {
375 // Iterate in reverse post order to propagate try membership information from
376 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100377 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100378 if (block->IsEntryBlock() || block->IsCatchBlock()) {
379 // Catch blocks after simplification have only exceptional predecessors
380 // and hence are never in tries.
381 continue;
382 }
383
384 // Infer try membership from the first predecessor. Having simplified loops,
385 // the first predecessor can never be a back edge and therefore it must have
386 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100387 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100388 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100389 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000390 if (try_entry != nullptr &&
391 (block->GetTryCatchInformation() == nullptr ||
392 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
393 // We are either setting try block membership for the first time or it
394 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100395 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
396 }
David Brazdilffee3d32015-07-06 11:48:53 +0100397 }
398}
399
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000401// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000403 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100404 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
405 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
406 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
407 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100408 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000409 if (block->GetSuccessors().size() > 1) {
410 // Only split normal-flow edges. We cannot split exceptional edges as they
411 // are synthesized (approximate real control flow), and we do not need to
412 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000413 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
414 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
415 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100416 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000417 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000418 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
419 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000420 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000421 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100422 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000423 // SplitCriticalEdge could have invalidated the `normal_successors`
424 // ArrayRef. We must re-acquire it.
425 normal_successors = block->GetNormalSuccessors();
426 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
427 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100428 }
429 }
430 }
431 if (block->IsLoopHeader()) {
432 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000433 } else if (!block->IsEntryBlock() &&
434 block->GetFirstInstruction() != nullptr &&
435 block->GetFirstInstruction()->IsSuspendCheck()) {
436 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000437 // a loop got dismantled. Just remove the suspend check.
438 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100439 }
440 }
441}
442
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000443GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100444 // We iterate post order to ensure we visit inner loops before outer loops.
445 // `PopulateRecursive` needs this guarantee to know whether a natural loop
446 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100447 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100449 if (block->IsCatchBlock()) {
450 // TODO: Dealing with exceptional back edges could be tricky because
451 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000452 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100453 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000454 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 }
456 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000457 return kAnalysisSuccess;
458}
459
460void HLoopInformation::Dump(std::ostream& os) {
461 os << "header: " << header_->GetBlockId() << std::endl;
462 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
463 for (HBasicBlock* block : back_edges_) {
464 os << "back edge: " << block->GetBlockId() << std::endl;
465 }
466 for (HBasicBlock* block : header_->GetPredecessors()) {
467 os << "predecessor: " << block->GetBlockId() << std::endl;
468 }
469 for (uint32_t idx : blocks_.Indexes()) {
470 os << " in loop: " << idx << std::endl;
471 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100472}
473
David Brazdil8d5b8b22015-03-24 10:51:52 +0000474void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000475 // New constants are inserted before the SuspendCheck at the bottom of the
476 // entry block. Note that this method can be called from the graph builder and
477 // the entry block therefore may not end with SuspendCheck->Goto yet.
478 HInstruction* insert_before = nullptr;
479
480 HInstruction* gota = entry_block_->GetLastInstruction();
481 if (gota != nullptr && gota->IsGoto()) {
482 HInstruction* suspend_check = gota->GetPrevious();
483 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
484 insert_before = suspend_check;
485 } else {
486 insert_before = gota;
487 }
488 }
489
490 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000491 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000492 } else {
493 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000494 }
495}
496
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600497HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100498 // For simplicity, don't bother reviving the cached null constant if it is
499 // not null and not in a block. Otherwise, we need to clear the instruction
500 // id and/or any invariants the graph is assuming when adding new instructions.
501 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600502 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000503 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000505 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000506 if (kIsDebugBuild) {
507 ScopedObjectAccess soa(Thread::Current());
508 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
509 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000510 return cached_null_constant_;
511}
512
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100513HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100514 // For simplicity, don't bother reviving the cached current method if it is
515 // not null and not in a block. Otherwise, we need to clear the instruction
516 // id and/or any invariants the graph is assuming when adding new instructions.
517 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600519 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
520 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100521 if (entry_block_->GetFirstInstruction() == nullptr) {
522 entry_block_->AddInstruction(cached_current_method_);
523 } else {
524 entry_block_->InsertInstructionBefore(
525 cached_current_method_, entry_block_->GetFirstInstruction());
526 }
527 }
528 return cached_current_method_;
529}
530
Igor Murashkind01745e2017-04-05 16:40:31 -0700531const char* HGraph::GetMethodName() const {
532 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
533 return dex_file_.GetMethodName(method_id);
534}
535
536std::string HGraph::PrettyMethod(bool with_signature) const {
537 return dex_file_.PrettyMethod(method_idx_, with_signature);
538}
539
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600540HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000541 switch (type) {
542 case Primitive::Type::kPrimBoolean:
543 DCHECK(IsUint<1>(value));
544 FALLTHROUGH_INTENDED;
545 case Primitive::Type::kPrimByte:
546 case Primitive::Type::kPrimChar:
547 case Primitive::Type::kPrimShort:
548 case Primitive::Type::kPrimInt:
549 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600550 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000551
552 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600553 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000554
555 default:
556 LOG(FATAL) << "Unsupported constant type";
557 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000558 }
David Brazdil46e2a392015-03-16 17:31:52 +0000559}
560
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000561void HGraph::CacheFloatConstant(HFloatConstant* constant) {
562 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
563 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
564 cached_float_constants_.Overwrite(value, constant);
565}
566
567void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
568 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
569 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
570 cached_double_constants_.Overwrite(value, constant);
571}
572
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000573void HLoopInformation::Add(HBasicBlock* block) {
574 blocks_.SetBit(block->GetBlockId());
575}
576
David Brazdil46e2a392015-03-16 17:31:52 +0000577void HLoopInformation::Remove(HBasicBlock* block) {
578 blocks_.ClearBit(block->GetBlockId());
579}
580
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100581void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
582 if (blocks_.IsBitSet(block->GetBlockId())) {
583 return;
584 }
585
586 blocks_.SetBit(block->GetBlockId());
587 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100588 if (block->IsLoopHeader()) {
589 // We're visiting loops in post-order, so inner loops must have been
590 // populated already.
591 DCHECK(block->GetLoopInformation()->IsPopulated());
592 if (block->GetLoopInformation()->IsIrreducible()) {
593 contains_irreducible_loop_ = true;
594 }
595 }
Vladimir Marko60584552015-09-03 13:35:12 +0000596 for (HBasicBlock* predecessor : block->GetPredecessors()) {
597 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100598 }
599}
600
David Brazdilc2e8af92016-04-05 17:15:19 +0100601void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
602 size_t block_id = block->GetBlockId();
603
604 // If `block` is in `finalized`, we know its membership in the loop has been
605 // decided and it does not need to be revisited.
606 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000607 return;
608 }
609
David Brazdilc2e8af92016-04-05 17:15:19 +0100610 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 if (block->IsLoopHeader()) {
612 // If we hit a loop header in an irreducible loop, we first check if the
613 // pre header of that loop belongs to the currently analyzed loop. If it does,
614 // then we visit the back edges.
615 // Note that we cannot use GetPreHeader, as the loop may have not been populated
616 // yet.
617 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100618 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000620 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100621 blocks_.SetBit(block_id);
622 finalized->SetBit(block_id);
623 is_finalized = true;
624
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000625 HLoopInformation* info = block->GetLoopInformation();
626 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100627 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000628 }
629 }
630 } else {
631 // Visit all predecessors. If one predecessor is part of the loop, this
632 // block is also part of this loop.
633 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100634 PopulateIrreducibleRecursive(predecessor, finalized);
635 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000636 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100637 blocks_.SetBit(block_id);
638 finalized->SetBit(block_id);
639 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000640 }
641 }
642 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100643
644 // All predecessors have been recursively visited. Mark finalized if not marked yet.
645 if (!is_finalized) {
646 finalized->SetBit(block_id);
647 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000648}
649
650void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100651 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000652 // Populate this loop: starting with the back edge, recursively add predecessors
653 // that are not already part of that loop. Set the header as part of the loop
654 // to end the recursion.
655 // This is a recursive implementation of the algorithm described in
656 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100657 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000658 blocks_.SetBit(header_->GetBlockId());
659 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100660
David Brazdil3f4a5222016-05-06 12:46:21 +0100661 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100662
663 if (is_irreducible_loop) {
664 ArenaBitVector visited(graph->GetArena(),
665 graph->GetBlocks().size(),
666 /* expandable */ false,
667 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100668 // Stop marking blocks at the loop header.
669 visited.SetBit(header_->GetBlockId());
670
David Brazdilc2e8af92016-04-05 17:15:19 +0100671 for (HBasicBlock* back_edge : GetBackEdges()) {
672 PopulateIrreducibleRecursive(back_edge, &visited);
673 }
674 } else {
675 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000676 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100677 }
David Brazdila4b8c212015-05-07 09:59:30 +0100678 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100679
Vladimir Markofd66c502016-04-18 15:37:01 +0100680 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
681 // When compiling in OSR mode, all loops in the compiled method may be entered
682 // from the interpreter. We treat this OSR entry point just like an extra entry
683 // to an irreducible loop, so we need to mark the method's loops as irreducible.
684 // This does not apply to inlined loops which do not act as OSR entry points.
685 if (suspend_check_ == nullptr) {
686 // Just building the graph in OSR mode, this loop is not inlined. We never build an
687 // inner graph in OSR mode as we can do OSR transition only from the outer method.
688 is_irreducible_loop = true;
689 } else {
690 // Look at the suspend check's environment to determine if the loop was inlined.
691 DCHECK(suspend_check_->HasEnvironment());
692 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
693 is_irreducible_loop = true;
694 }
695 }
696 }
697 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100698 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100699 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100700 graph->SetHasIrreducibleLoops(true);
701 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800702 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100703}
704
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100705HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000706 HBasicBlock* block = header_->GetPredecessors()[0];
707 DCHECK(irreducible_ || (block == header_->GetDominator()));
708 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100709}
710
711bool HLoopInformation::Contains(const HBasicBlock& block) const {
712 return blocks_.IsBitSet(block.GetBlockId());
713}
714
715bool HLoopInformation::IsIn(const HLoopInformation& other) const {
716 return other.blocks_.IsBitSet(header_->GetBlockId());
717}
718
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800719bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
720 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700721}
722
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100723size_t HLoopInformation::GetLifetimeEnd() const {
724 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100725 for (HBasicBlock* back_edge : GetBackEdges()) {
726 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100727 }
728 return last_position;
729}
730
David Brazdil3f4a5222016-05-06 12:46:21 +0100731bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
732 for (HBasicBlock* back_edge : GetBackEdges()) {
733 DCHECK(back_edge->GetDominator() != nullptr);
734 if (!header_->Dominates(back_edge)) {
735 return true;
736 }
737 }
738 return false;
739}
740
Anton Shaminf89381f2016-05-16 16:44:13 +0600741bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
742 for (HBasicBlock* back_edge : GetBackEdges()) {
743 if (!block->Dominates(back_edge)) {
744 return false;
745 }
746 }
747 return true;
748}
749
David Sehrc757dec2016-11-04 15:48:34 -0700750
751bool HLoopInformation::HasExitEdge() const {
752 // Determine if this loop has at least one exit edge.
753 HBlocksInLoopReversePostOrderIterator it_loop(*this);
754 for (; !it_loop.Done(); it_loop.Advance()) {
755 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
756 if (!Contains(*successor)) {
757 return true;
758 }
759 }
760 }
761 return false;
762}
763
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100764bool HBasicBlock::Dominates(HBasicBlock* other) const {
765 // Walk up the dominator tree from `other`, to find out if `this`
766 // is an ancestor.
767 HBasicBlock* current = other;
768 while (current != nullptr) {
769 if (current == this) {
770 return true;
771 }
772 current = current->GetDominator();
773 }
774 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100775}
776
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100777static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100778 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100779 for (size_t i = 0; i < inputs.size(); ++i) {
780 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100781 }
782 // Environment should be created later.
783 DCHECK(!instruction->HasEnvironment());
784}
785
Roland Levillainccc07a92014-09-16 14:48:16 +0100786void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
787 HInstruction* replacement) {
788 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400789 if (initial->IsControlFlow()) {
790 // We can only replace a control flow instruction with another control flow instruction.
791 DCHECK(replacement->IsControlFlow());
792 DCHECK_EQ(replacement->GetId(), -1);
793 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
794 DCHECK_EQ(initial->GetBlock(), this);
795 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100796 DCHECK(initial->GetUses().empty());
797 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400798 replacement->SetBlock(this);
799 replacement->SetId(GetGraph()->GetNextInstructionId());
800 instructions_.InsertInstructionBefore(replacement, initial);
801 UpdateInputsUsers(replacement);
802 } else {
803 InsertInstructionBefore(replacement, initial);
804 initial->ReplaceWith(replacement);
805 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100806 RemoveInstruction(initial);
807}
808
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100809static void Add(HInstructionList* instruction_list,
810 HBasicBlock* block,
811 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000812 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000813 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100814 instruction->SetBlock(block);
815 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100816 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100817 instruction_list->AddInstruction(instruction);
818}
819
820void HBasicBlock::AddInstruction(HInstruction* instruction) {
821 Add(&instructions_, this, instruction);
822}
823
824void HBasicBlock::AddPhi(HPhi* phi) {
825 Add(&phis_, this, phi);
826}
827
David Brazdilc3d743f2015-04-22 13:40:50 +0100828void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
829 DCHECK(!cursor->IsPhi());
830 DCHECK(!instruction->IsPhi());
831 DCHECK_EQ(instruction->GetId(), -1);
832 DCHECK_NE(cursor->GetId(), -1);
833 DCHECK_EQ(cursor->GetBlock(), this);
834 DCHECK(!instruction->IsControlFlow());
835 instruction->SetBlock(this);
836 instruction->SetId(GetGraph()->GetNextInstructionId());
837 UpdateInputsUsers(instruction);
838 instructions_.InsertInstructionBefore(instruction, cursor);
839}
840
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100841void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
842 DCHECK(!cursor->IsPhi());
843 DCHECK(!instruction->IsPhi());
844 DCHECK_EQ(instruction->GetId(), -1);
845 DCHECK_NE(cursor->GetId(), -1);
846 DCHECK_EQ(cursor->GetBlock(), this);
847 DCHECK(!instruction->IsControlFlow());
848 DCHECK(!cursor->IsControlFlow());
849 instruction->SetBlock(this);
850 instruction->SetId(GetGraph()->GetNextInstructionId());
851 UpdateInputsUsers(instruction);
852 instructions_.InsertInstructionAfter(instruction, cursor);
853}
854
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100855void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
856 DCHECK_EQ(phi->GetId(), -1);
857 DCHECK_NE(cursor->GetId(), -1);
858 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100859 phi->SetBlock(this);
860 phi->SetId(GetGraph()->GetNextInstructionId());
861 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100862 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100863}
864
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865static void Remove(HInstructionList* instruction_list,
866 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000867 HInstruction* instruction,
868 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100869 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870 instruction->SetBlock(nullptr);
871 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000872 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100873 DCHECK(instruction->GetUses().empty());
874 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000875 RemoveAsUser(instruction);
876 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100877}
878
David Brazdil1abb4192015-02-17 18:33:36 +0000879void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100880 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000881 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100882}
883
David Brazdil1abb4192015-02-17 18:33:36 +0000884void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
885 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100886}
887
David Brazdilc7508e92015-04-27 13:28:57 +0100888void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
889 if (instruction->IsPhi()) {
890 RemovePhi(instruction->AsPhi(), ensure_safety);
891 } else {
892 RemoveInstruction(instruction, ensure_safety);
893 }
894}
895
Vladimir Marko71bf8092015-09-15 15:33:14 +0100896void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
897 for (size_t i = 0; i < locals.size(); i++) {
898 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100899 SetRawEnvAt(i, instruction);
900 if (instruction != nullptr) {
901 instruction->AddEnvUseAt(this, i);
902 }
903 }
904}
905
David Brazdiled596192015-01-23 10:39:45 +0000906void HEnvironment::CopyFrom(HEnvironment* env) {
907 for (size_t i = 0; i < env->Size(); i++) {
908 HInstruction* instruction = env->GetInstructionAt(i);
909 SetRawEnvAt(i, instruction);
910 if (instruction != nullptr) {
911 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100912 }
David Brazdiled596192015-01-23 10:39:45 +0000913 }
914}
915
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700916void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
917 HBasicBlock* loop_header) {
918 DCHECK(loop_header->IsLoopHeader());
919 for (size_t i = 0; i < env->Size(); i++) {
920 HInstruction* instruction = env->GetInstructionAt(i);
921 SetRawEnvAt(i, instruction);
922 if (instruction == nullptr) {
923 continue;
924 }
925 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
926 // At the end of the loop pre-header, the corresponding value for instruction
927 // is the first input of the phi.
928 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700929 SetRawEnvAt(i, initial);
930 initial->AddEnvUseAt(this, i);
931 } else {
932 instruction->AddEnvUseAt(this, i);
933 }
934 }
935}
936
David Brazdil1abb4192015-02-17 18:33:36 +0000937void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100938 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
939 HInstruction* user = env_use.GetInstruction();
940 auto before_env_use_node = env_use.GetBeforeUseNode();
941 user->env_uses_.erase_after(before_env_use_node);
942 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100943}
944
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000945HInstruction::InstructionKind HInstruction::GetKind() const {
946 return GetKindInternal();
947}
948
Calin Juravle77520bc2015-01-12 18:45:46 +0000949HInstruction* HInstruction::GetNextDisregardingMoves() const {
950 HInstruction* next = GetNext();
951 while (next != nullptr && next->IsParallelMove()) {
952 next = next->GetNext();
953 }
954 return next;
955}
956
957HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
958 HInstruction* previous = GetPrevious();
959 while (previous != nullptr && previous->IsParallelMove()) {
960 previous = previous->GetPrevious();
961 }
962 return previous;
963}
964
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100965void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000966 if (first_instruction_ == nullptr) {
967 DCHECK(last_instruction_ == nullptr);
968 first_instruction_ = last_instruction_ = instruction;
969 } else {
970 last_instruction_->next_ = instruction;
971 instruction->previous_ = last_instruction_;
972 last_instruction_ = instruction;
973 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000974}
975
David Brazdilc3d743f2015-04-22 13:40:50 +0100976void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
977 DCHECK(Contains(cursor));
978 if (cursor == first_instruction_) {
979 cursor->previous_ = instruction;
980 instruction->next_ = cursor;
981 first_instruction_ = instruction;
982 } else {
983 instruction->previous_ = cursor->previous_;
984 instruction->next_ = cursor;
985 cursor->previous_ = instruction;
986 instruction->previous_->next_ = instruction;
987 }
988}
989
990void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
991 DCHECK(Contains(cursor));
992 if (cursor == last_instruction_) {
993 cursor->next_ = instruction;
994 instruction->previous_ = cursor;
995 last_instruction_ = instruction;
996 } else {
997 instruction->next_ = cursor->next_;
998 instruction->previous_ = cursor;
999 cursor->next_ = instruction;
1000 instruction->next_->previous_ = instruction;
1001 }
1002}
1003
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001004void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1005 if (instruction->previous_ != nullptr) {
1006 instruction->previous_->next_ = instruction->next_;
1007 }
1008 if (instruction->next_ != nullptr) {
1009 instruction->next_->previous_ = instruction->previous_;
1010 }
1011 if (instruction == first_instruction_) {
1012 first_instruction_ = instruction->next_;
1013 }
1014 if (instruction == last_instruction_) {
1015 last_instruction_ = instruction->previous_;
1016 }
1017}
1018
Roland Levillain6b469232014-09-25 10:10:38 +01001019bool HInstructionList::Contains(HInstruction* instruction) const {
1020 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1021 if (it.Current() == instruction) {
1022 return true;
1023 }
1024 }
1025 return false;
1026}
1027
Roland Levillainccc07a92014-09-16 14:48:16 +01001028bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1029 const HInstruction* instruction2) const {
1030 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1031 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1032 if (it.Current() == instruction1) {
1033 return true;
1034 }
1035 if (it.Current() == instruction2) {
1036 return false;
1037 }
1038 }
1039 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1040 return true;
1041}
1042
Roland Levillain6c82d402014-10-13 16:10:27 +01001043bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1044 if (other_instruction == this) {
1045 // An instruction does not strictly dominate itself.
1046 return false;
1047 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001048 HBasicBlock* block = GetBlock();
1049 HBasicBlock* other_block = other_instruction->GetBlock();
1050 if (block != other_block) {
1051 return GetBlock()->Dominates(other_instruction->GetBlock());
1052 } else {
1053 // If both instructions are in the same block, ensure this
1054 // instruction comes before `other_instruction`.
1055 if (IsPhi()) {
1056 if (!other_instruction->IsPhi()) {
1057 // Phis appear before non phi-instructions so this instruction
1058 // dominates `other_instruction`.
1059 return true;
1060 } else {
1061 // There is no order among phis.
1062 LOG(FATAL) << "There is no dominance between phis of a same block.";
1063 return false;
1064 }
1065 } else {
1066 // `this` is not a phi.
1067 if (other_instruction->IsPhi()) {
1068 // Phis appear before non phi-instructions so this instruction
1069 // does not dominate `other_instruction`.
1070 return false;
1071 } else {
1072 // Check whether this instruction comes before
1073 // `other_instruction` in the instruction list.
1074 return block->GetInstructions().FoundBefore(this, other_instruction);
1075 }
1076 }
1077 }
1078}
1079
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001080void HInstruction::RemoveEnvironment() {
1081 RemoveEnvironmentUses(this);
1082 environment_ = nullptr;
1083}
1084
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001085void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001086 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001087 // Note: fixup_end remains valid across splice_after().
1088 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1089 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1090 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001091
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001092 // Note: env_fixup_end remains valid across splice_after().
1093 auto env_fixup_end =
1094 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1095 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1096 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001097
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001098 DCHECK(uses_.empty());
1099 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001100}
1101
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001102void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1103 const HUseList<HInstruction*>& uses = GetUses();
1104 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1105 HInstruction* user = it->GetUser();
1106 size_t index = it->GetIndex();
1107 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1108 ++it;
1109 if (dominator->StrictlyDominates(user)) {
1110 user->ReplaceInput(replacement, index);
1111 }
1112 }
1113}
1114
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001115void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001116 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001117 if (input_use.GetInstruction() == replacement) {
1118 // Nothing to do.
1119 return;
1120 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001121 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001122 // Note: fixup_end remains valid across splice_after().
1123 auto fixup_end =
1124 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1125 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1126 input_use.GetInstruction()->uses_,
1127 before_use_node);
1128 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1129 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001130}
1131
Nicolas Geoffray39468442014-09-02 15:17:15 +01001132size_t HInstruction::EnvironmentSize() const {
1133 return HasEnvironment() ? environment_->Size() : 0;
1134}
1135
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001136void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001137 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001138 inputs_.push_back(HUserRecord<HInstruction*>(input));
1139 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001140}
1141
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001142void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1143 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1144 input->AddUseAt(this, index);
1145 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1146 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1147 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1148 inputs_[i].GetUseNode()->SetIndex(i);
1149 }
1150}
1151
1152void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001153 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001154 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001155 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1156 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1157 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1158 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001159 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001160}
1161
Igor Murashkind01745e2017-04-05 16:40:31 -07001162void HVariableInputSizeInstruction::RemoveAllInputs() {
1163 RemoveAsUserOfAllInputs();
1164 DCHECK(!HasNonEnvironmentUses());
1165
1166 inputs_.clear();
1167 DCHECK_EQ(0u, InputCount());
1168}
1169
1170void HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
1171 DCHECK(instruction->GetBlock() != nullptr);
1172 // Removing constructor fences only makes sense for instructions with an object return type.
1173 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1174
1175 // Efficient implementation that simultaneously (in one pass):
1176 // * Scans the uses list for all constructor fences.
1177 // * Deletes that constructor fence from the uses list of `instruction`.
1178 // * Deletes `instruction` from the constructor fence's inputs.
1179 // * Deletes the constructor fence if it now has 0 inputs.
1180
1181 const HUseList<HInstruction*>& uses = instruction->GetUses();
1182 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1183 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1184 const HUseListNode<HInstruction*>& use_node = *it;
1185 HInstruction* const use_instruction = use_node.GetUser();
1186
1187 // Advance the iterator immediately once we fetch the use_node.
1188 // Warning: If the input is removed, the current iterator becomes invalid.
1189 ++it;
1190
1191 if (use_instruction->IsConstructorFence()) {
1192 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1193 size_t input_index = use_node.GetIndex();
1194
1195 // Process the candidate instruction for removal
1196 // from the graph.
1197
1198 // Constructor fence instructions are never
1199 // used by other instructions.
1200 //
1201 // If we wanted to make this more generic, it
1202 // could be a runtime if statement.
1203 DCHECK(!ctor_fence->HasUses());
1204
1205 // A constructor fence's return type is "kPrimVoid"
1206 // and therefore it can't have any environment uses.
1207 DCHECK(!ctor_fence->HasEnvironmentUses());
1208
1209 // Remove the inputs first, otherwise removing the instruction
1210 // will try to remove its uses while we are already removing uses
1211 // and this operation will fail.
1212 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1213
1214 // Removing the input will also remove the `use_node`.
1215 // (Do not look at `use_node` after this, it will be a dangling reference).
1216 ctor_fence->RemoveInputAt(input_index);
1217
1218 // Once all inputs are removed, the fence is considered dead and
1219 // is removed.
1220 if (ctor_fence->InputCount() == 0u) {
1221 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
1222 }
1223 }
1224 }
1225
1226 if (kIsDebugBuild) {
1227 // Post-condition checks:
1228 // * None of the uses of `instruction` are a constructor fence.
1229 // * The `instruction` itself did not get removed from a block.
1230 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1231 CHECK(!use_node.GetUser()->IsConstructorFence());
1232 }
1233 CHECK(instruction->GetBlock() != nullptr);
1234 }
1235}
1236
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001237HInstruction* HConstructorFence::GetAssociatedAllocation() {
1238 HInstruction* new_instance_inst = GetPrevious();
1239 // Check if the immediately preceding instruction is a new-instance/new-array.
1240 // Otherwise this fence is for protecting final fields.
1241 if (new_instance_inst != nullptr &&
1242 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1243 // TODO: Need to update this code to handle multiple inputs.
1244 DCHECK_EQ(InputCount(), 1u);
1245 return new_instance_inst;
1246 } else {
1247 return nullptr;
1248 }
1249}
1250
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001251#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001252void H##name::Accept(HGraphVisitor* visitor) { \
1253 visitor->Visit##name(this); \
1254}
1255
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001256FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001257
1258#undef DEFINE_ACCEPT
1259
1260void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001261 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1262 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001263 if (block != nullptr) {
1264 VisitBasicBlock(block);
1265 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001266 }
1267}
1268
Roland Levillain633021e2014-10-01 14:12:25 +01001269void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001270 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1271 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001272 }
1273}
1274
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001275void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001276 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001277 it.Current()->Accept(this);
1278 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001279 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001280 it.Current()->Accept(this);
1281 }
1282}
1283
Mark Mendelle82549b2015-05-06 10:55:34 -04001284HConstant* HTypeConversion::TryStaticEvaluation() const {
1285 HGraph* graph = GetBlock()->GetGraph();
1286 if (GetInput()->IsIntConstant()) {
1287 int32_t value = GetInput()->AsIntConstant()->GetValue();
1288 switch (GetResultType()) {
1289 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001290 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001291 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001292 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001293 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001294 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001295 default:
1296 return nullptr;
1297 }
1298 } else if (GetInput()->IsLongConstant()) {
1299 int64_t value = GetInput()->AsLongConstant()->GetValue();
1300 switch (GetResultType()) {
1301 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001302 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001303 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001304 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001305 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001306 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001307 default:
1308 return nullptr;
1309 }
1310 } else if (GetInput()->IsFloatConstant()) {
1311 float value = GetInput()->AsFloatConstant()->GetValue();
1312 switch (GetResultType()) {
1313 case Primitive::kPrimInt:
1314 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001315 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001316 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001317 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001318 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001319 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1320 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001321 case Primitive::kPrimLong:
1322 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001323 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001324 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001325 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001326 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001327 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1328 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001329 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001330 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001331 default:
1332 return nullptr;
1333 }
1334 } else if (GetInput()->IsDoubleConstant()) {
1335 double value = GetInput()->AsDoubleConstant()->GetValue();
1336 switch (GetResultType()) {
1337 case Primitive::kPrimInt:
1338 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001339 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001340 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001341 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001342 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001343 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1344 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001345 case Primitive::kPrimLong:
1346 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001347 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001348 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001349 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001350 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001351 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1352 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001353 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001354 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001355 default:
1356 return nullptr;
1357 }
1358 }
1359 return nullptr;
1360}
1361
Roland Levillain9240d6a2014-10-20 16:47:04 +01001362HConstant* HUnaryOperation::TryStaticEvaluation() const {
1363 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001364 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001365 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001366 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001367 } else if (kEnableFloatingPointStaticEvaluation) {
1368 if (GetInput()->IsFloatConstant()) {
1369 return Evaluate(GetInput()->AsFloatConstant());
1370 } else if (GetInput()->IsDoubleConstant()) {
1371 return Evaluate(GetInput()->AsDoubleConstant());
1372 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001373 }
1374 return nullptr;
1375}
1376
1377HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001378 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1379 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001380 } else if (GetLeft()->IsLongConstant()) {
1381 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001382 // The binop(long, int) case is only valid for shifts and rotations.
1383 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001384 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1385 } else if (GetRight()->IsLongConstant()) {
1386 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001387 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001388 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001389 // The binop(null, null) case is only valid for equal and not-equal conditions.
1390 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001391 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001392 } else if (kEnableFloatingPointStaticEvaluation) {
1393 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1394 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1395 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1396 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1397 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001398 }
1399 return nullptr;
1400}
Dave Allison20dfc792014-06-16 20:44:29 -07001401
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001402HConstant* HBinaryOperation::GetConstantRight() const {
1403 if (GetRight()->IsConstant()) {
1404 return GetRight()->AsConstant();
1405 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1406 return GetLeft()->AsConstant();
1407 } else {
1408 return nullptr;
1409 }
1410}
1411
1412// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001413// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001414HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1415 HInstruction* most_constant_right = GetConstantRight();
1416 if (most_constant_right == nullptr) {
1417 return nullptr;
1418 } else if (most_constant_right == GetLeft()) {
1419 return GetRight();
1420 } else {
1421 return GetLeft();
1422 }
1423}
1424
Roland Levillain31dd3d62016-02-16 12:21:02 +00001425std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1426 switch (rhs) {
1427 case ComparisonBias::kNoBias:
1428 return os << "no_bias";
1429 case ComparisonBias::kGtBias:
1430 return os << "gt_bias";
1431 case ComparisonBias::kLtBias:
1432 return os << "lt_bias";
1433 default:
1434 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1435 UNREACHABLE();
1436 }
1437}
1438
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001439bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1440 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001441}
1442
Vladimir Marko372f10e2016-05-17 16:30:10 +01001443bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001444 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001445 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001446 if (!InstructionDataEquals(other)) return false;
1447 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001448 HConstInputsRef inputs = GetInputs();
1449 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001450 if (inputs.size() != other_inputs.size()) return false;
1451 for (size_t i = 0; i != inputs.size(); ++i) {
1452 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001453 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001454
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001455 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001456 return true;
1457}
1458
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001459std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1460#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1461 switch (rhs) {
1462 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1463 default:
1464 os << "Unknown instruction kind " << static_cast<int>(rhs);
1465 break;
1466 }
1467#undef DECLARE_CASE
1468 return os;
1469}
1470
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001471void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1472 if (do_checks) {
1473 DCHECK(!IsPhi());
1474 DCHECK(!IsControlFlow());
1475 DCHECK(CanBeMoved() ||
1476 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1477 IsShouldDeoptimizeFlag());
1478 DCHECK(!cursor->IsPhi());
1479 }
David Brazdild6c205e2016-06-07 14:20:52 +01001480
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001481 next_->previous_ = previous_;
1482 if (previous_ != nullptr) {
1483 previous_->next_ = next_;
1484 }
1485 if (block_->instructions_.first_instruction_ == this) {
1486 block_->instructions_.first_instruction_ = next_;
1487 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001488 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001489
1490 previous_ = cursor->previous_;
1491 if (previous_ != nullptr) {
1492 previous_->next_ = this;
1493 }
1494 next_ = cursor;
1495 cursor->previous_ = this;
1496 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001497
1498 if (block_->instructions_.first_instruction_ == cursor) {
1499 block_->instructions_.first_instruction_ = this;
1500 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001501}
1502
Vladimir Markofb337ea2015-11-25 15:25:10 +00001503void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1504 DCHECK(!CanThrow());
1505 DCHECK(!HasSideEffects());
1506 DCHECK(!HasEnvironmentUses());
1507 DCHECK(HasNonEnvironmentUses());
1508 DCHECK(!IsPhi()); // Makes no sense for Phi.
1509 DCHECK_EQ(InputCount(), 0u);
1510
1511 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001512 auto uses_it = GetUses().begin();
1513 auto uses_end = GetUses().end();
1514 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1515 ++uses_it;
1516 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1517 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001518 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001519 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001520 // This instruction has uses in two or more blocks. Find the common dominator.
1521 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001522 for (; uses_it != uses_end; ++uses_it) {
1523 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001524 }
1525 target_block = finder.Get();
1526 DCHECK(target_block != nullptr);
1527 }
1528 // Move to the first dominator not in a loop.
1529 while (target_block->IsInLoop()) {
1530 target_block = target_block->GetDominator();
1531 DCHECK(target_block != nullptr);
1532 }
1533
1534 // Find insertion position.
1535 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001536 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1537 if (use.GetUser()->GetBlock() == target_block &&
1538 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1539 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001540 }
1541 }
1542 if (insert_pos == nullptr) {
1543 // No user in `target_block`, insert before the control flow instruction.
1544 insert_pos = target_block->GetLastInstruction();
1545 DCHECK(insert_pos->IsControlFlow());
1546 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1547 if (insert_pos->IsIf()) {
1548 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1549 if (if_input == insert_pos->GetPrevious()) {
1550 insert_pos = if_input;
1551 }
1552 }
1553 }
1554 MoveBefore(insert_pos);
1555}
1556
David Brazdilfc6a86a2015-06-26 10:33:45 +00001557HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001558 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001559 DCHECK_EQ(cursor->GetBlock(), this);
1560
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001561 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1562 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001563 new_block->instructions_.first_instruction_ = cursor;
1564 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1565 instructions_.last_instruction_ = cursor->previous_;
1566 if (cursor->previous_ == nullptr) {
1567 instructions_.first_instruction_ = nullptr;
1568 } else {
1569 cursor->previous_->next_ = nullptr;
1570 cursor->previous_ = nullptr;
1571 }
1572
1573 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001574 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001575
Vladimir Marko60584552015-09-03 13:35:12 +00001576 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001577 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001578 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001579 new_block->successors_.swap(successors_);
1580 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001581 AddSuccessor(new_block);
1582
David Brazdil56e1acc2015-06-30 15:41:36 +01001583 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001584 return new_block;
1585}
1586
David Brazdild7558da2015-09-22 13:04:14 +01001587HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001588 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001589 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1590
1591 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1592
1593 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001594 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1595 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001596 new_block->predecessors_.swap(predecessors_);
1597 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001598 AddPredecessor(new_block);
1599
1600 GetGraph()->AddBlock(new_block);
1601 return new_block;
1602}
1603
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001604HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1605 DCHECK_EQ(cursor->GetBlock(), this);
1606
1607 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1608 cursor->GetDexPc());
1609 new_block->instructions_.first_instruction_ = cursor;
1610 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1611 instructions_.last_instruction_ = cursor->previous_;
1612 if (cursor->previous_ == nullptr) {
1613 instructions_.first_instruction_ = nullptr;
1614 } else {
1615 cursor->previous_->next_ = nullptr;
1616 cursor->previous_ = nullptr;
1617 }
1618
1619 new_block->instructions_.SetBlockOfInstructions(new_block);
1620
1621 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001622 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1623 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001624 new_block->successors_.swap(successors_);
1625 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001626
1627 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1628 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001629 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001630 new_block->dominated_blocks_.swap(dominated_blocks_);
1631 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001632 return new_block;
1633}
1634
1635HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001636 DCHECK(!cursor->IsControlFlow());
1637 DCHECK_NE(instructions_.last_instruction_, cursor);
1638 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001639
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001640 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1641 new_block->instructions_.first_instruction_ = cursor->GetNext();
1642 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1643 cursor->next_->previous_ = nullptr;
1644 cursor->next_ = nullptr;
1645 instructions_.last_instruction_ = cursor;
1646
1647 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001648 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001649 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001650 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001651 new_block->successors_.swap(successors_);
1652 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001653
Vladimir Marko60584552015-09-03 13:35:12 +00001654 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001655 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001656 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001657 new_block->dominated_blocks_.swap(dominated_blocks_);
1658 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001659 return new_block;
1660}
1661
David Brazdilec16f792015-08-19 15:04:01 +01001662const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001663 if (EndsWithTryBoundary()) {
1664 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1665 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001666 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001667 return try_boundary;
1668 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001669 DCHECK(IsTryBlock());
1670 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001671 return nullptr;
1672 }
David Brazdilec16f792015-08-19 15:04:01 +01001673 } else if (IsTryBlock()) {
1674 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001675 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001676 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001677 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001678}
1679
David Brazdild7558da2015-09-22 13:04:14 +01001680bool HBasicBlock::HasThrowingInstructions() const {
1681 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1682 if (it.Current()->CanThrow()) {
1683 return true;
1684 }
1685 }
1686 return false;
1687}
1688
David Brazdilfc6a86a2015-06-26 10:33:45 +00001689static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1690 return block.GetPhis().IsEmpty()
1691 && !block.GetInstructions().IsEmpty()
1692 && block.GetFirstInstruction() == block.GetLastInstruction();
1693}
1694
David Brazdil46e2a392015-03-16 17:31:52 +00001695bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001696 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1697}
1698
1699bool HBasicBlock::IsSingleTryBoundary() const {
1700 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001701}
1702
David Brazdil8d5b8b22015-03-24 10:51:52 +00001703bool HBasicBlock::EndsWithControlFlowInstruction() const {
1704 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1705}
1706
David Brazdilb2bd1c52015-03-25 11:17:37 +00001707bool HBasicBlock::EndsWithIf() const {
1708 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1709}
1710
David Brazdilffee3d32015-07-06 11:48:53 +01001711bool HBasicBlock::EndsWithTryBoundary() const {
1712 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1713}
1714
David Brazdilb2bd1c52015-03-25 11:17:37 +00001715bool HBasicBlock::HasSinglePhi() const {
1716 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1717}
1718
David Brazdild26a4112015-11-10 11:07:31 +00001719ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1720 if (EndsWithTryBoundary()) {
1721 // The normal-flow successor of HTryBoundary is always stored at index zero.
1722 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1723 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1724 } else {
1725 // All successors of blocks not ending with TryBoundary are normal.
1726 return ArrayRef<HBasicBlock* const>(successors_);
1727 }
1728}
1729
1730ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1731 if (EndsWithTryBoundary()) {
1732 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1733 } else {
1734 // Blocks not ending with TryBoundary do not have exceptional successors.
1735 return ArrayRef<HBasicBlock* const>();
1736 }
1737}
1738
David Brazdilffee3d32015-07-06 11:48:53 +01001739bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001740 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1741 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1742
1743 size_t length = handlers1.size();
1744 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001745 return false;
1746 }
1747
David Brazdilb618ade2015-07-29 10:31:29 +01001748 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001749 for (size_t i = 0; i < length; ++i) {
1750 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001751 return false;
1752 }
1753 }
1754 return true;
1755}
1756
David Brazdil2d7352b2015-04-20 14:52:42 +01001757size_t HInstructionList::CountSize() const {
1758 size_t size = 0;
1759 HInstruction* current = first_instruction_;
1760 for (; current != nullptr; current = current->GetNext()) {
1761 size++;
1762 }
1763 return size;
1764}
1765
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001766void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1767 for (HInstruction* current = first_instruction_;
1768 current != nullptr;
1769 current = current->GetNext()) {
1770 current->SetBlock(block);
1771 }
1772}
1773
1774void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1775 DCHECK(Contains(cursor));
1776 if (!instruction_list.IsEmpty()) {
1777 if (cursor == last_instruction_) {
1778 last_instruction_ = instruction_list.last_instruction_;
1779 } else {
1780 cursor->next_->previous_ = instruction_list.last_instruction_;
1781 }
1782 instruction_list.last_instruction_->next_ = cursor->next_;
1783 cursor->next_ = instruction_list.first_instruction_;
1784 instruction_list.first_instruction_->previous_ = cursor;
1785 }
1786}
1787
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001788void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1789 DCHECK(Contains(cursor));
1790 if (!instruction_list.IsEmpty()) {
1791 if (cursor == first_instruction_) {
1792 first_instruction_ = instruction_list.first_instruction_;
1793 } else {
1794 cursor->previous_->next_ = instruction_list.first_instruction_;
1795 }
1796 instruction_list.last_instruction_->next_ = cursor;
1797 instruction_list.first_instruction_->previous_ = cursor->previous_;
1798 cursor->previous_ = instruction_list.last_instruction_;
1799 }
1800}
1801
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001802void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001803 if (IsEmpty()) {
1804 first_instruction_ = instruction_list.first_instruction_;
1805 last_instruction_ = instruction_list.last_instruction_;
1806 } else {
1807 AddAfter(last_instruction_, instruction_list);
1808 }
1809}
1810
David Brazdil04ff4e82015-12-10 13:54:52 +00001811// Should be called on instructions in a dead block in post order. This method
1812// assumes `insn` has been removed from all users with the exception of catch
1813// phis because of missing exceptional edges in the graph. It removes the
1814// instruction from catch phi uses, together with inputs of other catch phis in
1815// the catch block at the same index, as these must be dead too.
1816static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1817 DCHECK(!insn->HasEnvironmentUses());
1818 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001819 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1820 size_t use_index = use.GetIndex();
1821 HBasicBlock* user_block = use.GetUser()->GetBlock();
1822 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001823 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1824 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1825 }
1826 }
1827}
1828
David Brazdil2d7352b2015-04-20 14:52:42 +01001829void HBasicBlock::DisconnectAndDelete() {
1830 // Dominators must be removed after all the blocks they dominate. This way
1831 // a loop header is removed last, a requirement for correct loop information
1832 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001833 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001834
David Brazdil9eeebf62016-03-24 11:18:15 +00001835 // The following steps gradually remove the block from all its dependants in
1836 // post order (b/27683071).
1837
1838 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1839 // We need to do this before step (4) which destroys the predecessor list.
1840 HBasicBlock* loop_update_start = this;
1841 if (IsLoopHeader()) {
1842 HLoopInformation* loop_info = GetLoopInformation();
1843 // All other blocks in this loop should have been removed because the header
1844 // was their dominator.
1845 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1846 DCHECK(!loop_info->IsIrreducible());
1847 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1848 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1849 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001850 }
1851
David Brazdil9eeebf62016-03-24 11:18:15 +00001852 // (2) Disconnect the block from its successors and update their phis.
1853 for (HBasicBlock* successor : successors_) {
1854 // Delete this block from the list of predecessors.
1855 size_t this_index = successor->GetPredecessorIndexOf(this);
1856 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1857
1858 // Check that `successor` has other predecessors, otherwise `this` is the
1859 // dominator of `successor` which violates the order DCHECKed at the top.
1860 DCHECK(!successor->predecessors_.empty());
1861
1862 // Remove this block's entries in the successor's phis. Skip exceptional
1863 // successors because catch phi inputs do not correspond to predecessor
1864 // blocks but throwing instructions. The inputs of the catch phis will be
1865 // updated in step (3).
1866 if (!successor->IsCatchBlock()) {
1867 if (successor->predecessors_.size() == 1u) {
1868 // The successor has just one predecessor left. Replace phis with the only
1869 // remaining input.
1870 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1871 HPhi* phi = phi_it.Current()->AsPhi();
1872 phi->ReplaceWith(phi->InputAt(1 - this_index));
1873 successor->RemovePhi(phi);
1874 }
1875 } else {
1876 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1877 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1878 }
1879 }
1880 }
1881 }
1882 successors_.clear();
1883
1884 // (3) Remove instructions and phis. Instructions should have no remaining uses
1885 // except in catch phis. If an instruction is used by a catch phi at `index`,
1886 // remove `index`-th input of all phis in the catch block since they are
1887 // guaranteed dead. Note that we may miss dead inputs this way but the
1888 // graph will always remain consistent.
1889 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1890 HInstruction* insn = it.Current();
1891 RemoveUsesOfDeadInstruction(insn);
1892 RemoveInstruction(insn);
1893 }
1894 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1895 HPhi* insn = it.Current()->AsPhi();
1896 RemoveUsesOfDeadInstruction(insn);
1897 RemovePhi(insn);
1898 }
1899
1900 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001901 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001902 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001903 // We should not see any back edges as they would have been removed by step (3).
1904 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1905
David Brazdil2d7352b2015-04-20 14:52:42 +01001906 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001907 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1908 // This block is the only normal-flow successor of the TryBoundary which
1909 // makes `predecessor` dead. Since DCE removes blocks in post order,
1910 // exception handlers of this TryBoundary were already visited and any
1911 // remaining handlers therefore must be live. We remove `predecessor` from
1912 // their list of predecessors.
1913 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1914 while (predecessor->GetSuccessors().size() > 1) {
1915 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1916 DCHECK(handler->IsCatchBlock());
1917 predecessor->RemoveSuccessor(handler);
1918 handler->RemovePredecessor(predecessor);
1919 }
1920 }
1921
David Brazdil2d7352b2015-04-20 14:52:42 +01001922 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001923 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1924 if (num_pred_successors == 1u) {
1925 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001926 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1927 // successor. Replace those with a HGoto.
1928 DCHECK(last_instruction->IsIf() ||
1929 last_instruction->IsPackedSwitch() ||
1930 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001931 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001932 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001933 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001934 // The predecessor has no remaining successors and therefore must be dead.
1935 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001936 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001937 predecessor->RemoveInstruction(last_instruction);
1938 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001939 // There are multiple successors left. The removed block might be a successor
1940 // of a PackedSwitch which will be completely removed (perhaps replaced with
1941 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1942 // case, leave `last_instruction` as is for now.
1943 DCHECK(last_instruction->IsPackedSwitch() ||
1944 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001945 }
David Brazdil46e2a392015-03-16 17:31:52 +00001946 }
Vladimir Marko60584552015-09-03 13:35:12 +00001947 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001948
David Brazdil9eeebf62016-03-24 11:18:15 +00001949 // (5) Remove the block from all loops it is included in. Skip the inner-most
1950 // loop if this is the loop header (see definition of `loop_update_start`)
1951 // because the loop header's predecessor list has been destroyed in step (4).
1952 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1953 HLoopInformation* loop_info = it.Current();
1954 loop_info->Remove(this);
1955 if (loop_info->IsBackEdge(*this)) {
1956 // If this was the last back edge of the loop, we deliberately leave the
1957 // loop in an inconsistent state and will fail GraphChecker unless the
1958 // entire loop is removed during the pass.
1959 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001960 }
1961 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001962
David Brazdil9eeebf62016-03-24 11:18:15 +00001963 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001964 dominator_->RemoveDominatedBlock(this);
1965 SetDominator(nullptr);
1966
David Brazdil9eeebf62016-03-24 11:18:15 +00001967 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001968 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001969 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001970}
1971
Aart Bik6b69e0a2017-01-11 10:20:43 -08001972void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
1973 DCHECK(EndsWithControlFlowInstruction());
1974 RemoveInstruction(GetLastInstruction());
1975 instructions_.Add(other->GetInstructions());
1976 other->instructions_.SetBlockOfInstructions(this);
1977 other->instructions_.Clear();
1978}
1979
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001980void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001981 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001982 DCHECK(ContainsElement(dominated_blocks_, other));
1983 DCHECK_EQ(GetSingleSuccessor(), other);
1984 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001985 DCHECK(other->GetPhis().IsEmpty());
1986
David Brazdil2d7352b2015-04-20 14:52:42 +01001987 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001988 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989
David Brazdil2d7352b2015-04-20 14:52:42 +01001990 // Remove `other` from the loops it is included in.
1991 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1992 HLoopInformation* loop_info = it.Current();
1993 loop_info->Remove(other);
1994 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001995 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001996 }
1997 }
1998
1999 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002000 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002001 for (HBasicBlock* successor : other->GetSuccessors()) {
2002 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002003 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002004 successors_.swap(other->successors_);
2005 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002006
David Brazdil2d7352b2015-04-20 14:52:42 +01002007 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002008 RemoveDominatedBlock(other);
2009 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002010 dominated->SetDominator(this);
2011 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002012 dominated_blocks_.insert(
2013 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002014 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002015 other->dominator_ = nullptr;
2016
2017 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002018 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002019
2020 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002021 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002022 other->SetGraph(nullptr);
2023}
2024
2025void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2026 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002027 DCHECK(GetDominatedBlocks().empty());
2028 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002029 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002030 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002031 DCHECK(other->GetPhis().IsEmpty());
2032 DCHECK(!other->IsInLoop());
2033
2034 // Move instructions from `other` to `this`.
2035 instructions_.Add(other->GetInstructions());
2036 other->instructions_.SetBlockOfInstructions(this);
2037
2038 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002039 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002040 for (HBasicBlock* successor : other->GetSuccessors()) {
2041 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002042 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002043 successors_.swap(other->successors_);
2044 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002045
2046 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002047 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002048 dominated->SetDominator(this);
2049 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002050 dominated_blocks_.insert(
2051 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002052 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002053 other->dominator_ = nullptr;
2054 other->graph_ = nullptr;
2055}
2056
2057void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002058 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002059 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002060 predecessor->ReplaceSuccessor(this, other);
2061 }
Vladimir Marko60584552015-09-03 13:35:12 +00002062 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002063 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002064 successor->ReplacePredecessor(this, other);
2065 }
Vladimir Marko60584552015-09-03 13:35:12 +00002066 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2067 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002068 }
2069 GetDominator()->ReplaceDominatedBlock(this, other);
2070 other->SetDominator(GetDominator());
2071 dominator_ = nullptr;
2072 graph_ = nullptr;
2073}
2074
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002075void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002076 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002077 DCHECK(block->GetSuccessors().empty());
2078 DCHECK(block->GetPredecessors().empty());
2079 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002080 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002081 DCHECK(block->GetInstructions().IsEmpty());
2082 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002083
David Brazdilc7af85d2015-05-26 12:05:55 +01002084 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002085 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002086 }
2087
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002088 RemoveElement(reverse_post_order_, block);
2089 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002090 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002091}
2092
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002093void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2094 HBasicBlock* reference,
2095 bool replace_if_back_edge) {
2096 if (block->IsLoopHeader()) {
2097 // Clear the information of which blocks are contained in that loop. Since the
2098 // information is stored as a bit vector based on block ids, we have to update
2099 // it, as those block ids were specific to the callee graph and we are now adding
2100 // these blocks to the caller graph.
2101 block->GetLoopInformation()->ClearAllBlocks();
2102 }
2103
2104 // If not already in a loop, update the loop information.
2105 if (!block->IsInLoop()) {
2106 block->SetLoopInformation(reference->GetLoopInformation());
2107 }
2108
2109 // If the block is in a loop, update all its outward loops.
2110 HLoopInformation* loop_info = block->GetLoopInformation();
2111 if (loop_info != nullptr) {
2112 for (HLoopInformationOutwardIterator loop_it(*block);
2113 !loop_it.Done();
2114 loop_it.Advance()) {
2115 loop_it.Current()->Add(block);
2116 }
2117 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2118 loop_info->ReplaceBackEdge(reference, block);
2119 }
2120 }
2121
2122 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2123 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2124 ? reference->GetTryCatchInformation()
2125 : nullptr;
2126 block->SetTryCatchInformation(try_catch_info);
2127}
2128
Calin Juravle2e768302015-07-28 14:41:11 +00002129HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002130 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002131 // Update the environments in this graph to have the invoke's environment
2132 // as parent.
2133 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002134 // Skip the entry block, we do not need to update the entry's suspend check.
2135 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002136 for (HInstructionIterator instr_it(block->GetInstructions());
2137 !instr_it.Done();
2138 instr_it.Advance()) {
2139 HInstruction* current = instr_it.Current();
2140 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002141 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002142 current->GetEnvironment()->SetAndCopyParentChain(
2143 outer_graph->GetArena(), invoke->GetEnvironment());
2144 }
2145 }
2146 }
2147 }
2148 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002149
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002150 if (HasBoundsChecks()) {
2151 outer_graph->SetHasBoundsChecks(true);
2152 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002153 if (HasLoops()) {
2154 outer_graph->SetHasLoops(true);
2155 }
2156 if (HasIrreducibleLoops()) {
2157 outer_graph->SetHasIrreducibleLoops(true);
2158 }
2159 if (HasTryCatch()) {
2160 outer_graph->SetHasTryCatch(true);
2161 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002162 if (HasSIMD()) {
2163 outer_graph->SetHasSIMD(true);
2164 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002165
Calin Juravle2e768302015-07-28 14:41:11 +00002166 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002167 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002168 // Inliner already made sure we don't inline methods that always throw.
2169 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002170 // Simple case of an entry block, a body block, and an exit block.
2171 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002172 HBasicBlock* body = GetBlocks()[1];
2173 DCHECK(GetBlocks()[0]->IsEntryBlock());
2174 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002175 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002176 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002177 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002178
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002179 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2180 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002181 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002182
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002183 // Replace the invoke with the return value of the inlined graph.
2184 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002185 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002186 } else {
2187 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002188 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002189
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002190 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002191 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002192 // Need to inline multiple blocks. We split `invoke`'s block
2193 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002194 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002195 // with the second half.
2196 ArenaAllocator* allocator = outer_graph->GetArena();
2197 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002198 // Note that we split before the invoke only to simplify polymorphic inlining.
2199 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002200
Vladimir Markoec7802a2015-10-01 20:57:57 +01002201 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002202 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002203 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002204 exit_block_->ReplaceWith(to);
2205
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002206 // Update the meta information surrounding blocks:
2207 // (1) the graph they are now in,
2208 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002209 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002210 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002211 // Note that we do not need to update catch phi inputs because they
2212 // correspond to the register file of the outer method which the inlinee
2213 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002214
2215 // We don't add the entry block, the exit block, and the first block, which
2216 // has been merged with `at`.
2217 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2218
2219 // We add the `to` block.
2220 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002221 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002222 + kNumberOfNewBlocksInCaller;
2223
2224 // Find the location of `at` in the outer graph's reverse post order. The new
2225 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002226 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002227 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2228
David Brazdil95177982015-10-30 12:56:58 -05002229 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2230 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002231 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002232 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002233 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002234 DCHECK(current->GetGraph() == this);
2235 current->SetGraph(outer_graph);
2236 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002237 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002238 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002239 }
2240 }
2241
David Brazdil95177982015-10-30 12:56:58 -05002242 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002243 to->SetGraph(outer_graph);
2244 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002245 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002246 // Only `to` can become a back edge, as the inlined blocks
2247 // are predecessors of `to`.
2248 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002249
David Brazdil3f523062016-02-29 16:53:33 +00002250 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002251 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2252 // to now get the outer graph exit block as successor. Note that the inliner
2253 // currently doesn't support inlining methods with try/catch.
2254 HPhi* return_value_phi = nullptr;
2255 bool rerun_dominance = false;
2256 bool rerun_loop_analysis = false;
2257 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2258 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002259 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002260 if (last->IsThrow()) {
2261 DCHECK(!at->IsTryBlock());
2262 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2263 --pred;
2264 // We need to re-run dominance information, as the exit block now has
2265 // a new dominator.
2266 rerun_dominance = true;
2267 if (predecessor->GetLoopInformation() != nullptr) {
2268 // The exit block and blocks post dominated by the exit block do not belong
2269 // to any loop. Because we do not compute the post dominators, we need to re-run
2270 // loop analysis to get the loop information correct.
2271 rerun_loop_analysis = true;
2272 }
2273 } else {
2274 if (last->IsReturnVoid()) {
2275 DCHECK(return_value == nullptr);
2276 DCHECK(return_value_phi == nullptr);
2277 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002278 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002279 if (return_value_phi != nullptr) {
2280 return_value_phi->AddInput(last->InputAt(0));
2281 } else if (return_value == nullptr) {
2282 return_value = last->InputAt(0);
2283 } else {
2284 // There will be multiple returns.
2285 return_value_phi = new (allocator) HPhi(
2286 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2287 to->AddPhi(return_value_phi);
2288 return_value_phi->AddInput(return_value);
2289 return_value_phi->AddInput(last->InputAt(0));
2290 return_value = return_value_phi;
2291 }
David Brazdil3f523062016-02-29 16:53:33 +00002292 }
2293 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2294 predecessor->RemoveInstruction(last);
2295 }
2296 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002297 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002298 DCHECK(!outer_graph->HasIrreducibleLoops())
2299 << "Recomputing loop information in graphs with irreducible loops "
2300 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002301 outer_graph->ClearLoopInformation();
2302 outer_graph->ClearDominanceInformation();
2303 outer_graph->BuildDominatorTree();
2304 } else if (rerun_dominance) {
2305 outer_graph->ClearDominanceInformation();
2306 outer_graph->ComputeDominanceInformation();
2307 }
David Brazdil3f523062016-02-29 16:53:33 +00002308 }
David Brazdil05144f42015-04-16 15:18:00 +01002309
2310 // Walk over the entry block and:
2311 // - Move constants from the entry block to the outer_graph's entry block,
2312 // - Replace HParameterValue instructions with their real value.
2313 // - Remove suspend checks, that hold an environment.
2314 // We must do this after the other blocks have been inlined, otherwise ids of
2315 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002316 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002317 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2318 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002319 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002320 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002321 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002322 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002323 replacement = outer_graph->GetIntConstant(
2324 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002325 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002326 replacement = outer_graph->GetLongConstant(
2327 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002328 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002329 replacement = outer_graph->GetFloatConstant(
2330 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002331 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002332 replacement = outer_graph->GetDoubleConstant(
2333 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002334 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002335 if (kIsDebugBuild
2336 && invoke->IsInvokeStaticOrDirect()
2337 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2338 // Ensure we do not use the last input of `invoke`, as it
2339 // contains a clinit check which is not an actual argument.
2340 size_t last_input_index = invoke->InputCount() - 1;
2341 DCHECK(parameter_index != last_input_index);
2342 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002343 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002344 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002345 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002346 } else {
2347 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2348 entry_block_->RemoveInstruction(current);
2349 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002350 if (replacement != nullptr) {
2351 current->ReplaceWith(replacement);
2352 // If the current is the return value then we need to update the latter.
2353 if (current == return_value) {
2354 DCHECK_EQ(entry_block_, return_value->GetBlock());
2355 return_value = replacement;
2356 }
2357 }
2358 }
2359
Calin Juravle2e768302015-07-28 14:41:11 +00002360 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002361}
2362
Mingyao Yang3584bce2015-05-19 16:01:59 -07002363/*
2364 * Loop will be transformed to:
2365 * old_pre_header
2366 * |
2367 * if_block
2368 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002369 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002370 * \ /
2371 * new_pre_header
2372 * |
2373 * header
2374 */
2375void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2376 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002377 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002378
Aart Bik3fc7f352015-11-20 22:03:03 -08002379 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002380 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002381 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2382 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002383 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2384 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002385 AddBlock(true_block);
2386 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002387 AddBlock(new_pre_header);
2388
Aart Bik3fc7f352015-11-20 22:03:03 -08002389 header->ReplacePredecessor(old_pre_header, new_pre_header);
2390 old_pre_header->successors_.clear();
2391 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002392
Aart Bik3fc7f352015-11-20 22:03:03 -08002393 old_pre_header->AddSuccessor(if_block);
2394 if_block->AddSuccessor(true_block); // True successor
2395 if_block->AddSuccessor(false_block); // False successor
2396 true_block->AddSuccessor(new_pre_header);
2397 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002398
Aart Bik3fc7f352015-11-20 22:03:03 -08002399 old_pre_header->dominated_blocks_.push_back(if_block);
2400 if_block->SetDominator(old_pre_header);
2401 if_block->dominated_blocks_.push_back(true_block);
2402 true_block->SetDominator(if_block);
2403 if_block->dominated_blocks_.push_back(false_block);
2404 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002405 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002406 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002407 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002408 header->SetDominator(new_pre_header);
2409
Aart Bik3fc7f352015-11-20 22:03:03 -08002410 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002411 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002412 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002413 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002414 reverse_post_order_[index_of_header++] = true_block;
2415 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002416 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002417
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002418 // The pre_header can never be a back edge of a loop.
2419 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2420 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2421 UpdateLoopAndTryInformationOfNewBlock(
2422 if_block, old_pre_header, /* replace_if_back_edge */ false);
2423 UpdateLoopAndTryInformationOfNewBlock(
2424 true_block, old_pre_header, /* replace_if_back_edge */ false);
2425 UpdateLoopAndTryInformationOfNewBlock(
2426 false_block, old_pre_header, /* replace_if_back_edge */ false);
2427 UpdateLoopAndTryInformationOfNewBlock(
2428 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002429}
2430
Aart Bikf8f5a162017-02-06 15:35:29 -08002431HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2432 HBasicBlock* body,
2433 HBasicBlock* exit) {
2434 DCHECK(header->IsLoopHeader());
2435 HLoopInformation* loop = header->GetLoopInformation();
2436
2437 // Add new loop blocks.
2438 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2439 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2440 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2441 AddBlock(new_pre_header);
2442 AddBlock(new_header);
2443 AddBlock(new_body);
2444
2445 // Set up control flow.
2446 header->ReplaceSuccessor(exit, new_pre_header);
2447 new_pre_header->AddSuccessor(new_header);
2448 new_header->AddSuccessor(exit);
2449 new_header->AddSuccessor(new_body);
2450 new_body->AddSuccessor(new_header);
2451
2452 // Set up dominators.
2453 header->ReplaceDominatedBlock(exit, new_pre_header);
2454 new_pre_header->SetDominator(header);
2455 new_pre_header->dominated_blocks_.push_back(new_header);
2456 new_header->SetDominator(new_pre_header);
2457 new_header->dominated_blocks_.push_back(new_body);
2458 new_body->SetDominator(new_header);
2459 new_header->dominated_blocks_.push_back(exit);
2460 exit->SetDominator(new_header);
2461
2462 // Fix reverse post order.
2463 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2464 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2465 reverse_post_order_[++index_of_header] = new_pre_header;
2466 reverse_post_order_[++index_of_header] = new_header;
2467 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2468 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2469 reverse_post_order_[index_of_body] = new_body;
2470
Aart Bikb07d1bc2017-04-05 10:03:15 -07002471 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002472 new_pre_header->AddInstruction(new (arena_) HGoto());
2473 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2474 new_header->AddInstruction(suspend_check);
2475 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002476 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2477 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002478
2479 // Update loop information.
2480 new_header->AddBackEdge(new_body);
2481 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2482 new_header->GetLoopInformation()->Populate();
2483 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2484 HLoopInformationOutwardIterator it(*new_header);
2485 for (it.Advance(); !it.Done(); it.Advance()) {
2486 it.Current()->Add(new_pre_header);
2487 it.Current()->Add(new_header);
2488 it.Current()->Add(new_body);
2489 }
2490 return new_pre_header;
2491}
2492
David Brazdilf5552582015-12-27 13:36:12 +00002493static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002494 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002495 if (rti.IsValid()) {
2496 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2497 << " upper_bound_rti: " << upper_bound_rti
2498 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002499 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2500 << " upper_bound_rti: " << upper_bound_rti
2501 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002502 }
2503}
2504
Calin Juravle2e768302015-07-28 14:41:11 +00002505void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2506 if (kIsDebugBuild) {
2507 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2508 ScopedObjectAccess soa(Thread::Current());
2509 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2510 if (IsBoundType()) {
2511 // Having the test here spares us from making the method virtual just for
2512 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002513 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002514 }
2515 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002516 reference_type_handle_ = rti.GetTypeHandle();
2517 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002518}
2519
David Brazdilf5552582015-12-27 13:36:12 +00002520void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2521 if (kIsDebugBuild) {
2522 ScopedObjectAccess soa(Thread::Current());
2523 DCHECK(upper_bound.IsValid());
2524 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2525 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2526 }
2527 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002528 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002529}
2530
Vladimir Markoa1de9182016-02-25 11:37:38 +00002531ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002532 if (kIsDebugBuild) {
2533 ScopedObjectAccess soa(Thread::Current());
2534 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002535 if (!is_exact) {
2536 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2537 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2538 }
Calin Juravle2e768302015-07-28 14:41:11 +00002539 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002540 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002541}
2542
Calin Juravleacf735c2015-02-12 15:25:22 +00002543std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2544 ScopedObjectAccess soa(Thread::Current());
2545 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002546 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002547 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002548 << " is_exact=" << rhs.IsExact()
2549 << " ]";
2550 return os;
2551}
2552
Mark Mendellc4701932015-04-10 13:18:51 -04002553bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2554 // For now, assume that instructions in different blocks may use the
2555 // environment.
2556 // TODO: Use the control flow to decide if this is true.
2557 if (GetBlock() != other->GetBlock()) {
2558 return true;
2559 }
2560
2561 // We know that we are in the same block. Walk from 'this' to 'other',
2562 // checking to see if there is any instruction with an environment.
2563 HInstruction* current = this;
2564 for (; current != other && current != nullptr; current = current->GetNext()) {
2565 // This is a conservative check, as the instruction result may not be in
2566 // the referenced environment.
2567 if (current->HasEnvironment()) {
2568 return true;
2569 }
2570 }
2571
2572 // We should have been called with 'this' before 'other' in the block.
2573 // Just confirm this.
2574 DCHECK(current != nullptr);
2575 return false;
2576}
2577
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002578void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002579 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2580 IntrinsicSideEffects side_effects,
2581 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002582 intrinsic_ = intrinsic;
2583 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002584
Aart Bik5d75afe2015-12-14 11:57:01 -08002585 // Adjust method's side effects from intrinsic table.
2586 switch (side_effects) {
2587 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2588 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2589 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2590 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2591 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002592
2593 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2594 opt.SetDoesNotNeedDexCache();
2595 opt.SetDoesNotNeedEnvironment();
2596 } else {
2597 // If we need an environment, that means there will be a call, which can trigger GC.
2598 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2599 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002600 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002601 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002602}
2603
David Brazdil6de19382016-01-08 17:37:10 +00002604bool HNewInstance::IsStringAlloc() const {
2605 ScopedObjectAccess soa(Thread::Current());
2606 return GetReferenceTypeInfo().IsStringClass();
2607}
2608
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002609bool HInvoke::NeedsEnvironment() const {
2610 if (!IsIntrinsic()) {
2611 return true;
2612 }
2613 IntrinsicOptimizations opt(*this);
2614 return !opt.GetDoesNotNeedEnvironment();
2615}
2616
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002617const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2618 ArtMethod* caller = GetEnvironment()->GetMethod();
2619 ScopedObjectAccess soa(Thread::Current());
2620 // `caller` is null for a top-level graph representing a method whose declaring
2621 // class was not resolved.
2622 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2623}
2624
Vladimir Markodc151b22015-10-15 18:02:30 +01002625bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2626 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002627 return false;
2628 }
2629 if (!IsIntrinsic()) {
2630 return true;
2631 }
2632 IntrinsicOptimizations opt(*this);
2633 return !opt.GetDoesNotNeedDexCache();
2634}
2635
Vladimir Markof64242a2015-12-01 14:58:23 +00002636std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2637 switch (rhs) {
2638 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002639 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002640 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002641 return os << "Recursive";
2642 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2643 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002644 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002645 return os << "DirectAddress";
Vladimir Markof64242a2015-12-01 14:58:23 +00002646 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
Vladimir Marko65979462017-05-19 17:25:12 +01002647 return os << "DexCachePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002648 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
Vladimir Marko65979462017-05-19 17:25:12 +01002649 return os << "DexCacheViaMethod";
Vladimir Markof64242a2015-12-01 14:58:23 +00002650 default:
2651 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2652 UNREACHABLE();
2653 }
2654}
2655
Vladimir Markofbb184a2015-11-13 14:47:00 +00002656std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2657 switch (rhs) {
2658 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2659 return os << "explicit";
2660 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2661 return os << "implicit";
2662 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2663 return os << "none";
2664 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002665 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2666 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002667 }
2668}
2669
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002670bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2671 const HLoadClass* other_load_class = other->AsLoadClass();
2672 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2673 // names rather than type indexes. However, we shall also have to re-think the hash code.
2674 if (type_index_ != other_load_class->type_index_ ||
2675 GetPackedFields() != other_load_class->GetPackedFields()) {
2676 return false;
2677 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002678 switch (GetLoadKind()) {
2679 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002680 case LoadKind::kJitTableAddress: {
2681 ScopedObjectAccess soa(Thread::Current());
2682 return GetClass().Get() == other_load_class->GetClass().Get();
2683 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002684 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002685 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002686 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002687 }
2688}
2689
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002690void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002691 SetPackedField<LoadKindField>(load_kind);
2692
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002693 if (load_kind != LoadKind::kDexCacheViaMethod &&
2694 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002695 RemoveAsUserOfInput(0u);
2696 SetRawInputAt(0u, nullptr);
2697 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002698
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002699 if (!NeedsEnvironment()) {
2700 RemoveEnvironment();
2701 SetSideEffects(SideEffects::None());
2702 }
2703}
2704
2705std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2706 switch (rhs) {
2707 case HLoadClass::LoadKind::kReferrersClass:
2708 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002709 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2710 return os << "BootImageLinkTimePcRelative";
2711 case HLoadClass::LoadKind::kBootImageAddress:
2712 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002713 case HLoadClass::LoadKind::kBssEntry:
2714 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002715 case HLoadClass::LoadKind::kJitTableAddress:
2716 return os << "JitTableAddress";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002717 case HLoadClass::LoadKind::kDexCacheViaMethod:
2718 return os << "DexCacheViaMethod";
2719 default:
2720 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2721 UNREACHABLE();
2722 }
2723}
2724
Vladimir Marko372f10e2016-05-17 16:30:10 +01002725bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2726 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002727 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2728 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002729 if (string_index_ != other_load_string->string_index_ ||
2730 GetPackedFields() != other_load_string->GetPackedFields()) {
2731 return false;
2732 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002733 switch (GetLoadKind()) {
2734 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002735 case LoadKind::kJitTableAddress: {
2736 ScopedObjectAccess soa(Thread::Current());
2737 return GetString().Get() == other_load_string->GetString().Get();
2738 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002739 default:
2740 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002741 }
2742}
2743
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002744void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002745 // Once sharpened, the load kind should not be changed again.
2746 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2747 SetPackedField<LoadKindField>(load_kind);
2748
2749 if (load_kind != LoadKind::kDexCacheViaMethod) {
2750 RemoveAsUserOfInput(0u);
2751 SetRawInputAt(0u, nullptr);
2752 }
2753 if (!NeedsEnvironment()) {
2754 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002755 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002756 }
2757}
2758
2759std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2760 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002761 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2762 return os << "BootImageLinkTimePcRelative";
2763 case HLoadString::LoadKind::kBootImageAddress:
2764 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002765 case HLoadString::LoadKind::kBssEntry:
2766 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002767 case HLoadString::LoadKind::kJitTableAddress:
2768 return os << "JitTableAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002769 case HLoadString::LoadKind::kDexCacheViaMethod:
2770 return os << "DexCacheViaMethod";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002771 default:
2772 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2773 UNREACHABLE();
2774 }
2775}
2776
Mark Mendellc4701932015-04-10 13:18:51 -04002777void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002778 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2779 HEnvironment* user = use.GetUser();
2780 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002781 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002782 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002783}
2784
Roland Levillainc9b21f82016-03-23 16:36:59 +00002785// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002786HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2787 ArenaAllocator* allocator = GetArena();
2788
2789 if (cond->IsCondition() &&
2790 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2791 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2792 HInstruction* lhs = cond->InputAt(0);
2793 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002794 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002795 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2796 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2797 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2798 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2799 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2800 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2801 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2802 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2803 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2804 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2805 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002806 default:
2807 LOG(FATAL) << "Unexpected condition";
2808 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002809 }
2810 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2811 return replacement;
2812 } else if (cond->IsIntConstant()) {
2813 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002814 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002815 return GetIntConstant(1);
2816 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002817 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002818 return GetIntConstant(0);
2819 }
2820 } else {
2821 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2822 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2823 return replacement;
2824 }
2825}
2826
Roland Levillainc9285912015-12-18 10:38:42 +00002827std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2828 os << "["
2829 << " source=" << rhs.GetSource()
2830 << " destination=" << rhs.GetDestination()
2831 << " type=" << rhs.GetType()
2832 << " instruction=";
2833 if (rhs.GetInstruction() != nullptr) {
2834 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2835 } else {
2836 os << "null";
2837 }
2838 os << " ]";
2839 return os;
2840}
2841
Roland Levillain86503782016-02-11 19:07:30 +00002842std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2843 switch (rhs) {
2844 case TypeCheckKind::kUnresolvedCheck:
2845 return os << "unresolved_check";
2846 case TypeCheckKind::kExactCheck:
2847 return os << "exact_check";
2848 case TypeCheckKind::kClassHierarchyCheck:
2849 return os << "class_hierarchy_check";
2850 case TypeCheckKind::kAbstractClassCheck:
2851 return os << "abstract_class_check";
2852 case TypeCheckKind::kInterfaceCheck:
2853 return os << "interface_check";
2854 case TypeCheckKind::kArrayObjectCheck:
2855 return os << "array_object_check";
2856 case TypeCheckKind::kArrayCheck:
2857 return os << "array_check";
2858 default:
2859 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2860 UNREACHABLE();
2861 }
2862}
2863
Andreas Gampe26de38b2016-07-27 17:53:11 -07002864std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2865 switch (kind) {
2866 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002867 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002868 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002869 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002870 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002871 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002872 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002873 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002874 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002875 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002876
2877 default:
2878 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2879 UNREACHABLE();
2880 }
2881}
2882
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002883} // namespace art