blob: cf67e1a7e90bbbe08304c5c4590731d501b24e23 [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
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
59 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
60 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
61 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
62 constexpr size_t kDefaultWorklistSize = 8;
63 worklist.reserve(kDefaultWorklistSize);
64 visited->SetBit(entry_block_->GetBlockId());
65 visiting.SetBit(entry_block_->GetBlockId());
66 worklist.push_back(entry_block_);
67
68 while (!worklist.empty()) {
69 HBasicBlock* current = worklist.back();
70 uint32_t current_id = current->GetBlockId();
71 if (successors_visited[current_id] == current->GetSuccessors().size()) {
72 visiting.ClearBit(current_id);
73 worklist.pop_back();
74 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010075 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
76 uint32_t successor_id = successor->GetBlockId();
77 if (visiting.IsBitSet(successor_id)) {
78 DCHECK(ContainsElement(worklist, successor));
79 successor->AddBackEdge(current);
80 } else if (!visited->IsBitSet(successor_id)) {
81 visited->SetBit(successor_id);
82 visiting.SetBit(successor_id);
83 worklist.push_back(successor);
84 }
85 }
86 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000087}
88
Vladimir Markocac5a7e2016-02-22 10:39:50 +000089static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010090 for (HEnvironment* environment = instruction->GetEnvironment();
91 environment != nullptr;
92 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000094 if (environment->GetInstructionAt(i) != nullptr) {
95 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000096 }
97 }
98 }
99}
100
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000101static void RemoveAsUser(HInstruction* instruction) {
102 for (size_t i = 0; i < instruction->InputCount(); i++) {
103 instruction->RemoveAsUserOfInput(i);
104 }
105
106 RemoveEnvironmentUses(instruction);
107}
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100112 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000113 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100114 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000115 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
116 RemoveAsUser(it.Current());
117 }
118 }
119 }
120}
121
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100122void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100125 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000128 for (HBasicBlock* successor : block->GetSuccessors()) {
129 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000130 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100131 // Remove the block from the list of blocks, so that further analyses
132 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600134 if (block->IsExitBlock()) {
135 SetExitBlock(nullptr);
136 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000137 // Mark the block as removed. This is used by the HGraphBuilder to discard
138 // the block as a branch target.
139 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 }
142}
143
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000145 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000146
David Brazdil86ea7ee2016-02-16 09:26:07 +0000147 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 FindBackEdges(&visited);
149
David Brazdil86ea7ee2016-02-16 09:26:07 +0000150 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000151 // the initial DFS as users from other instructions, so that
152 // users can be safely removed before uses later.
153 RemoveInstructionsAsUsersFromDeadBlocks(visited);
154
David Brazdil86ea7ee2016-02-16 09:26:07 +0000155 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000156 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 // predecessors list of live blocks.
158 RemoveDeadBlocks(visited);
159
David Brazdil86ea7ee2016-02-16 09:26:07 +0000160 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100161 // dominators and the reverse post order.
162 SimplifyCFG();
163
David Brazdil86ea7ee2016-02-16 09:26:07 +0000164 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000166
David Brazdil86ea7ee2016-02-16 09:26:07 +0000167 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168 // set the loop information on each block.
169 GraphAnalysisResult result = AnalyzeLoops();
170 if (result != kAnalysisSuccess) {
171 return result;
172 }
173
David Brazdil86ea7ee2016-02-16 09:26:07 +0000174 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175 // which needs the information to build catch block phis from values of
176 // locals at throwing instructions inside try blocks.
177 ComputeTryBlockInformation();
178
179 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100180}
181
182void HGraph::ClearDominanceInformation() {
183 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
184 it.Current()->ClearDominanceInformation();
185 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100186 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187}
188
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000189void HGraph::ClearLoopInformation() {
190 SetHasIrreducibleLoops(false);
191 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000192 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000193 }
194}
195
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000197 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198 dominator_ = nullptr;
199}
200
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000201HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
202 HInstruction* instruction = GetFirstInstruction();
203 while (instruction->IsParallelMove()) {
204 instruction = instruction->GetNext();
205 }
206 return instruction;
207}
208
David Brazdil3f4a5222016-05-06 12:46:21 +0100209static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
210 DCHECK(ContainsElement(block->GetSuccessors(), successor));
211
212 HBasicBlock* old_dominator = successor->GetDominator();
213 HBasicBlock* new_dominator =
214 (old_dominator == nullptr) ? block
215 : CommonDominator::ForPair(old_dominator, block);
216
217 if (old_dominator == new_dominator) {
218 return false;
219 } else {
220 successor->SetDominator(new_dominator);
221 return true;
222 }
223}
224
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100225void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100226 DCHECK(reverse_post_order_.empty());
227 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100228 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100229
230 // Number of visits of a given node, indexed by block id.
231 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
232 // Number of successors visited from a given node, indexed by block id.
233 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
234 // Nodes for which we need to visit successors.
235 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
236 constexpr size_t kDefaultWorklistSize = 8;
237 worklist.reserve(kDefaultWorklistSize);
238 worklist.push_back(entry_block_);
239
240 while (!worklist.empty()) {
241 HBasicBlock* current = worklist.back();
242 uint32_t current_id = current->GetBlockId();
243 if (successors_visited[current_id] == current->GetSuccessors().size()) {
244 worklist.pop_back();
245 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100246 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100247 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100248
249 // Once all the forward edges have been visited, we know the immediate
250 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100251 if (++visits[successor->GetBlockId()] ==
252 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100253 reverse_post_order_.push_back(successor);
254 worklist.push_back(successor);
255 }
256 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000257 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000258
David Brazdil3f4a5222016-05-06 12:46:21 +0100259 // Check if the graph has back edges not dominated by their respective headers.
260 // If so, we need to update the dominators of those headers and recursively of
261 // their successors. We do that with a fix-point iteration over all blocks.
262 // The algorithm is guaranteed to terminate because it loops only if the sum
263 // of all dominator chains has decreased in the current iteration.
264 bool must_run_fix_point = false;
265 for (HBasicBlock* block : blocks_) {
266 if (block != nullptr &&
267 block->IsLoopHeader() &&
268 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
269 must_run_fix_point = true;
270 break;
271 }
272 }
273 if (must_run_fix_point) {
274 bool update_occurred = true;
275 while (update_occurred) {
276 update_occurred = false;
277 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
278 HBasicBlock* block = it.Current();
279 for (HBasicBlock* successor : block->GetSuccessors()) {
280 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
281 }
282 }
283 }
284 }
285
286 // Make sure that there are no remaining blocks whose dominator information
287 // needs to be updated.
288 if (kIsDebugBuild) {
289 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
290 HBasicBlock* block = it.Current();
291 for (HBasicBlock* successor : block->GetSuccessors()) {
292 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
293 }
294 }
295 }
296
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000297 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000298 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000299 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
300 HBasicBlock* block = it.Current();
301 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.
377 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
378 HBasicBlock* block = it.Current();
379 if (block->IsEntryBlock() || block->IsCatchBlock()) {
380 // Catch blocks after simplification have only exceptional predecessors
381 // and hence are never in tries.
382 continue;
383 }
384
385 // Infer try membership from the first predecessor. Having simplified loops,
386 // the first predecessor can never be a back edge and therefore it must have
387 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100388 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100389 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100390 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000391 if (try_entry != nullptr &&
392 (block->GetTryCatchInformation() == nullptr ||
393 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
394 // We are either setting try block membership for the first time or it
395 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100396 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
397 }
David Brazdilffee3d32015-07-06 11:48:53 +0100398 }
399}
400
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100401void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000402// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100403 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000404 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100405 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
406 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
407 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
408 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100409 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000410 if (block->GetSuccessors().size() > 1) {
411 // Only split normal-flow edges. We cannot split exceptional edges as they
412 // are synthesized (approximate real control flow), and we do not need to
413 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000414 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
415 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
416 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100417 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000418 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000419 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
420 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000421 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000422 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100423 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000424 // SplitCriticalEdge could have invalidated the `normal_successors`
425 // ArrayRef. We must re-acquire it.
426 normal_successors = block->GetNormalSuccessors();
427 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
428 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100429 }
430 }
431 }
432 if (block->IsLoopHeader()) {
433 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000434 } else if (!block->IsEntryBlock() &&
435 block->GetFirstInstruction() != nullptr &&
436 block->GetFirstInstruction()->IsSuspendCheck()) {
437 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000438 // a loop got dismantled. Just remove the suspend check.
439 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100440 }
441 }
442}
443
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000444GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100445 // Order does not matter.
446 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
447 HBasicBlock* block = it.Current();
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
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600531HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000532 switch (type) {
533 case Primitive::Type::kPrimBoolean:
534 DCHECK(IsUint<1>(value));
535 FALLTHROUGH_INTENDED;
536 case Primitive::Type::kPrimByte:
537 case Primitive::Type::kPrimChar:
538 case Primitive::Type::kPrimShort:
539 case Primitive::Type::kPrimInt:
540 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600541 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000542
543 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600544 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000545
546 default:
547 LOG(FATAL) << "Unsupported constant type";
548 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000549 }
David Brazdil46e2a392015-03-16 17:31:52 +0000550}
551
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000552void HGraph::CacheFloatConstant(HFloatConstant* constant) {
553 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
554 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
555 cached_float_constants_.Overwrite(value, constant);
556}
557
558void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
559 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
560 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
561 cached_double_constants_.Overwrite(value, constant);
562}
563
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000564void HLoopInformation::Add(HBasicBlock* block) {
565 blocks_.SetBit(block->GetBlockId());
566}
567
David Brazdil46e2a392015-03-16 17:31:52 +0000568void HLoopInformation::Remove(HBasicBlock* block) {
569 blocks_.ClearBit(block->GetBlockId());
570}
571
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100572void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
573 if (blocks_.IsBitSet(block->GetBlockId())) {
574 return;
575 }
576
577 blocks_.SetBit(block->GetBlockId());
578 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000579 for (HBasicBlock* predecessor : block->GetPredecessors()) {
580 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100581 }
582}
583
David Brazdilc2e8af92016-04-05 17:15:19 +0100584void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
585 size_t block_id = block->GetBlockId();
586
587 // If `block` is in `finalized`, we know its membership in the loop has been
588 // decided and it does not need to be revisited.
589 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000590 return;
591 }
592
David Brazdilc2e8af92016-04-05 17:15:19 +0100593 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594 if (block->IsLoopHeader()) {
595 // If we hit a loop header in an irreducible loop, we first check if the
596 // pre header of that loop belongs to the currently analyzed loop. If it does,
597 // then we visit the back edges.
598 // Note that we cannot use GetPreHeader, as the loop may have not been populated
599 // yet.
600 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100601 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000602 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000603 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100604 blocks_.SetBit(block_id);
605 finalized->SetBit(block_id);
606 is_finalized = true;
607
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 HLoopInformation* info = block->GetLoopInformation();
609 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100610 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 }
612 }
613 } else {
614 // Visit all predecessors. If one predecessor is part of the loop, this
615 // block is also part of this loop.
616 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100617 PopulateIrreducibleRecursive(predecessor, finalized);
618 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100620 blocks_.SetBit(block_id);
621 finalized->SetBit(block_id);
622 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000623 }
624 }
625 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100626
627 // All predecessors have been recursively visited. Mark finalized if not marked yet.
628 if (!is_finalized) {
629 finalized->SetBit(block_id);
630 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000631}
632
633void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100634 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000635 // Populate this loop: starting with the back edge, recursively add predecessors
636 // that are not already part of that loop. Set the header as part of the loop
637 // to end the recursion.
638 // This is a recursive implementation of the algorithm described in
639 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100640 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000641 blocks_.SetBit(header_->GetBlockId());
642 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100643
David Brazdil3f4a5222016-05-06 12:46:21 +0100644 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100645
646 if (is_irreducible_loop) {
647 ArenaBitVector visited(graph->GetArena(),
648 graph->GetBlocks().size(),
649 /* expandable */ false,
650 kArenaAllocGraphBuilder);
651 for (HBasicBlock* back_edge : GetBackEdges()) {
652 PopulateIrreducibleRecursive(back_edge, &visited);
653 }
654 } else {
655 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000656 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100657 }
David Brazdila4b8c212015-05-07 09:59:30 +0100658 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100659
Vladimir Markofd66c502016-04-18 15:37:01 +0100660 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
661 // When compiling in OSR mode, all loops in the compiled method may be entered
662 // from the interpreter. We treat this OSR entry point just like an extra entry
663 // to an irreducible loop, so we need to mark the method's loops as irreducible.
664 // This does not apply to inlined loops which do not act as OSR entry points.
665 if (suspend_check_ == nullptr) {
666 // Just building the graph in OSR mode, this loop is not inlined. We never build an
667 // inner graph in OSR mode as we can do OSR transition only from the outer method.
668 is_irreducible_loop = true;
669 } else {
670 // Look at the suspend check's environment to determine if the loop was inlined.
671 DCHECK(suspend_check_->HasEnvironment());
672 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
673 is_irreducible_loop = true;
674 }
675 }
676 }
677 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100678 irreducible_ = true;
679 graph->SetHasIrreducibleLoops(true);
680 }
David Brazdila4b8c212015-05-07 09:59:30 +0100681}
682
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100683HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000684 HBasicBlock* block = header_->GetPredecessors()[0];
685 DCHECK(irreducible_ || (block == header_->GetDominator()));
686 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100687}
688
689bool HLoopInformation::Contains(const HBasicBlock& block) const {
690 return blocks_.IsBitSet(block.GetBlockId());
691}
692
693bool HLoopInformation::IsIn(const HLoopInformation& other) const {
694 return other.blocks_.IsBitSet(header_->GetBlockId());
695}
696
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800697bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
698 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700699}
700
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100701size_t HLoopInformation::GetLifetimeEnd() const {
702 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100703 for (HBasicBlock* back_edge : GetBackEdges()) {
704 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100705 }
706 return last_position;
707}
708
David Brazdil3f4a5222016-05-06 12:46:21 +0100709bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
710 for (HBasicBlock* back_edge : GetBackEdges()) {
711 DCHECK(back_edge->GetDominator() != nullptr);
712 if (!header_->Dominates(back_edge)) {
713 return true;
714 }
715 }
716 return false;
717}
718
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100719bool HBasicBlock::Dominates(HBasicBlock* other) const {
720 // Walk up the dominator tree from `other`, to find out if `this`
721 // is an ancestor.
722 HBasicBlock* current = other;
723 while (current != nullptr) {
724 if (current == this) {
725 return true;
726 }
727 current = current->GetDominator();
728 }
729 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100730}
731
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100732static void UpdateInputsUsers(HInstruction* instruction) {
733 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
734 instruction->InputAt(i)->AddUseAt(instruction, i);
735 }
736 // Environment should be created later.
737 DCHECK(!instruction->HasEnvironment());
738}
739
Roland Levillainccc07a92014-09-16 14:48:16 +0100740void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
741 HInstruction* replacement) {
742 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400743 if (initial->IsControlFlow()) {
744 // We can only replace a control flow instruction with another control flow instruction.
745 DCHECK(replacement->IsControlFlow());
746 DCHECK_EQ(replacement->GetId(), -1);
747 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
748 DCHECK_EQ(initial->GetBlock(), this);
749 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100750 DCHECK(initial->GetUses().empty());
751 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400752 replacement->SetBlock(this);
753 replacement->SetId(GetGraph()->GetNextInstructionId());
754 instructions_.InsertInstructionBefore(replacement, initial);
755 UpdateInputsUsers(replacement);
756 } else {
757 InsertInstructionBefore(replacement, initial);
758 initial->ReplaceWith(replacement);
759 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100760 RemoveInstruction(initial);
761}
762
David Brazdil74eb1b22015-12-14 11:44:01 +0000763void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
764 DCHECK(!cursor->IsPhi());
765 DCHECK(!insn->IsPhi());
766 DCHECK(!insn->IsControlFlow());
767 DCHECK(insn->CanBeMoved());
768 DCHECK(!insn->HasSideEffects());
769
770 HBasicBlock* from_block = insn->GetBlock();
771 HBasicBlock* to_block = cursor->GetBlock();
772 DCHECK(from_block != to_block);
773
774 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
775 insn->SetBlock(to_block);
776 to_block->instructions_.InsertInstructionBefore(insn, cursor);
777}
778
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100779static void Add(HInstructionList* instruction_list,
780 HBasicBlock* block,
781 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000782 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000783 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100784 instruction->SetBlock(block);
785 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100786 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100787 instruction_list->AddInstruction(instruction);
788}
789
790void HBasicBlock::AddInstruction(HInstruction* instruction) {
791 Add(&instructions_, this, instruction);
792}
793
794void HBasicBlock::AddPhi(HPhi* phi) {
795 Add(&phis_, this, phi);
796}
797
David Brazdilc3d743f2015-04-22 13:40:50 +0100798void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
799 DCHECK(!cursor->IsPhi());
800 DCHECK(!instruction->IsPhi());
801 DCHECK_EQ(instruction->GetId(), -1);
802 DCHECK_NE(cursor->GetId(), -1);
803 DCHECK_EQ(cursor->GetBlock(), this);
804 DCHECK(!instruction->IsControlFlow());
805 instruction->SetBlock(this);
806 instruction->SetId(GetGraph()->GetNextInstructionId());
807 UpdateInputsUsers(instruction);
808 instructions_.InsertInstructionBefore(instruction, cursor);
809}
810
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100811void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
812 DCHECK(!cursor->IsPhi());
813 DCHECK(!instruction->IsPhi());
814 DCHECK_EQ(instruction->GetId(), -1);
815 DCHECK_NE(cursor->GetId(), -1);
816 DCHECK_EQ(cursor->GetBlock(), this);
817 DCHECK(!instruction->IsControlFlow());
818 DCHECK(!cursor->IsControlFlow());
819 instruction->SetBlock(this);
820 instruction->SetId(GetGraph()->GetNextInstructionId());
821 UpdateInputsUsers(instruction);
822 instructions_.InsertInstructionAfter(instruction, cursor);
823}
824
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100825void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
826 DCHECK_EQ(phi->GetId(), -1);
827 DCHECK_NE(cursor->GetId(), -1);
828 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100829 phi->SetBlock(this);
830 phi->SetId(GetGraph()->GetNextInstructionId());
831 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100832 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100833}
834
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100835static void Remove(HInstructionList* instruction_list,
836 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000837 HInstruction* instruction,
838 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100839 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100840 instruction->SetBlock(nullptr);
841 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000842 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100843 DCHECK(instruction->GetUses().empty());
844 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000845 RemoveAsUser(instruction);
846 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100847}
848
David Brazdil1abb4192015-02-17 18:33:36 +0000849void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100850 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000851 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100852}
853
David Brazdil1abb4192015-02-17 18:33:36 +0000854void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
855 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100856}
857
David Brazdilc7508e92015-04-27 13:28:57 +0100858void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
859 if (instruction->IsPhi()) {
860 RemovePhi(instruction->AsPhi(), ensure_safety);
861 } else {
862 RemoveInstruction(instruction, ensure_safety);
863 }
864}
865
Vladimir Marko71bf8092015-09-15 15:33:14 +0100866void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
867 for (size_t i = 0; i < locals.size(); i++) {
868 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100869 SetRawEnvAt(i, instruction);
870 if (instruction != nullptr) {
871 instruction->AddEnvUseAt(this, i);
872 }
873 }
874}
875
David Brazdiled596192015-01-23 10:39:45 +0000876void HEnvironment::CopyFrom(HEnvironment* env) {
877 for (size_t i = 0; i < env->Size(); i++) {
878 HInstruction* instruction = env->GetInstructionAt(i);
879 SetRawEnvAt(i, instruction);
880 if (instruction != nullptr) {
881 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100882 }
David Brazdiled596192015-01-23 10:39:45 +0000883 }
884}
885
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700886void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
887 HBasicBlock* loop_header) {
888 DCHECK(loop_header->IsLoopHeader());
889 for (size_t i = 0; i < env->Size(); i++) {
890 HInstruction* instruction = env->GetInstructionAt(i);
891 SetRawEnvAt(i, instruction);
892 if (instruction == nullptr) {
893 continue;
894 }
895 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
896 // At the end of the loop pre-header, the corresponding value for instruction
897 // is the first input of the phi.
898 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700899 SetRawEnvAt(i, initial);
900 initial->AddEnvUseAt(this, i);
901 } else {
902 instruction->AddEnvUseAt(this, i);
903 }
904 }
905}
906
David Brazdil1abb4192015-02-17 18:33:36 +0000907void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100908 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
909 HInstruction* user = env_use.GetInstruction();
910 auto before_env_use_node = env_use.GetBeforeUseNode();
911 user->env_uses_.erase_after(before_env_use_node);
912 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100913}
914
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000915HInstruction::InstructionKind HInstruction::GetKind() const {
916 return GetKindInternal();
917}
918
Calin Juravle77520bc2015-01-12 18:45:46 +0000919HInstruction* HInstruction::GetNextDisregardingMoves() const {
920 HInstruction* next = GetNext();
921 while (next != nullptr && next->IsParallelMove()) {
922 next = next->GetNext();
923 }
924 return next;
925}
926
927HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
928 HInstruction* previous = GetPrevious();
929 while (previous != nullptr && previous->IsParallelMove()) {
930 previous = previous->GetPrevious();
931 }
932 return previous;
933}
934
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100935void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000936 if (first_instruction_ == nullptr) {
937 DCHECK(last_instruction_ == nullptr);
938 first_instruction_ = last_instruction_ = instruction;
939 } else {
940 last_instruction_->next_ = instruction;
941 instruction->previous_ = last_instruction_;
942 last_instruction_ = instruction;
943 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000944}
945
David Brazdilc3d743f2015-04-22 13:40:50 +0100946void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
947 DCHECK(Contains(cursor));
948 if (cursor == first_instruction_) {
949 cursor->previous_ = instruction;
950 instruction->next_ = cursor;
951 first_instruction_ = instruction;
952 } else {
953 instruction->previous_ = cursor->previous_;
954 instruction->next_ = cursor;
955 cursor->previous_ = instruction;
956 instruction->previous_->next_ = instruction;
957 }
958}
959
960void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
961 DCHECK(Contains(cursor));
962 if (cursor == last_instruction_) {
963 cursor->next_ = instruction;
964 instruction->previous_ = cursor;
965 last_instruction_ = instruction;
966 } else {
967 instruction->next_ = cursor->next_;
968 instruction->previous_ = cursor;
969 cursor->next_ = instruction;
970 instruction->next_->previous_ = instruction;
971 }
972}
973
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100974void HInstructionList::RemoveInstruction(HInstruction* instruction) {
975 if (instruction->previous_ != nullptr) {
976 instruction->previous_->next_ = instruction->next_;
977 }
978 if (instruction->next_ != nullptr) {
979 instruction->next_->previous_ = instruction->previous_;
980 }
981 if (instruction == first_instruction_) {
982 first_instruction_ = instruction->next_;
983 }
984 if (instruction == last_instruction_) {
985 last_instruction_ = instruction->previous_;
986 }
987}
988
Roland Levillain6b469232014-09-25 10:10:38 +0100989bool HInstructionList::Contains(HInstruction* instruction) const {
990 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
991 if (it.Current() == instruction) {
992 return true;
993 }
994 }
995 return false;
996}
997
Roland Levillainccc07a92014-09-16 14:48:16 +0100998bool HInstructionList::FoundBefore(const HInstruction* instruction1,
999 const HInstruction* instruction2) const {
1000 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1001 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1002 if (it.Current() == instruction1) {
1003 return true;
1004 }
1005 if (it.Current() == instruction2) {
1006 return false;
1007 }
1008 }
1009 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1010 return true;
1011}
1012
Roland Levillain6c82d402014-10-13 16:10:27 +01001013bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1014 if (other_instruction == this) {
1015 // An instruction does not strictly dominate itself.
1016 return false;
1017 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001018 HBasicBlock* block = GetBlock();
1019 HBasicBlock* other_block = other_instruction->GetBlock();
1020 if (block != other_block) {
1021 return GetBlock()->Dominates(other_instruction->GetBlock());
1022 } else {
1023 // If both instructions are in the same block, ensure this
1024 // instruction comes before `other_instruction`.
1025 if (IsPhi()) {
1026 if (!other_instruction->IsPhi()) {
1027 // Phis appear before non phi-instructions so this instruction
1028 // dominates `other_instruction`.
1029 return true;
1030 } else {
1031 // There is no order among phis.
1032 LOG(FATAL) << "There is no dominance between phis of a same block.";
1033 return false;
1034 }
1035 } else {
1036 // `this` is not a phi.
1037 if (other_instruction->IsPhi()) {
1038 // Phis appear before non phi-instructions so this instruction
1039 // does not dominate `other_instruction`.
1040 return false;
1041 } else {
1042 // Check whether this instruction comes before
1043 // `other_instruction` in the instruction list.
1044 return block->GetInstructions().FoundBefore(this, other_instruction);
1045 }
1046 }
1047 }
1048}
1049
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001050void HInstruction::RemoveEnvironment() {
1051 RemoveEnvironmentUses(this);
1052 environment_ = nullptr;
1053}
1054
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001055void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001056 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001057 // Note: fixup_end remains valid across splice_after().
1058 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1059 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1060 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001061
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001062 // Note: env_fixup_end remains valid across splice_after().
1063 auto env_fixup_end =
1064 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1065 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1066 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001067
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001068 DCHECK(uses_.empty());
1069 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001070}
1071
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001072void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001073 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001074 if (input_use.GetInstruction() == replacement) {
1075 // Nothing to do.
1076 return;
1077 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001078 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001079 // Note: fixup_end remains valid across splice_after().
1080 auto fixup_end =
1081 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1082 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1083 input_use.GetInstruction()->uses_,
1084 before_use_node);
1085 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1086 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001087}
1088
Nicolas Geoffray39468442014-09-02 15:17:15 +01001089size_t HInstruction::EnvironmentSize() const {
1090 return HasEnvironment() ? environment_->Size() : 0;
1091}
1092
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001093void HPhi::AddInput(HInstruction* input) {
1094 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001095 inputs_.push_back(HUserRecord<HInstruction*>(input));
1096 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001097}
1098
David Brazdil2d7352b2015-04-20 14:52:42 +01001099void HPhi::RemoveInputAt(size_t index) {
1100 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001101 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001102 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001103 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001104 InputRecordAt(i).GetUseNode()->SetIndex(i);
1105 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001106}
1107
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001108#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001109void H##name::Accept(HGraphVisitor* visitor) { \
1110 visitor->Visit##name(this); \
1111}
1112
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001113FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001114
1115#undef DEFINE_ACCEPT
1116
1117void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001118 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1119 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001120 if (block != nullptr) {
1121 VisitBasicBlock(block);
1122 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001123 }
1124}
1125
Roland Levillain633021e2014-10-01 14:12:25 +01001126void HGraphVisitor::VisitReversePostOrder() {
1127 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1128 VisitBasicBlock(it.Current());
1129 }
1130}
1131
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001132void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001133 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001134 it.Current()->Accept(this);
1135 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001136 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001137 it.Current()->Accept(this);
1138 }
1139}
1140
Mark Mendelle82549b2015-05-06 10:55:34 -04001141HConstant* HTypeConversion::TryStaticEvaluation() const {
1142 HGraph* graph = GetBlock()->GetGraph();
1143 if (GetInput()->IsIntConstant()) {
1144 int32_t value = GetInput()->AsIntConstant()->GetValue();
1145 switch (GetResultType()) {
1146 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001147 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001149 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001150 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001151 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001152 default:
1153 return nullptr;
1154 }
1155 } else if (GetInput()->IsLongConstant()) {
1156 int64_t value = GetInput()->AsLongConstant()->GetValue();
1157 switch (GetResultType()) {
1158 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001159 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001160 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001161 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001162 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001163 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001164 default:
1165 return nullptr;
1166 }
1167 } else if (GetInput()->IsFloatConstant()) {
1168 float value = GetInput()->AsFloatConstant()->GetValue();
1169 switch (GetResultType()) {
1170 case Primitive::kPrimInt:
1171 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001172 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001173 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001174 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001175 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001176 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1177 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001178 case Primitive::kPrimLong:
1179 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001180 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001181 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001182 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001183 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001184 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1185 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001186 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001187 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001188 default:
1189 return nullptr;
1190 }
1191 } else if (GetInput()->IsDoubleConstant()) {
1192 double value = GetInput()->AsDoubleConstant()->GetValue();
1193 switch (GetResultType()) {
1194 case Primitive::kPrimInt:
1195 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001196 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001197 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001198 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001199 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001200 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1201 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001202 case Primitive::kPrimLong:
1203 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001204 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001205 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001206 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001207 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001208 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1209 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001210 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001211 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001212 default:
1213 return nullptr;
1214 }
1215 }
1216 return nullptr;
1217}
1218
Roland Levillain9240d6a2014-10-20 16:47:04 +01001219HConstant* HUnaryOperation::TryStaticEvaluation() const {
1220 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001221 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001222 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001223 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001224 } else if (kEnableFloatingPointStaticEvaluation) {
1225 if (GetInput()->IsFloatConstant()) {
1226 return Evaluate(GetInput()->AsFloatConstant());
1227 } else if (GetInput()->IsDoubleConstant()) {
1228 return Evaluate(GetInput()->AsDoubleConstant());
1229 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001230 }
1231 return nullptr;
1232}
1233
1234HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001235 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1236 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001237 } else if (GetLeft()->IsLongConstant()) {
1238 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001239 // The binop(long, int) case is only valid for shifts and rotations.
1240 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001241 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1242 } else if (GetRight()->IsLongConstant()) {
1243 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001244 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001245 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001246 // The binop(null, null) case is only valid for equal and not-equal conditions.
1247 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001248 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001249 } else if (kEnableFloatingPointStaticEvaluation) {
1250 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1251 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1252 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1253 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1254 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001255 }
1256 return nullptr;
1257}
Dave Allison20dfc792014-06-16 20:44:29 -07001258
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001259HConstant* HBinaryOperation::GetConstantRight() const {
1260 if (GetRight()->IsConstant()) {
1261 return GetRight()->AsConstant();
1262 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1263 return GetLeft()->AsConstant();
1264 } else {
1265 return nullptr;
1266 }
1267}
1268
1269// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001270// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001271HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1272 HInstruction* most_constant_right = GetConstantRight();
1273 if (most_constant_right == nullptr) {
1274 return nullptr;
1275 } else if (most_constant_right == GetLeft()) {
1276 return GetRight();
1277 } else {
1278 return GetLeft();
1279 }
1280}
1281
Roland Levillain31dd3d62016-02-16 12:21:02 +00001282std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1283 switch (rhs) {
1284 case ComparisonBias::kNoBias:
1285 return os << "no_bias";
1286 case ComparisonBias::kGtBias:
1287 return os << "gt_bias";
1288 case ComparisonBias::kLtBias:
1289 return os << "lt_bias";
1290 default:
1291 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1292 UNREACHABLE();
1293 }
1294}
1295
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001296bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1297 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001298}
1299
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001300bool HInstruction::Equals(HInstruction* other) const {
1301 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001302 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001303 if (!InstructionDataEquals(other)) return false;
1304 if (GetType() != other->GetType()) return false;
1305 if (InputCount() != other->InputCount()) return false;
1306
1307 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1308 if (InputAt(i) != other->InputAt(i)) return false;
1309 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001310 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001311 return true;
1312}
1313
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001314std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1315#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1316 switch (rhs) {
1317 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1318 default:
1319 os << "Unknown instruction kind " << static_cast<int>(rhs);
1320 break;
1321 }
1322#undef DECLARE_CASE
1323 return os;
1324}
1325
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001326void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001327 next_->previous_ = previous_;
1328 if (previous_ != nullptr) {
1329 previous_->next_ = next_;
1330 }
1331 if (block_->instructions_.first_instruction_ == this) {
1332 block_->instructions_.first_instruction_ = next_;
1333 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001334 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001335
1336 previous_ = cursor->previous_;
1337 if (previous_ != nullptr) {
1338 previous_->next_ = this;
1339 }
1340 next_ = cursor;
1341 cursor->previous_ = this;
1342 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001343
1344 if (block_->instructions_.first_instruction_ == cursor) {
1345 block_->instructions_.first_instruction_ = this;
1346 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001347}
1348
Vladimir Markofb337ea2015-11-25 15:25:10 +00001349void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1350 DCHECK(!CanThrow());
1351 DCHECK(!HasSideEffects());
1352 DCHECK(!HasEnvironmentUses());
1353 DCHECK(HasNonEnvironmentUses());
1354 DCHECK(!IsPhi()); // Makes no sense for Phi.
1355 DCHECK_EQ(InputCount(), 0u);
1356
1357 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001358 auto uses_it = GetUses().begin();
1359 auto uses_end = GetUses().end();
1360 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1361 ++uses_it;
1362 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1363 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001364 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001365 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001366 // This instruction has uses in two or more blocks. Find the common dominator.
1367 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001368 for (; uses_it != uses_end; ++uses_it) {
1369 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001370 }
1371 target_block = finder.Get();
1372 DCHECK(target_block != nullptr);
1373 }
1374 // Move to the first dominator not in a loop.
1375 while (target_block->IsInLoop()) {
1376 target_block = target_block->GetDominator();
1377 DCHECK(target_block != nullptr);
1378 }
1379
1380 // Find insertion position.
1381 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001382 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1383 if (use.GetUser()->GetBlock() == target_block &&
1384 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1385 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001386 }
1387 }
1388 if (insert_pos == nullptr) {
1389 // No user in `target_block`, insert before the control flow instruction.
1390 insert_pos = target_block->GetLastInstruction();
1391 DCHECK(insert_pos->IsControlFlow());
1392 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1393 if (insert_pos->IsIf()) {
1394 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1395 if (if_input == insert_pos->GetPrevious()) {
1396 insert_pos = if_input;
1397 }
1398 }
1399 }
1400 MoveBefore(insert_pos);
1401}
1402
David Brazdilfc6a86a2015-06-26 10:33:45 +00001403HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001404 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001405 DCHECK_EQ(cursor->GetBlock(), this);
1406
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001407 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1408 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001409 new_block->instructions_.first_instruction_ = cursor;
1410 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1411 instructions_.last_instruction_ = cursor->previous_;
1412 if (cursor->previous_ == nullptr) {
1413 instructions_.first_instruction_ = nullptr;
1414 } else {
1415 cursor->previous_->next_ = nullptr;
1416 cursor->previous_ = nullptr;
1417 }
1418
1419 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001420 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001421
Vladimir Marko60584552015-09-03 13:35:12 +00001422 for (HBasicBlock* successor : GetSuccessors()) {
1423 new_block->successors_.push_back(successor);
1424 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001425 }
Vladimir Marko60584552015-09-03 13:35:12 +00001426 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001427 AddSuccessor(new_block);
1428
David Brazdil56e1acc2015-06-30 15:41:36 +01001429 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001430 return new_block;
1431}
1432
David Brazdild7558da2015-09-22 13:04:14 +01001433HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001434 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001435 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1436
1437 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1438
1439 for (HBasicBlock* predecessor : GetPredecessors()) {
1440 new_block->predecessors_.push_back(predecessor);
1441 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1442 }
1443 predecessors_.clear();
1444 AddPredecessor(new_block);
1445
1446 GetGraph()->AddBlock(new_block);
1447 return new_block;
1448}
1449
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001450HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1451 DCHECK_EQ(cursor->GetBlock(), this);
1452
1453 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1454 cursor->GetDexPc());
1455 new_block->instructions_.first_instruction_ = cursor;
1456 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1457 instructions_.last_instruction_ = cursor->previous_;
1458 if (cursor->previous_ == nullptr) {
1459 instructions_.first_instruction_ = nullptr;
1460 } else {
1461 cursor->previous_->next_ = nullptr;
1462 cursor->previous_ = nullptr;
1463 }
1464
1465 new_block->instructions_.SetBlockOfInstructions(new_block);
1466
1467 for (HBasicBlock* successor : GetSuccessors()) {
1468 new_block->successors_.push_back(successor);
1469 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1470 }
1471 successors_.clear();
1472
1473 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1474 dominated->dominator_ = new_block;
1475 new_block->dominated_blocks_.push_back(dominated);
1476 }
1477 dominated_blocks_.clear();
1478 return new_block;
1479}
1480
1481HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001482 DCHECK(!cursor->IsControlFlow());
1483 DCHECK_NE(instructions_.last_instruction_, cursor);
1484 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001485
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001486 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1487 new_block->instructions_.first_instruction_ = cursor->GetNext();
1488 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1489 cursor->next_->previous_ = nullptr;
1490 cursor->next_ = nullptr;
1491 instructions_.last_instruction_ = cursor;
1492
1493 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001494 for (HBasicBlock* successor : GetSuccessors()) {
1495 new_block->successors_.push_back(successor);
1496 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001497 }
Vladimir Marko60584552015-09-03 13:35:12 +00001498 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001499
Vladimir Marko60584552015-09-03 13:35:12 +00001500 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001501 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001502 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001503 }
Vladimir Marko60584552015-09-03 13:35:12 +00001504 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001505 return new_block;
1506}
1507
David Brazdilec16f792015-08-19 15:04:01 +01001508const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001509 if (EndsWithTryBoundary()) {
1510 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1511 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001512 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001513 return try_boundary;
1514 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001515 DCHECK(IsTryBlock());
1516 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001517 return nullptr;
1518 }
David Brazdilec16f792015-08-19 15:04:01 +01001519 } else if (IsTryBlock()) {
1520 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001521 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001522 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001523 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001524}
1525
David Brazdild7558da2015-09-22 13:04:14 +01001526bool HBasicBlock::HasThrowingInstructions() const {
1527 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1528 if (it.Current()->CanThrow()) {
1529 return true;
1530 }
1531 }
1532 return false;
1533}
1534
David Brazdilfc6a86a2015-06-26 10:33:45 +00001535static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1536 return block.GetPhis().IsEmpty()
1537 && !block.GetInstructions().IsEmpty()
1538 && block.GetFirstInstruction() == block.GetLastInstruction();
1539}
1540
David Brazdil46e2a392015-03-16 17:31:52 +00001541bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001542 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1543}
1544
1545bool HBasicBlock::IsSingleTryBoundary() const {
1546 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001547}
1548
David Brazdil8d5b8b22015-03-24 10:51:52 +00001549bool HBasicBlock::EndsWithControlFlowInstruction() const {
1550 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1551}
1552
David Brazdilb2bd1c52015-03-25 11:17:37 +00001553bool HBasicBlock::EndsWithIf() const {
1554 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1555}
1556
David Brazdilffee3d32015-07-06 11:48:53 +01001557bool HBasicBlock::EndsWithTryBoundary() const {
1558 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1559}
1560
David Brazdilb2bd1c52015-03-25 11:17:37 +00001561bool HBasicBlock::HasSinglePhi() const {
1562 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1563}
1564
David Brazdild26a4112015-11-10 11:07:31 +00001565ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1566 if (EndsWithTryBoundary()) {
1567 // The normal-flow successor of HTryBoundary is always stored at index zero.
1568 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1569 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1570 } else {
1571 // All successors of blocks not ending with TryBoundary are normal.
1572 return ArrayRef<HBasicBlock* const>(successors_);
1573 }
1574}
1575
1576ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1577 if (EndsWithTryBoundary()) {
1578 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1579 } else {
1580 // Blocks not ending with TryBoundary do not have exceptional successors.
1581 return ArrayRef<HBasicBlock* const>();
1582 }
1583}
1584
David Brazdilffee3d32015-07-06 11:48:53 +01001585bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001586 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1587 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1588
1589 size_t length = handlers1.size();
1590 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001591 return false;
1592 }
1593
David Brazdilb618ade2015-07-29 10:31:29 +01001594 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001595 for (size_t i = 0; i < length; ++i) {
1596 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001597 return false;
1598 }
1599 }
1600 return true;
1601}
1602
David Brazdil2d7352b2015-04-20 14:52:42 +01001603size_t HInstructionList::CountSize() const {
1604 size_t size = 0;
1605 HInstruction* current = first_instruction_;
1606 for (; current != nullptr; current = current->GetNext()) {
1607 size++;
1608 }
1609 return size;
1610}
1611
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001612void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1613 for (HInstruction* current = first_instruction_;
1614 current != nullptr;
1615 current = current->GetNext()) {
1616 current->SetBlock(block);
1617 }
1618}
1619
1620void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1621 DCHECK(Contains(cursor));
1622 if (!instruction_list.IsEmpty()) {
1623 if (cursor == last_instruction_) {
1624 last_instruction_ = instruction_list.last_instruction_;
1625 } else {
1626 cursor->next_->previous_ = instruction_list.last_instruction_;
1627 }
1628 instruction_list.last_instruction_->next_ = cursor->next_;
1629 cursor->next_ = instruction_list.first_instruction_;
1630 instruction_list.first_instruction_->previous_ = cursor;
1631 }
1632}
1633
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001634void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1635 DCHECK(Contains(cursor));
1636 if (!instruction_list.IsEmpty()) {
1637 if (cursor == first_instruction_) {
1638 first_instruction_ = instruction_list.first_instruction_;
1639 } else {
1640 cursor->previous_->next_ = instruction_list.first_instruction_;
1641 }
1642 instruction_list.last_instruction_->next_ = cursor;
1643 instruction_list.first_instruction_->previous_ = cursor->previous_;
1644 cursor->previous_ = instruction_list.last_instruction_;
1645 }
1646}
1647
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001648void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001649 if (IsEmpty()) {
1650 first_instruction_ = instruction_list.first_instruction_;
1651 last_instruction_ = instruction_list.last_instruction_;
1652 } else {
1653 AddAfter(last_instruction_, instruction_list);
1654 }
1655}
1656
David Brazdil04ff4e82015-12-10 13:54:52 +00001657// Should be called on instructions in a dead block in post order. This method
1658// assumes `insn` has been removed from all users with the exception of catch
1659// phis because of missing exceptional edges in the graph. It removes the
1660// instruction from catch phi uses, together with inputs of other catch phis in
1661// the catch block at the same index, as these must be dead too.
1662static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1663 DCHECK(!insn->HasEnvironmentUses());
1664 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001665 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1666 size_t use_index = use.GetIndex();
1667 HBasicBlock* user_block = use.GetUser()->GetBlock();
1668 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001669 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1670 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1671 }
1672 }
1673}
1674
David Brazdil2d7352b2015-04-20 14:52:42 +01001675void HBasicBlock::DisconnectAndDelete() {
1676 // Dominators must be removed after all the blocks they dominate. This way
1677 // a loop header is removed last, a requirement for correct loop information
1678 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001679 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001680
David Brazdil9eeebf62016-03-24 11:18:15 +00001681 // The following steps gradually remove the block from all its dependants in
1682 // post order (b/27683071).
1683
1684 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1685 // We need to do this before step (4) which destroys the predecessor list.
1686 HBasicBlock* loop_update_start = this;
1687 if (IsLoopHeader()) {
1688 HLoopInformation* loop_info = GetLoopInformation();
1689 // All other blocks in this loop should have been removed because the header
1690 // was their dominator.
1691 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1692 DCHECK(!loop_info->IsIrreducible());
1693 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1694 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1695 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001696 }
1697
David Brazdil9eeebf62016-03-24 11:18:15 +00001698 // (2) Disconnect the block from its successors and update their phis.
1699 for (HBasicBlock* successor : successors_) {
1700 // Delete this block from the list of predecessors.
1701 size_t this_index = successor->GetPredecessorIndexOf(this);
1702 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1703
1704 // Check that `successor` has other predecessors, otherwise `this` is the
1705 // dominator of `successor` which violates the order DCHECKed at the top.
1706 DCHECK(!successor->predecessors_.empty());
1707
1708 // Remove this block's entries in the successor's phis. Skip exceptional
1709 // successors because catch phi inputs do not correspond to predecessor
1710 // blocks but throwing instructions. The inputs of the catch phis will be
1711 // updated in step (3).
1712 if (!successor->IsCatchBlock()) {
1713 if (successor->predecessors_.size() == 1u) {
1714 // The successor has just one predecessor left. Replace phis with the only
1715 // remaining input.
1716 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1717 HPhi* phi = phi_it.Current()->AsPhi();
1718 phi->ReplaceWith(phi->InputAt(1 - this_index));
1719 successor->RemovePhi(phi);
1720 }
1721 } else {
1722 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1723 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1724 }
1725 }
1726 }
1727 }
1728 successors_.clear();
1729
1730 // (3) Remove instructions and phis. Instructions should have no remaining uses
1731 // except in catch phis. If an instruction is used by a catch phi at `index`,
1732 // remove `index`-th input of all phis in the catch block since they are
1733 // guaranteed dead. Note that we may miss dead inputs this way but the
1734 // graph will always remain consistent.
1735 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1736 HInstruction* insn = it.Current();
1737 RemoveUsesOfDeadInstruction(insn);
1738 RemoveInstruction(insn);
1739 }
1740 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1741 HPhi* insn = it.Current()->AsPhi();
1742 RemoveUsesOfDeadInstruction(insn);
1743 RemovePhi(insn);
1744 }
1745
1746 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001747 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001748 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001749 // We should not see any back edges as they would have been removed by step (3).
1750 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1751
David Brazdil2d7352b2015-04-20 14:52:42 +01001752 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001753 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1754 // This block is the only normal-flow successor of the TryBoundary which
1755 // makes `predecessor` dead. Since DCE removes blocks in post order,
1756 // exception handlers of this TryBoundary were already visited and any
1757 // remaining handlers therefore must be live. We remove `predecessor` from
1758 // their list of predecessors.
1759 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1760 while (predecessor->GetSuccessors().size() > 1) {
1761 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1762 DCHECK(handler->IsCatchBlock());
1763 predecessor->RemoveSuccessor(handler);
1764 handler->RemovePredecessor(predecessor);
1765 }
1766 }
1767
David Brazdil2d7352b2015-04-20 14:52:42 +01001768 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001769 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1770 if (num_pred_successors == 1u) {
1771 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001772 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1773 // successor. Replace those with a HGoto.
1774 DCHECK(last_instruction->IsIf() ||
1775 last_instruction->IsPackedSwitch() ||
1776 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001777 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001778 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001779 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001780 // The predecessor has no remaining successors and therefore must be dead.
1781 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001782 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001783 predecessor->RemoveInstruction(last_instruction);
1784 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001785 // There are multiple successors left. The removed block might be a successor
1786 // of a PackedSwitch which will be completely removed (perhaps replaced with
1787 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1788 // case, leave `last_instruction` as is for now.
1789 DCHECK(last_instruction->IsPackedSwitch() ||
1790 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001791 }
David Brazdil46e2a392015-03-16 17:31:52 +00001792 }
Vladimir Marko60584552015-09-03 13:35:12 +00001793 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001794
David Brazdil9eeebf62016-03-24 11:18:15 +00001795 // (5) Remove the block from all loops it is included in. Skip the inner-most
1796 // loop if this is the loop header (see definition of `loop_update_start`)
1797 // because the loop header's predecessor list has been destroyed in step (4).
1798 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1799 HLoopInformation* loop_info = it.Current();
1800 loop_info->Remove(this);
1801 if (loop_info->IsBackEdge(*this)) {
1802 // If this was the last back edge of the loop, we deliberately leave the
1803 // loop in an inconsistent state and will fail GraphChecker unless the
1804 // entire loop is removed during the pass.
1805 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001806 }
1807 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001808
David Brazdil9eeebf62016-03-24 11:18:15 +00001809 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001810 dominator_->RemoveDominatedBlock(this);
1811 SetDominator(nullptr);
1812
David Brazdil9eeebf62016-03-24 11:18:15 +00001813 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001814 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001815 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001816}
1817
1818void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001819 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001820 DCHECK(ContainsElement(dominated_blocks_, other));
1821 DCHECK_EQ(GetSingleSuccessor(), other);
1822 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001823 DCHECK(other->GetPhis().IsEmpty());
1824
David Brazdil2d7352b2015-04-20 14:52:42 +01001825 // Move instructions from `other` to `this`.
1826 DCHECK(EndsWithControlFlowInstruction());
1827 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001828 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001829 other->instructions_.SetBlockOfInstructions(this);
1830 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001831
David Brazdil2d7352b2015-04-20 14:52:42 +01001832 // Remove `other` from the loops it is included in.
1833 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1834 HLoopInformation* loop_info = it.Current();
1835 loop_info->Remove(other);
1836 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001837 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001838 }
1839 }
1840
1841 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001842 successors_.clear();
1843 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001844 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001845 successor->ReplacePredecessor(other, this);
1846 }
1847
David Brazdil2d7352b2015-04-20 14:52:42 +01001848 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001849 RemoveDominatedBlock(other);
1850 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1851 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001852 dominated->SetDominator(this);
1853 }
Vladimir Marko60584552015-09-03 13:35:12 +00001854 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001855 other->dominator_ = nullptr;
1856
1857 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001858 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001859
1860 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001861 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001862 other->SetGraph(nullptr);
1863}
1864
1865void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1866 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001867 DCHECK(GetDominatedBlocks().empty());
1868 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001869 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001870 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001871 DCHECK(other->GetPhis().IsEmpty());
1872 DCHECK(!other->IsInLoop());
1873
1874 // Move instructions from `other` to `this`.
1875 instructions_.Add(other->GetInstructions());
1876 other->instructions_.SetBlockOfInstructions(this);
1877
1878 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001879 successors_.clear();
1880 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001881 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001882 successor->ReplacePredecessor(other, this);
1883 }
1884
1885 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001886 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1887 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001888 dominated->SetDominator(this);
1889 }
Vladimir Marko60584552015-09-03 13:35:12 +00001890 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001891 other->dominator_ = nullptr;
1892 other->graph_ = nullptr;
1893}
1894
1895void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001896 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001897 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 predecessor->ReplaceSuccessor(this, other);
1899 }
Vladimir Marko60584552015-09-03 13:35:12 +00001900 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001901 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001902 successor->ReplacePredecessor(this, other);
1903 }
Vladimir Marko60584552015-09-03 13:35:12 +00001904 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1905 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001906 }
1907 GetDominator()->ReplaceDominatedBlock(this, other);
1908 other->SetDominator(GetDominator());
1909 dominator_ = nullptr;
1910 graph_ = nullptr;
1911}
1912
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001913void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001914 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001915 DCHECK(block->GetSuccessors().empty());
1916 DCHECK(block->GetPredecessors().empty());
1917 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001918 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001919 DCHECK(block->GetInstructions().IsEmpty());
1920 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001921
David Brazdilc7af85d2015-05-26 12:05:55 +01001922 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001923 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001924 }
1925
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001926 RemoveElement(reverse_post_order_, block);
1927 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001928 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001929}
1930
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001931void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1932 HBasicBlock* reference,
1933 bool replace_if_back_edge) {
1934 if (block->IsLoopHeader()) {
1935 // Clear the information of which blocks are contained in that loop. Since the
1936 // information is stored as a bit vector based on block ids, we have to update
1937 // it, as those block ids were specific to the callee graph and we are now adding
1938 // these blocks to the caller graph.
1939 block->GetLoopInformation()->ClearAllBlocks();
1940 }
1941
1942 // If not already in a loop, update the loop information.
1943 if (!block->IsInLoop()) {
1944 block->SetLoopInformation(reference->GetLoopInformation());
1945 }
1946
1947 // If the block is in a loop, update all its outward loops.
1948 HLoopInformation* loop_info = block->GetLoopInformation();
1949 if (loop_info != nullptr) {
1950 for (HLoopInformationOutwardIterator loop_it(*block);
1951 !loop_it.Done();
1952 loop_it.Advance()) {
1953 loop_it.Current()->Add(block);
1954 }
1955 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1956 loop_info->ReplaceBackEdge(reference, block);
1957 }
1958 }
1959
1960 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1961 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1962 ? reference->GetTryCatchInformation()
1963 : nullptr;
1964 block->SetTryCatchInformation(try_catch_info);
1965}
1966
Calin Juravle2e768302015-07-28 14:41:11 +00001967HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001968 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001969 // Update the environments in this graph to have the invoke's environment
1970 // as parent.
1971 {
1972 HReversePostOrderIterator it(*this);
1973 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1974 for (; !it.Done(); it.Advance()) {
1975 HBasicBlock* block = it.Current();
1976 for (HInstructionIterator instr_it(block->GetInstructions());
1977 !instr_it.Done();
1978 instr_it.Advance()) {
1979 HInstruction* current = instr_it.Current();
1980 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001981 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001982 current->GetEnvironment()->SetAndCopyParentChain(
1983 outer_graph->GetArena(), invoke->GetEnvironment());
1984 }
1985 }
1986 }
1987 }
1988 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1989 if (HasBoundsChecks()) {
1990 outer_graph->SetHasBoundsChecks(true);
1991 }
1992
Calin Juravle2e768302015-07-28 14:41:11 +00001993 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001994 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001995 // Simple case of an entry block, a body block, and an exit block.
1996 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001997 HBasicBlock* body = GetBlocks()[1];
1998 DCHECK(GetBlocks()[0]->IsEntryBlock());
1999 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002000 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002001 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002002 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002003
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002004 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2005 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002006 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002007
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002008 // Replace the invoke with the return value of the inlined graph.
2009 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002010 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002011 } else {
2012 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002013 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002014
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002015 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002016 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002017 // Need to inline multiple blocks. We split `invoke`'s block
2018 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002019 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002020 // with the second half.
2021 ArenaAllocator* allocator = outer_graph->GetArena();
2022 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002023 // Note that we split before the invoke only to simplify polymorphic inlining.
2024 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002025
Vladimir Markoec7802a2015-10-01 20:57:57 +01002026 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002027 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002028 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002029 exit_block_->ReplaceWith(to);
2030
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002031 // Update the meta information surrounding blocks:
2032 // (1) the graph they are now in,
2033 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002034 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002035 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002036 // Note that we do not need to update catch phi inputs because they
2037 // correspond to the register file of the outer method which the inlinee
2038 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002039
2040 // We don't add the entry block, the exit block, and the first block, which
2041 // has been merged with `at`.
2042 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2043
2044 // We add the `to` block.
2045 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002046 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002047 + kNumberOfNewBlocksInCaller;
2048
2049 // Find the location of `at` in the outer graph's reverse post order. The new
2050 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002051 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002052 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2053
David Brazdil95177982015-10-30 12:56:58 -05002054 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2055 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002056 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2057 HBasicBlock* current = it.Current();
2058 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002059 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002060 DCHECK(current->GetGraph() == this);
2061 current->SetGraph(outer_graph);
2062 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002063 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002064 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002065 }
2066 }
2067
David Brazdil95177982015-10-30 12:56:58 -05002068 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002069 to->SetGraph(outer_graph);
2070 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002071 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002072 // Only `to` can become a back edge, as the inlined blocks
2073 // are predecessors of `to`.
2074 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002075
David Brazdil3f523062016-02-29 16:53:33 +00002076 // Update all predecessors of the exit block (now the `to` block)
2077 // to not `HReturn` but `HGoto` instead.
2078 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2079 if (to->GetPredecessors().size() == 1) {
2080 HBasicBlock* predecessor = to->GetPredecessors()[0];
2081 HInstruction* last = predecessor->GetLastInstruction();
2082 if (!returns_void) {
2083 return_value = last->InputAt(0);
2084 }
2085 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2086 predecessor->RemoveInstruction(last);
2087 } else {
2088 if (!returns_void) {
2089 // There will be multiple returns.
2090 return_value = new (allocator) HPhi(
2091 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2092 to->AddPhi(return_value->AsPhi());
2093 }
2094 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2095 HInstruction* last = predecessor->GetLastInstruction();
2096 if (!returns_void) {
2097 DCHECK(last->IsReturn());
2098 return_value->AsPhi()->AddInput(last->InputAt(0));
2099 }
2100 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2101 predecessor->RemoveInstruction(last);
2102 }
2103 }
2104 }
David Brazdil05144f42015-04-16 15:18:00 +01002105
2106 // Walk over the entry block and:
2107 // - Move constants from the entry block to the outer_graph's entry block,
2108 // - Replace HParameterValue instructions with their real value.
2109 // - Remove suspend checks, that hold an environment.
2110 // We must do this after the other blocks have been inlined, otherwise ids of
2111 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002112 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002113 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2114 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002115 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002116 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002117 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002118 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002119 replacement = outer_graph->GetIntConstant(
2120 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002121 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002122 replacement = outer_graph->GetLongConstant(
2123 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002124 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002125 replacement = outer_graph->GetFloatConstant(
2126 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002127 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002128 replacement = outer_graph->GetDoubleConstant(
2129 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002130 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002131 if (kIsDebugBuild
2132 && invoke->IsInvokeStaticOrDirect()
2133 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2134 // Ensure we do not use the last input of `invoke`, as it
2135 // contains a clinit check which is not an actual argument.
2136 size_t last_input_index = invoke->InputCount() - 1;
2137 DCHECK(parameter_index != last_input_index);
2138 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002139 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002140 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002141 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002142 } else {
2143 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2144 entry_block_->RemoveInstruction(current);
2145 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002146 if (replacement != nullptr) {
2147 current->ReplaceWith(replacement);
2148 // If the current is the return value then we need to update the latter.
2149 if (current == return_value) {
2150 DCHECK_EQ(entry_block_, return_value->GetBlock());
2151 return_value = replacement;
2152 }
2153 }
2154 }
2155
Calin Juravle2e768302015-07-28 14:41:11 +00002156 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002157}
2158
Mingyao Yang3584bce2015-05-19 16:01:59 -07002159/*
2160 * Loop will be transformed to:
2161 * old_pre_header
2162 * |
2163 * if_block
2164 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002165 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002166 * \ /
2167 * new_pre_header
2168 * |
2169 * header
2170 */
2171void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2172 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002173 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002174
Aart Bik3fc7f352015-11-20 22:03:03 -08002175 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002176 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002177 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2178 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002179 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2180 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002181 AddBlock(true_block);
2182 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002183 AddBlock(new_pre_header);
2184
Aart Bik3fc7f352015-11-20 22:03:03 -08002185 header->ReplacePredecessor(old_pre_header, new_pre_header);
2186 old_pre_header->successors_.clear();
2187 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002188
Aart Bik3fc7f352015-11-20 22:03:03 -08002189 old_pre_header->AddSuccessor(if_block);
2190 if_block->AddSuccessor(true_block); // True successor
2191 if_block->AddSuccessor(false_block); // False successor
2192 true_block->AddSuccessor(new_pre_header);
2193 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002194
Aart Bik3fc7f352015-11-20 22:03:03 -08002195 old_pre_header->dominated_blocks_.push_back(if_block);
2196 if_block->SetDominator(old_pre_header);
2197 if_block->dominated_blocks_.push_back(true_block);
2198 true_block->SetDominator(if_block);
2199 if_block->dominated_blocks_.push_back(false_block);
2200 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002201 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002202 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002203 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002204 header->SetDominator(new_pre_header);
2205
Aart Bik3fc7f352015-11-20 22:03:03 -08002206 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002207 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002208 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002209 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002210 reverse_post_order_[index_of_header++] = true_block;
2211 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002212 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002213
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002214 // The pre_header can never be a back edge of a loop.
2215 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2216 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2217 UpdateLoopAndTryInformationOfNewBlock(
2218 if_block, old_pre_header, /* replace_if_back_edge */ false);
2219 UpdateLoopAndTryInformationOfNewBlock(
2220 true_block, old_pre_header, /* replace_if_back_edge */ false);
2221 UpdateLoopAndTryInformationOfNewBlock(
2222 false_block, old_pre_header, /* replace_if_back_edge */ false);
2223 UpdateLoopAndTryInformationOfNewBlock(
2224 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002225}
2226
David Brazdilf5552582015-12-27 13:36:12 +00002227static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2228 SHARED_REQUIRES(Locks::mutator_lock_) {
2229 if (rti.IsValid()) {
2230 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2231 << " upper_bound_rti: " << upper_bound_rti
2232 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002233 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2234 << " upper_bound_rti: " << upper_bound_rti
2235 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002236 }
2237}
2238
Calin Juravle2e768302015-07-28 14:41:11 +00002239void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2240 if (kIsDebugBuild) {
2241 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2242 ScopedObjectAccess soa(Thread::Current());
2243 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2244 if (IsBoundType()) {
2245 // Having the test here spares us from making the method virtual just for
2246 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002247 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002248 }
2249 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002250 reference_type_handle_ = rti.GetTypeHandle();
2251 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002252}
2253
David Brazdilf5552582015-12-27 13:36:12 +00002254void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2255 if (kIsDebugBuild) {
2256 ScopedObjectAccess soa(Thread::Current());
2257 DCHECK(upper_bound.IsValid());
2258 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2259 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2260 }
2261 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002262 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002263}
2264
Vladimir Markoa1de9182016-02-25 11:37:38 +00002265ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002266 if (kIsDebugBuild) {
2267 ScopedObjectAccess soa(Thread::Current());
2268 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002269 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002270 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002271 if (!is_exact) {
2272 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2273 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2274 }
Calin Juravle2e768302015-07-28 14:41:11 +00002275 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002276 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002277}
2278
Calin Juravleacf735c2015-02-12 15:25:22 +00002279std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2280 ScopedObjectAccess soa(Thread::Current());
2281 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002282 << " is_valid=" << rhs.IsValid()
2283 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002284 << " is_exact=" << rhs.IsExact()
2285 << " ]";
2286 return os;
2287}
2288
Mark Mendellc4701932015-04-10 13:18:51 -04002289bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2290 // For now, assume that instructions in different blocks may use the
2291 // environment.
2292 // TODO: Use the control flow to decide if this is true.
2293 if (GetBlock() != other->GetBlock()) {
2294 return true;
2295 }
2296
2297 // We know that we are in the same block. Walk from 'this' to 'other',
2298 // checking to see if there is any instruction with an environment.
2299 HInstruction* current = this;
2300 for (; current != other && current != nullptr; current = current->GetNext()) {
2301 // This is a conservative check, as the instruction result may not be in
2302 // the referenced environment.
2303 if (current->HasEnvironment()) {
2304 return true;
2305 }
2306 }
2307
2308 // We should have been called with 'this' before 'other' in the block.
2309 // Just confirm this.
2310 DCHECK(current != nullptr);
2311 return false;
2312}
2313
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002314void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002315 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2316 IntrinsicSideEffects side_effects,
2317 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002318 intrinsic_ = intrinsic;
2319 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002320
Aart Bik5d75afe2015-12-14 11:57:01 -08002321 // Adjust method's side effects from intrinsic table.
2322 switch (side_effects) {
2323 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2324 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2325 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2326 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2327 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002328
2329 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2330 opt.SetDoesNotNeedDexCache();
2331 opt.SetDoesNotNeedEnvironment();
2332 } else {
2333 // If we need an environment, that means there will be a call, which can trigger GC.
2334 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2335 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002336 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002337 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002338}
2339
David Brazdil6de19382016-01-08 17:37:10 +00002340bool HNewInstance::IsStringAlloc() const {
2341 ScopedObjectAccess soa(Thread::Current());
2342 return GetReferenceTypeInfo().IsStringClass();
2343}
2344
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002345bool HInvoke::NeedsEnvironment() const {
2346 if (!IsIntrinsic()) {
2347 return true;
2348 }
2349 IntrinsicOptimizations opt(*this);
2350 return !opt.GetDoesNotNeedEnvironment();
2351}
2352
Vladimir Markodc151b22015-10-15 18:02:30 +01002353bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2354 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002355 return false;
2356 }
2357 if (!IsIntrinsic()) {
2358 return true;
2359 }
2360 IntrinsicOptimizations opt(*this);
2361 return !opt.GetDoesNotNeedDexCache();
2362}
2363
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002364void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2365 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2366 input->AddUseAt(this, index);
2367 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2368 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2369 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2370 InputRecordAt(i).GetUseNode()->SetIndex(i);
2371 }
2372}
2373
Vladimir Markob554b5a2015-11-06 12:57:55 +00002374void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2375 RemoveAsUserOfInput(index);
2376 inputs_.erase(inputs_.begin() + index);
2377 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2378 for (size_t i = index, e = InputCount(); i < e; ++i) {
2379 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2380 InputRecordAt(i).GetUseNode()->SetIndex(i);
2381 }
2382}
2383
Vladimir Markof64242a2015-12-01 14:58:23 +00002384std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2385 switch (rhs) {
2386 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2387 return os << "string_init";
2388 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2389 return os << "recursive";
2390 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2391 return os << "direct";
2392 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2393 return os << "direct_fixup";
2394 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2395 return os << "dex_cache_pc_relative";
2396 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2397 return os << "dex_cache_via_method";
2398 default:
2399 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2400 UNREACHABLE();
2401 }
2402}
2403
Vladimir Markofbb184a2015-11-13 14:47:00 +00002404std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2405 switch (rhs) {
2406 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2407 return os << "explicit";
2408 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2409 return os << "implicit";
2410 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2411 return os << "none";
2412 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002413 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2414 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002415 }
2416}
2417
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002418bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2419 HLoadString* other_load_string = other->AsLoadString();
2420 if (string_index_ != other_load_string->string_index_ ||
2421 GetPackedFields() != other_load_string->GetPackedFields()) {
2422 return false;
2423 }
2424 LoadKind load_kind = GetLoadKind();
2425 if (HasAddress(load_kind)) {
2426 return GetAddress() == other_load_string->GetAddress();
2427 } else if (HasStringReference(load_kind)) {
2428 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2429 } else {
2430 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2431 // If the string indexes and dex files are the same, dex cache element offsets
2432 // must also be the same, so we don't need to compare them.
2433 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2434 }
2435}
2436
2437void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2438 // Once sharpened, the load kind should not be changed again.
2439 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2440 SetPackedField<LoadKindField>(load_kind);
2441
2442 if (load_kind != LoadKind::kDexCacheViaMethod) {
2443 RemoveAsUserOfInput(0u);
2444 SetRawInputAt(0u, nullptr);
2445 }
2446 if (!NeedsEnvironment()) {
2447 RemoveEnvironment();
2448 }
2449}
2450
2451std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2452 switch (rhs) {
2453 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2454 return os << "BootImageLinkTimeAddress";
2455 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2456 return os << "BootImageLinkTimePcRelative";
2457 case HLoadString::LoadKind::kBootImageAddress:
2458 return os << "BootImageAddress";
2459 case HLoadString::LoadKind::kDexCacheAddress:
2460 return os << "DexCacheAddress";
2461 case HLoadString::LoadKind::kDexCachePcRelative:
2462 return os << "DexCachePcRelative";
2463 case HLoadString::LoadKind::kDexCacheViaMethod:
2464 return os << "DexCacheViaMethod";
2465 default:
2466 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2467 UNREACHABLE();
2468 }
2469}
2470
Mark Mendellc4701932015-04-10 13:18:51 -04002471void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002472 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2473 HEnvironment* user = use.GetUser();
2474 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002475 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002476 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002477}
2478
Roland Levillainc9b21f82016-03-23 16:36:59 +00002479// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002480HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2481 ArenaAllocator* allocator = GetArena();
2482
2483 if (cond->IsCondition() &&
2484 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2485 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2486 HInstruction* lhs = cond->InputAt(0);
2487 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002488 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002489 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2490 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2491 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2492 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2493 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2494 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2495 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2496 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2497 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2498 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2499 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002500 default:
2501 LOG(FATAL) << "Unexpected condition";
2502 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002503 }
2504 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2505 return replacement;
2506 } else if (cond->IsIntConstant()) {
2507 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002508 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002509 return GetIntConstant(1);
2510 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002511 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002512 return GetIntConstant(0);
2513 }
2514 } else {
2515 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2516 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2517 return replacement;
2518 }
2519}
2520
Roland Levillainc9285912015-12-18 10:38:42 +00002521std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2522 os << "["
2523 << " source=" << rhs.GetSource()
2524 << " destination=" << rhs.GetDestination()
2525 << " type=" << rhs.GetType()
2526 << " instruction=";
2527 if (rhs.GetInstruction() != nullptr) {
2528 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2529 } else {
2530 os << "null";
2531 }
2532 os << " ]";
2533 return os;
2534}
2535
Roland Levillain86503782016-02-11 19:07:30 +00002536std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2537 switch (rhs) {
2538 case TypeCheckKind::kUnresolvedCheck:
2539 return os << "unresolved_check";
2540 case TypeCheckKind::kExactCheck:
2541 return os << "exact_check";
2542 case TypeCheckKind::kClassHierarchyCheck:
2543 return os << "class_hierarchy_check";
2544 case TypeCheckKind::kAbstractClassCheck:
2545 return os << "abstract_class_check";
2546 case TypeCheckKind::kInterfaceCheck:
2547 return os << "interface_check";
2548 case TypeCheckKind::kArrayObjectCheck:
2549 return os << "array_object_check";
2550 case TypeCheckKind::kArrayCheck:
2551 return os << "array_check";
2552 default:
2553 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2554 UNREACHABLE();
2555 }
2556}
2557
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002558} // namespace art