blob: 3a1864b2ae53b85eb7e8fd435e1f1618a8159661 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Artem Serov21c7e6f2017-07-27 16:04:42 +010093// Remove the environment use records of the instruction for users.
94void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010095 for (HEnvironment* environment = instruction->GetEnvironment();
96 environment != nullptr;
97 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000099 if (environment->GetInstructionAt(i) != nullptr) {
100 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000101 }
102 }
103 }
104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Return whether the instruction has an environment and it's used by others.
107bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
112 HInstruction* user = environment->GetInstructionAt(i);
113 if (user != nullptr) {
114 return true;
115 }
116 }
117 }
118 return false;
119}
120
121// Reset environment records of the instruction itself.
122void ResetEnvironmentInputRecords(HInstruction* instruction) {
123 for (HEnvironment* environment = instruction->GetEnvironment();
124 environment != nullptr;
125 environment = environment->GetParent()) {
126 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
127 DCHECK(environment->GetHolder() == instruction);
128 if (environment->GetInstructionAt(i) != nullptr) {
129 environment->SetRawEnvAt(i, nullptr);
130 }
131 }
132 }
133}
134
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000135static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100136 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000137 RemoveEnvironmentUses(instruction);
138}
139
Roland Levillainfc600dc2014-12-02 17:16:31 +0000140void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100141 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000142 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100143 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100145 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
147 RemoveAsUser(it.Current());
148 }
149 }
150 }
151}
152
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100153void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000159 for (HBasicBlock* successor : block->GetSuccessors()) {
160 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000161 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // Remove the block from the list of blocks, so that further analyses
163 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600165 if (block->IsExitBlock()) {
166 SetExitBlock(nullptr);
167 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // Mark the block as removed. This is used by the HGraphBuilder to discard
169 // the block as a branch target.
170 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172 }
173}
174
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000176 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177
David Brazdil86ea7ee2016-02-16 09:26:07 +0000178 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 FindBackEdges(&visited);
180
David Brazdil86ea7ee2016-02-16 09:26:07 +0000181 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000182 // the initial DFS as users from other instructions, so that
183 // users can be safely removed before uses later.
184 RemoveInstructionsAsUsersFromDeadBlocks(visited);
185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 // predecessors list of live blocks.
189 RemoveDeadBlocks(visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 // dominators and the reverse post order.
193 SimplifyCFG();
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197
David Brazdil86ea7ee2016-02-16 09:26:07 +0000198 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000199 // set the loop information on each block.
200 GraphAnalysisResult result = AnalyzeLoops();
201 if (result != kAnalysisSuccess) {
202 return result;
203 }
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206 // which needs the information to build catch block phis from values of
207 // locals at throwing instructions inside try blocks.
208 ComputeTryBlockInformation();
209
210 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211}
212
213void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100214 for (HBasicBlock* block : GetReversePostOrder()) {
215 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100216 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100217 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100218}
219
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000220void HGraph::ClearLoopInformation() {
221 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000228 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229 dominator_ = nullptr;
230}
231
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000232HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
233 HInstruction* instruction = GetFirstInstruction();
234 while (instruction->IsParallelMove()) {
235 instruction = instruction->GetNext();
236 }
237 return instruction;
238}
239
David Brazdil3f4a5222016-05-06 12:46:21 +0100240static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
241 DCHECK(ContainsElement(block->GetSuccessors(), successor));
242
243 HBasicBlock* old_dominator = successor->GetDominator();
244 HBasicBlock* new_dominator =
245 (old_dominator == nullptr) ? block
246 : CommonDominator::ForPair(old_dominator, block);
247
248 if (old_dominator == new_dominator) {
249 return false;
250 } else {
251 successor->SetDominator(new_dominator);
252 return true;
253 }
254}
255
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100256void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100257 DCHECK(reverse_post_order_.empty());
258 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100259 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100260
261 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100262 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100263 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100264 ArenaVector<size_t> successors_visited(blocks_.size(),
265 0u,
266 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100267 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100268 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100269 constexpr size_t kDefaultWorklistSize = 8;
270 worklist.reserve(kDefaultWorklistSize);
271 worklist.push_back(entry_block_);
272
273 while (!worklist.empty()) {
274 HBasicBlock* current = worklist.back();
275 uint32_t current_id = current->GetBlockId();
276 if (successors_visited[current_id] == current->GetSuccessors().size()) {
277 worklist.pop_back();
278 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100280 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100281
282 // Once all the forward edges have been visited, we know the immediate
283 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100284 if (++visits[successor->GetBlockId()] ==
285 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100286 reverse_post_order_.push_back(successor);
287 worklist.push_back(successor);
288 }
289 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000290 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000291
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 // Check if the graph has back edges not dominated by their respective headers.
293 // If so, we need to update the dominators of those headers and recursively of
294 // their successors. We do that with a fix-point iteration over all blocks.
295 // The algorithm is guaranteed to terminate because it loops only if the sum
296 // of all dominator chains has decreased in the current iteration.
297 bool must_run_fix_point = false;
298 for (HBasicBlock* block : blocks_) {
299 if (block != nullptr &&
300 block->IsLoopHeader() &&
301 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
302 must_run_fix_point = true;
303 break;
304 }
305 }
306 if (must_run_fix_point) {
307 bool update_occurred = true;
308 while (update_occurred) {
309 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100310 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100311 for (HBasicBlock* successor : block->GetSuccessors()) {
312 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
313 }
314 }
315 }
316 }
317
318 // Make sure that there are no remaining blocks whose dominator information
319 // needs to be updated.
320 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100321 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100322 for (HBasicBlock* successor : block->GetSuccessors()) {
323 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
324 }
325 }
326 }
327
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000328 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000329 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100330 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000331 if (!block->IsEntryBlock()) {
332 block->GetDominator()->AddDominatedBlock(block);
333 }
334 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000335}
336
David Brazdilfc6a86a2015-06-26 10:33:45 +0000337HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000338 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
339 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000340 // Use `InsertBetween` to ensure the predecessor index and successor index of
341 // `block` and `successor` are preserved.
342 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000343 return new_block;
344}
345
346void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
347 // Insert a new node between `block` and `successor` to split the
348 // critical edge.
349 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600350 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100351 if (successor->IsLoopHeader()) {
352 // If we split at a back edge boundary, make the new block the back edge.
353 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000354 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355 info->RemoveBackEdge(block);
356 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100357 }
358 }
359}
360
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361void HGraph::SimplifyLoop(HBasicBlock* header) {
362 HLoopInformation* info = header->GetLoopInformation();
363
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100364 // Make sure the loop has only one pre header. This simplifies SSA building by having
365 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000366 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
367 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000368 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000369 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100370 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100371 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600372 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100373
Vladimir Marko60584552015-09-03 13:35:12 +0000374 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100375 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100376 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100377 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100378 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100379 }
380 }
381 pre_header->AddSuccessor(header);
382 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100383
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100384 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100385 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
386 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000387 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100388 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100389 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000390 header->predecessors_[pred] = to_swap;
391 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100392 break;
393 }
394 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100395 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100396
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100397 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000398 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
399 // Called from DeadBlockElimination. Update SuspendCheck pointer.
400 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100401 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402}
403
David Brazdilffee3d32015-07-06 11:48:53 +0100404void HGraph::ComputeTryBlockInformation() {
405 // Iterate in reverse post order to propagate try membership information from
406 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100407 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100408 if (block->IsEntryBlock() || block->IsCatchBlock()) {
409 // Catch blocks after simplification have only exceptional predecessors
410 // and hence are never in tries.
411 continue;
412 }
413
414 // Infer try membership from the first predecessor. Having simplified loops,
415 // the first predecessor can never be a back edge and therefore it must have
416 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100417 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100418 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100419 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000420 if (try_entry != nullptr &&
421 (block->GetTryCatchInformation() == nullptr ||
422 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
423 // We are either setting try block membership for the first time or it
424 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100425 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
426 }
David Brazdilffee3d32015-07-06 11:48:53 +0100427 }
428}
429
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000431// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100432 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000433 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100434 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
435 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
436 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
437 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100438 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000439 if (block->GetSuccessors().size() > 1) {
440 // Only split normal-flow edges. We cannot split exceptional edges as they
441 // are synthesized (approximate real control flow), and we do not need to
442 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000443 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
444 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
445 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100446 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000447 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000448 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
449 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000450 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000451 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100452 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000453 // SplitCriticalEdge could have invalidated the `normal_successors`
454 // ArrayRef. We must re-acquire it.
455 normal_successors = block->GetNormalSuccessors();
456 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
457 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100458 }
459 }
460 }
461 if (block->IsLoopHeader()) {
462 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000463 } else if (!block->IsEntryBlock() &&
464 block->GetFirstInstruction() != nullptr &&
465 block->GetFirstInstruction()->IsSuspendCheck()) {
466 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000467 // a loop got dismantled. Just remove the suspend check.
468 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100469 }
470 }
471}
472
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000473GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100474 // We iterate post order to ensure we visit inner loops before outer loops.
475 // `PopulateRecursive` needs this guarantee to know whether a natural loop
476 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100477 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100479 if (block->IsCatchBlock()) {
480 // TODO: Dealing with exceptional back edges could be tricky because
481 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000482 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100483 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000484 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100485 }
486 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000487 return kAnalysisSuccess;
488}
489
490void HLoopInformation::Dump(std::ostream& os) {
491 os << "header: " << header_->GetBlockId() << std::endl;
492 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
493 for (HBasicBlock* block : back_edges_) {
494 os << "back edge: " << block->GetBlockId() << std::endl;
495 }
496 for (HBasicBlock* block : header_->GetPredecessors()) {
497 os << "predecessor: " << block->GetBlockId() << std::endl;
498 }
499 for (uint32_t idx : blocks_.Indexes()) {
500 os << " in loop: " << idx << std::endl;
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502}
503
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000505 // New constants are inserted before the SuspendCheck at the bottom of the
506 // entry block. Note that this method can be called from the graph builder and
507 // the entry block therefore may not end with SuspendCheck->Goto yet.
508 HInstruction* insert_before = nullptr;
509
510 HInstruction* gota = entry_block_->GetLastInstruction();
511 if (gota != nullptr && gota->IsGoto()) {
512 HInstruction* suspend_check = gota->GetPrevious();
513 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
514 insert_before = suspend_check;
515 } else {
516 insert_before = gota;
517 }
518 }
519
520 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000521 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000522 } else {
523 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000524 }
525}
526
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600527HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100528 // For simplicity, don't bother reviving the cached null constant if it is
529 // not null and not in a block. Otherwise, we need to clear the instruction
530 // id and/or any invariants the graph is assuming when adding new instructions.
531 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600532 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000533 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000534 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000535 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000536 if (kIsDebugBuild) {
537 ScopedObjectAccess soa(Thread::Current());
538 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
539 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000540 return cached_null_constant_;
541}
542
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100543HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100544 // For simplicity, don't bother reviving the cached current method if it is
545 // not null and not in a block. Otherwise, we need to clear the instruction
546 // id and/or any invariants the graph is assuming when adding new instructions.
547 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700548 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600549 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
550 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100551 if (entry_block_->GetFirstInstruction() == nullptr) {
552 entry_block_->AddInstruction(cached_current_method_);
553 } else {
554 entry_block_->InsertInstructionBefore(
555 cached_current_method_, entry_block_->GetFirstInstruction());
556 }
557 }
558 return cached_current_method_;
559}
560
Igor Murashkind01745e2017-04-05 16:40:31 -0700561const char* HGraph::GetMethodName() const {
562 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
563 return dex_file_.GetMethodName(method_id);
564}
565
566std::string HGraph::PrettyMethod(bool with_signature) const {
567 return dex_file_.PrettyMethod(method_idx_, with_signature);
568}
569
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600570HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000571 switch (type) {
572 case Primitive::Type::kPrimBoolean:
573 DCHECK(IsUint<1>(value));
574 FALLTHROUGH_INTENDED;
575 case Primitive::Type::kPrimByte:
576 case Primitive::Type::kPrimChar:
577 case Primitive::Type::kPrimShort:
578 case Primitive::Type::kPrimInt:
579 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600580 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000581
582 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600583 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000584
585 default:
586 LOG(FATAL) << "Unsupported constant type";
587 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000588 }
David Brazdil46e2a392015-03-16 17:31:52 +0000589}
590
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000591void HGraph::CacheFloatConstant(HFloatConstant* constant) {
592 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
593 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
594 cached_float_constants_.Overwrite(value, constant);
595}
596
597void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
598 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
599 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
600 cached_double_constants_.Overwrite(value, constant);
601}
602
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000603void HLoopInformation::Add(HBasicBlock* block) {
604 blocks_.SetBit(block->GetBlockId());
605}
606
David Brazdil46e2a392015-03-16 17:31:52 +0000607void HLoopInformation::Remove(HBasicBlock* block) {
608 blocks_.ClearBit(block->GetBlockId());
609}
610
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100611void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
612 if (blocks_.IsBitSet(block->GetBlockId())) {
613 return;
614 }
615
616 blocks_.SetBit(block->GetBlockId());
617 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100618 if (block->IsLoopHeader()) {
619 // We're visiting loops in post-order, so inner loops must have been
620 // populated already.
621 DCHECK(block->GetLoopInformation()->IsPopulated());
622 if (block->GetLoopInformation()->IsIrreducible()) {
623 contains_irreducible_loop_ = true;
624 }
625 }
Vladimir Marko60584552015-09-03 13:35:12 +0000626 for (HBasicBlock* predecessor : block->GetPredecessors()) {
627 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100628 }
629}
630
David Brazdilc2e8af92016-04-05 17:15:19 +0100631void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
632 size_t block_id = block->GetBlockId();
633
634 // If `block` is in `finalized`, we know its membership in the loop has been
635 // decided and it does not need to be revisited.
636 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 return;
638 }
639
David Brazdilc2e8af92016-04-05 17:15:19 +0100640 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000641 if (block->IsLoopHeader()) {
642 // If we hit a loop header in an irreducible loop, we first check if the
643 // pre header of that loop belongs to the currently analyzed loop. If it does,
644 // then we visit the back edges.
645 // Note that we cannot use GetPreHeader, as the loop may have not been populated
646 // yet.
647 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100648 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000649 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000650 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100651 blocks_.SetBit(block_id);
652 finalized->SetBit(block_id);
653 is_finalized = true;
654
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 HLoopInformation* info = block->GetLoopInformation();
656 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100657 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000658 }
659 }
660 } else {
661 // Visit all predecessors. If one predecessor is part of the loop, this
662 // block is also part of this loop.
663 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100664 PopulateIrreducibleRecursive(predecessor, finalized);
665 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000666 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100667 blocks_.SetBit(block_id);
668 finalized->SetBit(block_id);
669 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000670 }
671 }
672 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100673
674 // All predecessors have been recursively visited. Mark finalized if not marked yet.
675 if (!is_finalized) {
676 finalized->SetBit(block_id);
677 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000678}
679
680void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100681 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000682 // Populate this loop: starting with the back edge, recursively add predecessors
683 // that are not already part of that loop. Set the header as part of the loop
684 // to end the recursion.
685 // This is a recursive implementation of the algorithm described in
686 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100687 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000688 blocks_.SetBit(header_->GetBlockId());
689 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100690
David Brazdil3f4a5222016-05-06 12:46:21 +0100691 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100692
693 if (is_irreducible_loop) {
694 ArenaBitVector visited(graph->GetArena(),
695 graph->GetBlocks().size(),
696 /* expandable */ false,
697 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100698 // Stop marking blocks at the loop header.
699 visited.SetBit(header_->GetBlockId());
700
David Brazdilc2e8af92016-04-05 17:15:19 +0100701 for (HBasicBlock* back_edge : GetBackEdges()) {
702 PopulateIrreducibleRecursive(back_edge, &visited);
703 }
704 } else {
705 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000706 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100707 }
David Brazdila4b8c212015-05-07 09:59:30 +0100708 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100709
Vladimir Markofd66c502016-04-18 15:37:01 +0100710 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
711 // When compiling in OSR mode, all loops in the compiled method may be entered
712 // from the interpreter. We treat this OSR entry point just like an extra entry
713 // to an irreducible loop, so we need to mark the method's loops as irreducible.
714 // This does not apply to inlined loops which do not act as OSR entry points.
715 if (suspend_check_ == nullptr) {
716 // Just building the graph in OSR mode, this loop is not inlined. We never build an
717 // inner graph in OSR mode as we can do OSR transition only from the outer method.
718 is_irreducible_loop = true;
719 } else {
720 // Look at the suspend check's environment to determine if the loop was inlined.
721 DCHECK(suspend_check_->HasEnvironment());
722 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
723 is_irreducible_loop = true;
724 }
725 }
726 }
727 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100728 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100729 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100730 graph->SetHasIrreducibleLoops(true);
731 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800732 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100733}
734
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100735HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000736 HBasicBlock* block = header_->GetPredecessors()[0];
737 DCHECK(irreducible_ || (block == header_->GetDominator()));
738 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100739}
740
741bool HLoopInformation::Contains(const HBasicBlock& block) const {
742 return blocks_.IsBitSet(block.GetBlockId());
743}
744
745bool HLoopInformation::IsIn(const HLoopInformation& other) const {
746 return other.blocks_.IsBitSet(header_->GetBlockId());
747}
748
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800749bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
750 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700751}
752
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100753size_t HLoopInformation::GetLifetimeEnd() const {
754 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100755 for (HBasicBlock* back_edge : GetBackEdges()) {
756 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100757 }
758 return last_position;
759}
760
David Brazdil3f4a5222016-05-06 12:46:21 +0100761bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
762 for (HBasicBlock* back_edge : GetBackEdges()) {
763 DCHECK(back_edge->GetDominator() != nullptr);
764 if (!header_->Dominates(back_edge)) {
765 return true;
766 }
767 }
768 return false;
769}
770
Anton Shaminf89381f2016-05-16 16:44:13 +0600771bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
772 for (HBasicBlock* back_edge : GetBackEdges()) {
773 if (!block->Dominates(back_edge)) {
774 return false;
775 }
776 }
777 return true;
778}
779
David Sehrc757dec2016-11-04 15:48:34 -0700780
781bool HLoopInformation::HasExitEdge() const {
782 // Determine if this loop has at least one exit edge.
783 HBlocksInLoopReversePostOrderIterator it_loop(*this);
784 for (; !it_loop.Done(); it_loop.Advance()) {
785 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
786 if (!Contains(*successor)) {
787 return true;
788 }
789 }
790 }
791 return false;
792}
793
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100794bool HBasicBlock::Dominates(HBasicBlock* other) const {
795 // Walk up the dominator tree from `other`, to find out if `this`
796 // is an ancestor.
797 HBasicBlock* current = other;
798 while (current != nullptr) {
799 if (current == this) {
800 return true;
801 }
802 current = current->GetDominator();
803 }
804 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100805}
806
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100807static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100808 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100809 for (size_t i = 0; i < inputs.size(); ++i) {
810 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100811 }
812 // Environment should be created later.
813 DCHECK(!instruction->HasEnvironment());
814}
815
Roland Levillainccc07a92014-09-16 14:48:16 +0100816void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
817 HInstruction* replacement) {
818 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400819 if (initial->IsControlFlow()) {
820 // We can only replace a control flow instruction with another control flow instruction.
821 DCHECK(replacement->IsControlFlow());
822 DCHECK_EQ(replacement->GetId(), -1);
823 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
824 DCHECK_EQ(initial->GetBlock(), this);
825 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100826 DCHECK(initial->GetUses().empty());
827 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400828 replacement->SetBlock(this);
829 replacement->SetId(GetGraph()->GetNextInstructionId());
830 instructions_.InsertInstructionBefore(replacement, initial);
831 UpdateInputsUsers(replacement);
832 } else {
833 InsertInstructionBefore(replacement, initial);
834 initial->ReplaceWith(replacement);
835 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100836 RemoveInstruction(initial);
837}
838
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100839static void Add(HInstructionList* instruction_list,
840 HBasicBlock* block,
841 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000842 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000843 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100844 instruction->SetBlock(block);
845 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100846 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100847 instruction_list->AddInstruction(instruction);
848}
849
850void HBasicBlock::AddInstruction(HInstruction* instruction) {
851 Add(&instructions_, this, instruction);
852}
853
854void HBasicBlock::AddPhi(HPhi* phi) {
855 Add(&phis_, this, phi);
856}
857
David Brazdilc3d743f2015-04-22 13:40:50 +0100858void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
859 DCHECK(!cursor->IsPhi());
860 DCHECK(!instruction->IsPhi());
861 DCHECK_EQ(instruction->GetId(), -1);
862 DCHECK_NE(cursor->GetId(), -1);
863 DCHECK_EQ(cursor->GetBlock(), this);
864 DCHECK(!instruction->IsControlFlow());
865 instruction->SetBlock(this);
866 instruction->SetId(GetGraph()->GetNextInstructionId());
867 UpdateInputsUsers(instruction);
868 instructions_.InsertInstructionBefore(instruction, cursor);
869}
870
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100871void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
872 DCHECK(!cursor->IsPhi());
873 DCHECK(!instruction->IsPhi());
874 DCHECK_EQ(instruction->GetId(), -1);
875 DCHECK_NE(cursor->GetId(), -1);
876 DCHECK_EQ(cursor->GetBlock(), this);
877 DCHECK(!instruction->IsControlFlow());
878 DCHECK(!cursor->IsControlFlow());
879 instruction->SetBlock(this);
880 instruction->SetId(GetGraph()->GetNextInstructionId());
881 UpdateInputsUsers(instruction);
882 instructions_.InsertInstructionAfter(instruction, cursor);
883}
884
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100885void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
886 DCHECK_EQ(phi->GetId(), -1);
887 DCHECK_NE(cursor->GetId(), -1);
888 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100889 phi->SetBlock(this);
890 phi->SetId(GetGraph()->GetNextInstructionId());
891 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100892 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100893}
894
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895static void Remove(HInstructionList* instruction_list,
896 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000897 HInstruction* instruction,
898 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100899 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100900 instruction->SetBlock(nullptr);
901 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000902 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100903 DCHECK(instruction->GetUses().empty());
904 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000905 RemoveAsUser(instruction);
906 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100907}
908
David Brazdil1abb4192015-02-17 18:33:36 +0000909void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100910 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000911 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100912}
913
David Brazdil1abb4192015-02-17 18:33:36 +0000914void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
915 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100916}
917
David Brazdilc7508e92015-04-27 13:28:57 +0100918void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
919 if (instruction->IsPhi()) {
920 RemovePhi(instruction->AsPhi(), ensure_safety);
921 } else {
922 RemoveInstruction(instruction, ensure_safety);
923 }
924}
925
Vladimir Marko71bf8092015-09-15 15:33:14 +0100926void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
927 for (size_t i = 0; i < locals.size(); i++) {
928 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100929 SetRawEnvAt(i, instruction);
930 if (instruction != nullptr) {
931 instruction->AddEnvUseAt(this, i);
932 }
933 }
934}
935
David Brazdiled596192015-01-23 10:39:45 +0000936void HEnvironment::CopyFrom(HEnvironment* env) {
937 for (size_t i = 0; i < env->Size(); i++) {
938 HInstruction* instruction = env->GetInstructionAt(i);
939 SetRawEnvAt(i, instruction);
940 if (instruction != nullptr) {
941 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100942 }
David Brazdiled596192015-01-23 10:39:45 +0000943 }
944}
945
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700946void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
947 HBasicBlock* loop_header) {
948 DCHECK(loop_header->IsLoopHeader());
949 for (size_t i = 0; i < env->Size(); i++) {
950 HInstruction* instruction = env->GetInstructionAt(i);
951 SetRawEnvAt(i, instruction);
952 if (instruction == nullptr) {
953 continue;
954 }
955 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
956 // At the end of the loop pre-header, the corresponding value for instruction
957 // is the first input of the phi.
958 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700959 SetRawEnvAt(i, initial);
960 initial->AddEnvUseAt(this, i);
961 } else {
962 instruction->AddEnvUseAt(this, i);
963 }
964 }
965}
966
David Brazdil1abb4192015-02-17 18:33:36 +0000967void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100968 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
969 HInstruction* user = env_use.GetInstruction();
970 auto before_env_use_node = env_use.GetBeforeUseNode();
971 user->env_uses_.erase_after(before_env_use_node);
972 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100973}
974
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000975HInstruction::InstructionKind HInstruction::GetKind() const {
976 return GetKindInternal();
977}
978
Calin Juravle77520bc2015-01-12 18:45:46 +0000979HInstruction* HInstruction::GetNextDisregardingMoves() const {
980 HInstruction* next = GetNext();
981 while (next != nullptr && next->IsParallelMove()) {
982 next = next->GetNext();
983 }
984 return next;
985}
986
987HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
988 HInstruction* previous = GetPrevious();
989 while (previous != nullptr && previous->IsParallelMove()) {
990 previous = previous->GetPrevious();
991 }
992 return previous;
993}
994
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100995void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000996 if (first_instruction_ == nullptr) {
997 DCHECK(last_instruction_ == nullptr);
998 first_instruction_ = last_instruction_ = instruction;
999 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001000 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001001 last_instruction_->next_ = instruction;
1002 instruction->previous_ = last_instruction_;
1003 last_instruction_ = instruction;
1004 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001005}
1006
David Brazdilc3d743f2015-04-22 13:40:50 +01001007void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1008 DCHECK(Contains(cursor));
1009 if (cursor == first_instruction_) {
1010 cursor->previous_ = instruction;
1011 instruction->next_ = cursor;
1012 first_instruction_ = instruction;
1013 } else {
1014 instruction->previous_ = cursor->previous_;
1015 instruction->next_ = cursor;
1016 cursor->previous_ = instruction;
1017 instruction->previous_->next_ = instruction;
1018 }
1019}
1020
1021void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1022 DCHECK(Contains(cursor));
1023 if (cursor == last_instruction_) {
1024 cursor->next_ = instruction;
1025 instruction->previous_ = cursor;
1026 last_instruction_ = instruction;
1027 } else {
1028 instruction->next_ = cursor->next_;
1029 instruction->previous_ = cursor;
1030 cursor->next_ = instruction;
1031 instruction->next_->previous_ = instruction;
1032 }
1033}
1034
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001035void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1036 if (instruction->previous_ != nullptr) {
1037 instruction->previous_->next_ = instruction->next_;
1038 }
1039 if (instruction->next_ != nullptr) {
1040 instruction->next_->previous_ = instruction->previous_;
1041 }
1042 if (instruction == first_instruction_) {
1043 first_instruction_ = instruction->next_;
1044 }
1045 if (instruction == last_instruction_) {
1046 last_instruction_ = instruction->previous_;
1047 }
1048}
1049
Roland Levillain6b469232014-09-25 10:10:38 +01001050bool HInstructionList::Contains(HInstruction* instruction) const {
1051 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1052 if (it.Current() == instruction) {
1053 return true;
1054 }
1055 }
1056 return false;
1057}
1058
Roland Levillainccc07a92014-09-16 14:48:16 +01001059bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1060 const HInstruction* instruction2) const {
1061 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1062 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1063 if (it.Current() == instruction1) {
1064 return true;
1065 }
1066 if (it.Current() == instruction2) {
1067 return false;
1068 }
1069 }
1070 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1071 return true;
1072}
1073
Roland Levillain6c82d402014-10-13 16:10:27 +01001074bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1075 if (other_instruction == this) {
1076 // An instruction does not strictly dominate itself.
1077 return false;
1078 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001079 HBasicBlock* block = GetBlock();
1080 HBasicBlock* other_block = other_instruction->GetBlock();
1081 if (block != other_block) {
1082 return GetBlock()->Dominates(other_instruction->GetBlock());
1083 } else {
1084 // If both instructions are in the same block, ensure this
1085 // instruction comes before `other_instruction`.
1086 if (IsPhi()) {
1087 if (!other_instruction->IsPhi()) {
1088 // Phis appear before non phi-instructions so this instruction
1089 // dominates `other_instruction`.
1090 return true;
1091 } else {
1092 // There is no order among phis.
1093 LOG(FATAL) << "There is no dominance between phis of a same block.";
1094 return false;
1095 }
1096 } else {
1097 // `this` is not a phi.
1098 if (other_instruction->IsPhi()) {
1099 // Phis appear before non phi-instructions so this instruction
1100 // does not dominate `other_instruction`.
1101 return false;
1102 } else {
1103 // Check whether this instruction comes before
1104 // `other_instruction` in the instruction list.
1105 return block->GetInstructions().FoundBefore(this, other_instruction);
1106 }
1107 }
1108 }
1109}
1110
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001111void HInstruction::RemoveEnvironment() {
1112 RemoveEnvironmentUses(this);
1113 environment_ = nullptr;
1114}
1115
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001116void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001117 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001118 // Note: fixup_end remains valid across splice_after().
1119 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1120 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1121 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001123 // Note: env_fixup_end remains valid across splice_after().
1124 auto env_fixup_end =
1125 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1126 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1127 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001128
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001129 DCHECK(uses_.empty());
1130 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001131}
1132
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001133void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1134 const HUseList<HInstruction*>& uses = GetUses();
1135 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1136 HInstruction* user = it->GetUser();
1137 size_t index = it->GetIndex();
1138 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1139 ++it;
1140 if (dominator->StrictlyDominates(user)) {
1141 user->ReplaceInput(replacement, index);
1142 }
1143 }
1144}
1145
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001146void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001147 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001148 if (input_use.GetInstruction() == replacement) {
1149 // Nothing to do.
1150 return;
1151 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001152 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001153 // Note: fixup_end remains valid across splice_after().
1154 auto fixup_end =
1155 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1156 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1157 input_use.GetInstruction()->uses_,
1158 before_use_node);
1159 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1160 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001161}
1162
Nicolas Geoffray39468442014-09-02 15:17:15 +01001163size_t HInstruction::EnvironmentSize() const {
1164 return HasEnvironment() ? environment_->Size() : 0;
1165}
1166
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001167void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001168 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001169 inputs_.push_back(HUserRecord<HInstruction*>(input));
1170 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001171}
1172
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001173void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1174 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1175 input->AddUseAt(this, index);
1176 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1177 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1178 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1179 inputs_[i].GetUseNode()->SetIndex(i);
1180 }
1181}
1182
1183void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001184 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001185 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001186 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1187 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1188 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1189 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001190 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001191}
1192
Igor Murashkind01745e2017-04-05 16:40:31 -07001193void HVariableInputSizeInstruction::RemoveAllInputs() {
1194 RemoveAsUserOfAllInputs();
1195 DCHECK(!HasNonEnvironmentUses());
1196
1197 inputs_.clear();
1198 DCHECK_EQ(0u, InputCount());
1199}
1200
1201void HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
1202 DCHECK(instruction->GetBlock() != nullptr);
1203 // Removing constructor fences only makes sense for instructions with an object return type.
1204 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1205
1206 // Efficient implementation that simultaneously (in one pass):
1207 // * Scans the uses list for all constructor fences.
1208 // * Deletes that constructor fence from the uses list of `instruction`.
1209 // * Deletes `instruction` from the constructor fence's inputs.
1210 // * Deletes the constructor fence if it now has 0 inputs.
1211
1212 const HUseList<HInstruction*>& uses = instruction->GetUses();
1213 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1214 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1215 const HUseListNode<HInstruction*>& use_node = *it;
1216 HInstruction* const use_instruction = use_node.GetUser();
1217
1218 // Advance the iterator immediately once we fetch the use_node.
1219 // Warning: If the input is removed, the current iterator becomes invalid.
1220 ++it;
1221
1222 if (use_instruction->IsConstructorFence()) {
1223 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1224 size_t input_index = use_node.GetIndex();
1225
1226 // Process the candidate instruction for removal
1227 // from the graph.
1228
1229 // Constructor fence instructions are never
1230 // used by other instructions.
1231 //
1232 // If we wanted to make this more generic, it
1233 // could be a runtime if statement.
1234 DCHECK(!ctor_fence->HasUses());
1235
1236 // A constructor fence's return type is "kPrimVoid"
1237 // and therefore it can't have any environment uses.
1238 DCHECK(!ctor_fence->HasEnvironmentUses());
1239
1240 // Remove the inputs first, otherwise removing the instruction
1241 // will try to remove its uses while we are already removing uses
1242 // and this operation will fail.
1243 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1244
1245 // Removing the input will also remove the `use_node`.
1246 // (Do not look at `use_node` after this, it will be a dangling reference).
1247 ctor_fence->RemoveInputAt(input_index);
1248
1249 // Once all inputs are removed, the fence is considered dead and
1250 // is removed.
1251 if (ctor_fence->InputCount() == 0u) {
1252 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
1253 }
1254 }
1255 }
1256
1257 if (kIsDebugBuild) {
1258 // Post-condition checks:
1259 // * None of the uses of `instruction` are a constructor fence.
1260 // * The `instruction` itself did not get removed from a block.
1261 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1262 CHECK(!use_node.GetUser()->IsConstructorFence());
1263 }
1264 CHECK(instruction->GetBlock() != nullptr);
1265 }
1266}
1267
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001268HInstruction* HConstructorFence::GetAssociatedAllocation() {
1269 HInstruction* new_instance_inst = GetPrevious();
1270 // Check if the immediately preceding instruction is a new-instance/new-array.
1271 // Otherwise this fence is for protecting final fields.
1272 if (new_instance_inst != nullptr &&
1273 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1274 // TODO: Need to update this code to handle multiple inputs.
1275 DCHECK_EQ(InputCount(), 1u);
1276 return new_instance_inst;
1277 } else {
1278 return nullptr;
1279 }
1280}
1281
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001282#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001283void H##name::Accept(HGraphVisitor* visitor) { \
1284 visitor->Visit##name(this); \
1285}
1286
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001287FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001288
1289#undef DEFINE_ACCEPT
1290
1291void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001292 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1293 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001294 if (block != nullptr) {
1295 VisitBasicBlock(block);
1296 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001297 }
1298}
1299
Roland Levillain633021e2014-10-01 14:12:25 +01001300void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001301 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1302 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001303 }
1304}
1305
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001306void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001307 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001308 it.Current()->Accept(this);
1309 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001310 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001311 it.Current()->Accept(this);
1312 }
1313}
1314
Mark Mendelle82549b2015-05-06 10:55:34 -04001315HConstant* HTypeConversion::TryStaticEvaluation() const {
1316 HGraph* graph = GetBlock()->GetGraph();
1317 if (GetInput()->IsIntConstant()) {
1318 int32_t value = GetInput()->AsIntConstant()->GetValue();
1319 switch (GetResultType()) {
1320 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001321 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001322 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001323 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001324 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001325 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001326 default:
1327 return nullptr;
1328 }
1329 } else if (GetInput()->IsLongConstant()) {
1330 int64_t value = GetInput()->AsLongConstant()->GetValue();
1331 switch (GetResultType()) {
1332 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001333 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001334 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001335 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001336 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001337 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001338 default:
1339 return nullptr;
1340 }
1341 } else if (GetInput()->IsFloatConstant()) {
1342 float value = GetInput()->AsFloatConstant()->GetValue();
1343 switch (GetResultType()) {
1344 case Primitive::kPrimInt:
1345 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001346 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001347 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001348 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001349 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001350 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1351 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001352 case Primitive::kPrimLong:
1353 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001354 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001355 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001356 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001357 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001358 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1359 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001360 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001361 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001362 default:
1363 return nullptr;
1364 }
1365 } else if (GetInput()->IsDoubleConstant()) {
1366 double value = GetInput()->AsDoubleConstant()->GetValue();
1367 switch (GetResultType()) {
1368 case Primitive::kPrimInt:
1369 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001370 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001371 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001372 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001373 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001374 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1375 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001376 case Primitive::kPrimLong:
1377 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001378 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001379 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001380 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001381 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001382 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1383 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001384 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001385 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001386 default:
1387 return nullptr;
1388 }
1389 }
1390 return nullptr;
1391}
1392
Roland Levillain9240d6a2014-10-20 16:47:04 +01001393HConstant* HUnaryOperation::TryStaticEvaluation() const {
1394 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001395 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001396 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001397 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001398 } else if (kEnableFloatingPointStaticEvaluation) {
1399 if (GetInput()->IsFloatConstant()) {
1400 return Evaluate(GetInput()->AsFloatConstant());
1401 } else if (GetInput()->IsDoubleConstant()) {
1402 return Evaluate(GetInput()->AsDoubleConstant());
1403 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001404 }
1405 return nullptr;
1406}
1407
1408HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001409 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1410 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001411 } else if (GetLeft()->IsLongConstant()) {
1412 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001413 // The binop(long, int) case is only valid for shifts and rotations.
1414 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001415 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1416 } else if (GetRight()->IsLongConstant()) {
1417 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001418 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001419 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001420 // The binop(null, null) case is only valid for equal and not-equal conditions.
1421 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001422 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001423 } else if (kEnableFloatingPointStaticEvaluation) {
1424 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1425 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1426 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1427 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1428 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001429 }
1430 return nullptr;
1431}
Dave Allison20dfc792014-06-16 20:44:29 -07001432
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001433HConstant* HBinaryOperation::GetConstantRight() const {
1434 if (GetRight()->IsConstant()) {
1435 return GetRight()->AsConstant();
1436 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1437 return GetLeft()->AsConstant();
1438 } else {
1439 return nullptr;
1440 }
1441}
1442
1443// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001444// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001445HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1446 HInstruction* most_constant_right = GetConstantRight();
1447 if (most_constant_right == nullptr) {
1448 return nullptr;
1449 } else if (most_constant_right == GetLeft()) {
1450 return GetRight();
1451 } else {
1452 return GetLeft();
1453 }
1454}
1455
Roland Levillain31dd3d62016-02-16 12:21:02 +00001456std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1457 switch (rhs) {
1458 case ComparisonBias::kNoBias:
1459 return os << "no_bias";
1460 case ComparisonBias::kGtBias:
1461 return os << "gt_bias";
1462 case ComparisonBias::kLtBias:
1463 return os << "lt_bias";
1464 default:
1465 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1466 UNREACHABLE();
1467 }
1468}
1469
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001470bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1471 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001472}
1473
Vladimir Marko372f10e2016-05-17 16:30:10 +01001474bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001475 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001476 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001477 if (!InstructionDataEquals(other)) return false;
1478 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001479 HConstInputsRef inputs = GetInputs();
1480 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001481 if (inputs.size() != other_inputs.size()) return false;
1482 for (size_t i = 0; i != inputs.size(); ++i) {
1483 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001484 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001485
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001486 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001487 return true;
1488}
1489
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001490std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1491#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1492 switch (rhs) {
1493 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1494 default:
1495 os << "Unknown instruction kind " << static_cast<int>(rhs);
1496 break;
1497 }
1498#undef DECLARE_CASE
1499 return os;
1500}
1501
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001502void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1503 if (do_checks) {
1504 DCHECK(!IsPhi());
1505 DCHECK(!IsControlFlow());
1506 DCHECK(CanBeMoved() ||
1507 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1508 IsShouldDeoptimizeFlag());
1509 DCHECK(!cursor->IsPhi());
1510 }
David Brazdild6c205e2016-06-07 14:20:52 +01001511
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001512 next_->previous_ = previous_;
1513 if (previous_ != nullptr) {
1514 previous_->next_ = next_;
1515 }
1516 if (block_->instructions_.first_instruction_ == this) {
1517 block_->instructions_.first_instruction_ = next_;
1518 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001519 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001520
1521 previous_ = cursor->previous_;
1522 if (previous_ != nullptr) {
1523 previous_->next_ = this;
1524 }
1525 next_ = cursor;
1526 cursor->previous_ = this;
1527 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001528
1529 if (block_->instructions_.first_instruction_ == cursor) {
1530 block_->instructions_.first_instruction_ = this;
1531 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001532}
1533
Vladimir Markofb337ea2015-11-25 15:25:10 +00001534void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1535 DCHECK(!CanThrow());
1536 DCHECK(!HasSideEffects());
1537 DCHECK(!HasEnvironmentUses());
1538 DCHECK(HasNonEnvironmentUses());
1539 DCHECK(!IsPhi()); // Makes no sense for Phi.
1540 DCHECK_EQ(InputCount(), 0u);
1541
1542 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001543 auto uses_it = GetUses().begin();
1544 auto uses_end = GetUses().end();
1545 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1546 ++uses_it;
1547 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1548 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001549 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001550 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001551 // This instruction has uses in two or more blocks. Find the common dominator.
1552 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001553 for (; uses_it != uses_end; ++uses_it) {
1554 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001555 }
1556 target_block = finder.Get();
1557 DCHECK(target_block != nullptr);
1558 }
1559 // Move to the first dominator not in a loop.
1560 while (target_block->IsInLoop()) {
1561 target_block = target_block->GetDominator();
1562 DCHECK(target_block != nullptr);
1563 }
1564
1565 // Find insertion position.
1566 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001567 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1568 if (use.GetUser()->GetBlock() == target_block &&
1569 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1570 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001571 }
1572 }
1573 if (insert_pos == nullptr) {
1574 // No user in `target_block`, insert before the control flow instruction.
1575 insert_pos = target_block->GetLastInstruction();
1576 DCHECK(insert_pos->IsControlFlow());
1577 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1578 if (insert_pos->IsIf()) {
1579 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1580 if (if_input == insert_pos->GetPrevious()) {
1581 insert_pos = if_input;
1582 }
1583 }
1584 }
1585 MoveBefore(insert_pos);
1586}
1587
David Brazdilfc6a86a2015-06-26 10:33:45 +00001588HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001589 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001590 DCHECK_EQ(cursor->GetBlock(), this);
1591
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001592 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1593 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001594 new_block->instructions_.first_instruction_ = cursor;
1595 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1596 instructions_.last_instruction_ = cursor->previous_;
1597 if (cursor->previous_ == nullptr) {
1598 instructions_.first_instruction_ = nullptr;
1599 } else {
1600 cursor->previous_->next_ = nullptr;
1601 cursor->previous_ = nullptr;
1602 }
1603
1604 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001605 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001606
Vladimir Marko60584552015-09-03 13:35:12 +00001607 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001608 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001609 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001610 new_block->successors_.swap(successors_);
1611 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001612 AddSuccessor(new_block);
1613
David Brazdil56e1acc2015-06-30 15:41:36 +01001614 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001615 return new_block;
1616}
1617
David Brazdild7558da2015-09-22 13:04:14 +01001618HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001619 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001620 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1621
1622 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1623
1624 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001625 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1626 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001627 new_block->predecessors_.swap(predecessors_);
1628 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001629 AddPredecessor(new_block);
1630
1631 GetGraph()->AddBlock(new_block);
1632 return new_block;
1633}
1634
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001635HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1636 DCHECK_EQ(cursor->GetBlock(), this);
1637
1638 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1639 cursor->GetDexPc());
1640 new_block->instructions_.first_instruction_ = cursor;
1641 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1642 instructions_.last_instruction_ = cursor->previous_;
1643 if (cursor->previous_ == nullptr) {
1644 instructions_.first_instruction_ = nullptr;
1645 } else {
1646 cursor->previous_->next_ = nullptr;
1647 cursor->previous_ = nullptr;
1648 }
1649
1650 new_block->instructions_.SetBlockOfInstructions(new_block);
1651
1652 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001653 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1654 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001655 new_block->successors_.swap(successors_);
1656 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001657
1658 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1659 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001660 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001661 new_block->dominated_blocks_.swap(dominated_blocks_);
1662 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001663 return new_block;
1664}
1665
1666HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001667 DCHECK(!cursor->IsControlFlow());
1668 DCHECK_NE(instructions_.last_instruction_, cursor);
1669 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001670
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001671 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1672 new_block->instructions_.first_instruction_ = cursor->GetNext();
1673 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1674 cursor->next_->previous_ = nullptr;
1675 cursor->next_ = nullptr;
1676 instructions_.last_instruction_ = cursor;
1677
1678 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001679 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001680 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001681 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001682 new_block->successors_.swap(successors_);
1683 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001684
Vladimir Marko60584552015-09-03 13:35:12 +00001685 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001686 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001687 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001688 new_block->dominated_blocks_.swap(dominated_blocks_);
1689 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001690 return new_block;
1691}
1692
David Brazdilec16f792015-08-19 15:04:01 +01001693const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001694 if (EndsWithTryBoundary()) {
1695 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1696 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001697 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001698 return try_boundary;
1699 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001700 DCHECK(IsTryBlock());
1701 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001702 return nullptr;
1703 }
David Brazdilec16f792015-08-19 15:04:01 +01001704 } else if (IsTryBlock()) {
1705 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001706 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001707 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001708 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001709}
1710
David Brazdild7558da2015-09-22 13:04:14 +01001711bool HBasicBlock::HasThrowingInstructions() const {
1712 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1713 if (it.Current()->CanThrow()) {
1714 return true;
1715 }
1716 }
1717 return false;
1718}
1719
David Brazdilfc6a86a2015-06-26 10:33:45 +00001720static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1721 return block.GetPhis().IsEmpty()
1722 && !block.GetInstructions().IsEmpty()
1723 && block.GetFirstInstruction() == block.GetLastInstruction();
1724}
1725
David Brazdil46e2a392015-03-16 17:31:52 +00001726bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001727 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1728}
1729
1730bool HBasicBlock::IsSingleTryBoundary() const {
1731 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001732}
1733
David Brazdil8d5b8b22015-03-24 10:51:52 +00001734bool HBasicBlock::EndsWithControlFlowInstruction() const {
1735 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1736}
1737
David Brazdilb2bd1c52015-03-25 11:17:37 +00001738bool HBasicBlock::EndsWithIf() const {
1739 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1740}
1741
David Brazdilffee3d32015-07-06 11:48:53 +01001742bool HBasicBlock::EndsWithTryBoundary() const {
1743 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1744}
1745
David Brazdilb2bd1c52015-03-25 11:17:37 +00001746bool HBasicBlock::HasSinglePhi() const {
1747 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1748}
1749
David Brazdild26a4112015-11-10 11:07:31 +00001750ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1751 if (EndsWithTryBoundary()) {
1752 // The normal-flow successor of HTryBoundary is always stored at index zero.
1753 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1754 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1755 } else {
1756 // All successors of blocks not ending with TryBoundary are normal.
1757 return ArrayRef<HBasicBlock* const>(successors_);
1758 }
1759}
1760
1761ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1762 if (EndsWithTryBoundary()) {
1763 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1764 } else {
1765 // Blocks not ending with TryBoundary do not have exceptional successors.
1766 return ArrayRef<HBasicBlock* const>();
1767 }
1768}
1769
David Brazdilffee3d32015-07-06 11:48:53 +01001770bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001771 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1772 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1773
1774 size_t length = handlers1.size();
1775 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001776 return false;
1777 }
1778
David Brazdilb618ade2015-07-29 10:31:29 +01001779 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001780 for (size_t i = 0; i < length; ++i) {
1781 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001782 return false;
1783 }
1784 }
1785 return true;
1786}
1787
David Brazdil2d7352b2015-04-20 14:52:42 +01001788size_t HInstructionList::CountSize() const {
1789 size_t size = 0;
1790 HInstruction* current = first_instruction_;
1791 for (; current != nullptr; current = current->GetNext()) {
1792 size++;
1793 }
1794 return size;
1795}
1796
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001797void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1798 for (HInstruction* current = first_instruction_;
1799 current != nullptr;
1800 current = current->GetNext()) {
1801 current->SetBlock(block);
1802 }
1803}
1804
1805void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1806 DCHECK(Contains(cursor));
1807 if (!instruction_list.IsEmpty()) {
1808 if (cursor == last_instruction_) {
1809 last_instruction_ = instruction_list.last_instruction_;
1810 } else {
1811 cursor->next_->previous_ = instruction_list.last_instruction_;
1812 }
1813 instruction_list.last_instruction_->next_ = cursor->next_;
1814 cursor->next_ = instruction_list.first_instruction_;
1815 instruction_list.first_instruction_->previous_ = cursor;
1816 }
1817}
1818
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001819void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1820 DCHECK(Contains(cursor));
1821 if (!instruction_list.IsEmpty()) {
1822 if (cursor == first_instruction_) {
1823 first_instruction_ = instruction_list.first_instruction_;
1824 } else {
1825 cursor->previous_->next_ = instruction_list.first_instruction_;
1826 }
1827 instruction_list.last_instruction_->next_ = cursor;
1828 instruction_list.first_instruction_->previous_ = cursor->previous_;
1829 cursor->previous_ = instruction_list.last_instruction_;
1830 }
1831}
1832
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001833void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001834 if (IsEmpty()) {
1835 first_instruction_ = instruction_list.first_instruction_;
1836 last_instruction_ = instruction_list.last_instruction_;
1837 } else {
1838 AddAfter(last_instruction_, instruction_list);
1839 }
1840}
1841
David Brazdil04ff4e82015-12-10 13:54:52 +00001842// Should be called on instructions in a dead block in post order. This method
1843// assumes `insn` has been removed from all users with the exception of catch
1844// phis because of missing exceptional edges in the graph. It removes the
1845// instruction from catch phi uses, together with inputs of other catch phis in
1846// the catch block at the same index, as these must be dead too.
1847static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1848 DCHECK(!insn->HasEnvironmentUses());
1849 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001850 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1851 size_t use_index = use.GetIndex();
1852 HBasicBlock* user_block = use.GetUser()->GetBlock();
1853 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001854 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1855 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1856 }
1857 }
1858}
1859
David Brazdil2d7352b2015-04-20 14:52:42 +01001860void HBasicBlock::DisconnectAndDelete() {
1861 // Dominators must be removed after all the blocks they dominate. This way
1862 // a loop header is removed last, a requirement for correct loop information
1863 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001864 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001865
David Brazdil9eeebf62016-03-24 11:18:15 +00001866 // The following steps gradually remove the block from all its dependants in
1867 // post order (b/27683071).
1868
1869 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1870 // We need to do this before step (4) which destroys the predecessor list.
1871 HBasicBlock* loop_update_start = this;
1872 if (IsLoopHeader()) {
1873 HLoopInformation* loop_info = GetLoopInformation();
1874 // All other blocks in this loop should have been removed because the header
1875 // was their dominator.
1876 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1877 DCHECK(!loop_info->IsIrreducible());
1878 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1879 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1880 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001881 }
1882
David Brazdil9eeebf62016-03-24 11:18:15 +00001883 // (2) Disconnect the block from its successors and update their phis.
1884 for (HBasicBlock* successor : successors_) {
1885 // Delete this block from the list of predecessors.
1886 size_t this_index = successor->GetPredecessorIndexOf(this);
1887 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1888
1889 // Check that `successor` has other predecessors, otherwise `this` is the
1890 // dominator of `successor` which violates the order DCHECKed at the top.
1891 DCHECK(!successor->predecessors_.empty());
1892
1893 // Remove this block's entries in the successor's phis. Skip exceptional
1894 // successors because catch phi inputs do not correspond to predecessor
1895 // blocks but throwing instructions. The inputs of the catch phis will be
1896 // updated in step (3).
1897 if (!successor->IsCatchBlock()) {
1898 if (successor->predecessors_.size() == 1u) {
1899 // The successor has just one predecessor left. Replace phis with the only
1900 // remaining input.
1901 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1902 HPhi* phi = phi_it.Current()->AsPhi();
1903 phi->ReplaceWith(phi->InputAt(1 - this_index));
1904 successor->RemovePhi(phi);
1905 }
1906 } else {
1907 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1908 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1909 }
1910 }
1911 }
1912 }
1913 successors_.clear();
1914
1915 // (3) Remove instructions and phis. Instructions should have no remaining uses
1916 // except in catch phis. If an instruction is used by a catch phi at `index`,
1917 // remove `index`-th input of all phis in the catch block since they are
1918 // guaranteed dead. Note that we may miss dead inputs this way but the
1919 // graph will always remain consistent.
1920 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1921 HInstruction* insn = it.Current();
1922 RemoveUsesOfDeadInstruction(insn);
1923 RemoveInstruction(insn);
1924 }
1925 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1926 HPhi* insn = it.Current()->AsPhi();
1927 RemoveUsesOfDeadInstruction(insn);
1928 RemovePhi(insn);
1929 }
1930
1931 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001932 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001933 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001934 // We should not see any back edges as they would have been removed by step (3).
1935 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1936
David Brazdil2d7352b2015-04-20 14:52:42 +01001937 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001938 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1939 // This block is the only normal-flow successor of the TryBoundary which
1940 // makes `predecessor` dead. Since DCE removes blocks in post order,
1941 // exception handlers of this TryBoundary were already visited and any
1942 // remaining handlers therefore must be live. We remove `predecessor` from
1943 // their list of predecessors.
1944 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1945 while (predecessor->GetSuccessors().size() > 1) {
1946 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1947 DCHECK(handler->IsCatchBlock());
1948 predecessor->RemoveSuccessor(handler);
1949 handler->RemovePredecessor(predecessor);
1950 }
1951 }
1952
David Brazdil2d7352b2015-04-20 14:52:42 +01001953 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001954 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1955 if (num_pred_successors == 1u) {
1956 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001957 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1958 // successor. Replace those with a HGoto.
1959 DCHECK(last_instruction->IsIf() ||
1960 last_instruction->IsPackedSwitch() ||
1961 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001962 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001963 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001964 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001965 // The predecessor has no remaining successors and therefore must be dead.
1966 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001967 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001968 predecessor->RemoveInstruction(last_instruction);
1969 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001970 // There are multiple successors left. The removed block might be a successor
1971 // of a PackedSwitch which will be completely removed (perhaps replaced with
1972 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1973 // case, leave `last_instruction` as is for now.
1974 DCHECK(last_instruction->IsPackedSwitch() ||
1975 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001976 }
David Brazdil46e2a392015-03-16 17:31:52 +00001977 }
Vladimir Marko60584552015-09-03 13:35:12 +00001978 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001979
David Brazdil9eeebf62016-03-24 11:18:15 +00001980 // (5) Remove the block from all loops it is included in. Skip the inner-most
1981 // loop if this is the loop header (see definition of `loop_update_start`)
1982 // because the loop header's predecessor list has been destroyed in step (4).
1983 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1984 HLoopInformation* loop_info = it.Current();
1985 loop_info->Remove(this);
1986 if (loop_info->IsBackEdge(*this)) {
1987 // If this was the last back edge of the loop, we deliberately leave the
1988 // loop in an inconsistent state and will fail GraphChecker unless the
1989 // entire loop is removed during the pass.
1990 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001991 }
1992 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001993
David Brazdil9eeebf62016-03-24 11:18:15 +00001994 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001995 dominator_->RemoveDominatedBlock(this);
1996 SetDominator(nullptr);
1997
David Brazdil9eeebf62016-03-24 11:18:15 +00001998 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001999 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002000 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002001}
2002
Aart Bik6b69e0a2017-01-11 10:20:43 -08002003void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2004 DCHECK(EndsWithControlFlowInstruction());
2005 RemoveInstruction(GetLastInstruction());
2006 instructions_.Add(other->GetInstructions());
2007 other->instructions_.SetBlockOfInstructions(this);
2008 other->instructions_.Clear();
2009}
2010
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002011void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002012 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002013 DCHECK(ContainsElement(dominated_blocks_, other));
2014 DCHECK_EQ(GetSingleSuccessor(), other);
2015 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002016 DCHECK(other->GetPhis().IsEmpty());
2017
David Brazdil2d7352b2015-04-20 14:52:42 +01002018 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002019 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002020
David Brazdil2d7352b2015-04-20 14:52:42 +01002021 // Remove `other` from the loops it is included in.
2022 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2023 HLoopInformation* loop_info = it.Current();
2024 loop_info->Remove(other);
2025 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002026 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002027 }
2028 }
2029
2030 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002031 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002032 for (HBasicBlock* successor : other->GetSuccessors()) {
2033 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002034 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002035 successors_.swap(other->successors_);
2036 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002037
David Brazdil2d7352b2015-04-20 14:52:42 +01002038 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002039 RemoveDominatedBlock(other);
2040 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002041 dominated->SetDominator(this);
2042 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002043 dominated_blocks_.insert(
2044 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002045 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002046 other->dominator_ = nullptr;
2047
2048 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002049 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002050
2051 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002052 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002053 other->SetGraph(nullptr);
2054}
2055
2056void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2057 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002058 DCHECK(GetDominatedBlocks().empty());
2059 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002060 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002061 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002062 DCHECK(other->GetPhis().IsEmpty());
2063 DCHECK(!other->IsInLoop());
2064
2065 // Move instructions from `other` to `this`.
2066 instructions_.Add(other->GetInstructions());
2067 other->instructions_.SetBlockOfInstructions(this);
2068
2069 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002070 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002071 for (HBasicBlock* successor : other->GetSuccessors()) {
2072 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002073 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002074 successors_.swap(other->successors_);
2075 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002076
2077 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002078 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002079 dominated->SetDominator(this);
2080 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002081 dominated_blocks_.insert(
2082 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002083 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002084 other->dominator_ = nullptr;
2085 other->graph_ = nullptr;
2086}
2087
2088void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002089 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002090 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002091 predecessor->ReplaceSuccessor(this, other);
2092 }
Vladimir Marko60584552015-09-03 13:35:12 +00002093 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002094 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002095 successor->ReplacePredecessor(this, other);
2096 }
Vladimir Marko60584552015-09-03 13:35:12 +00002097 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2098 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002099 }
2100 GetDominator()->ReplaceDominatedBlock(this, other);
2101 other->SetDominator(GetDominator());
2102 dominator_ = nullptr;
2103 graph_ = nullptr;
2104}
2105
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002106void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002107 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002108 DCHECK(block->GetSuccessors().empty());
2109 DCHECK(block->GetPredecessors().empty());
2110 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002111 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002112 DCHECK(block->GetInstructions().IsEmpty());
2113 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002114
David Brazdilc7af85d2015-05-26 12:05:55 +01002115 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002116 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002117 }
2118
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002119 RemoveElement(reverse_post_order_, block);
2120 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002121 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002122}
2123
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002124void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2125 HBasicBlock* reference,
2126 bool replace_if_back_edge) {
2127 if (block->IsLoopHeader()) {
2128 // Clear the information of which blocks are contained in that loop. Since the
2129 // information is stored as a bit vector based on block ids, we have to update
2130 // it, as those block ids were specific to the callee graph and we are now adding
2131 // these blocks to the caller graph.
2132 block->GetLoopInformation()->ClearAllBlocks();
2133 }
2134
2135 // If not already in a loop, update the loop information.
2136 if (!block->IsInLoop()) {
2137 block->SetLoopInformation(reference->GetLoopInformation());
2138 }
2139
2140 // If the block is in a loop, update all its outward loops.
2141 HLoopInformation* loop_info = block->GetLoopInformation();
2142 if (loop_info != nullptr) {
2143 for (HLoopInformationOutwardIterator loop_it(*block);
2144 !loop_it.Done();
2145 loop_it.Advance()) {
2146 loop_it.Current()->Add(block);
2147 }
2148 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2149 loop_info->ReplaceBackEdge(reference, block);
2150 }
2151 }
2152
2153 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2154 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2155 ? reference->GetTryCatchInformation()
2156 : nullptr;
2157 block->SetTryCatchInformation(try_catch_info);
2158}
2159
Calin Juravle2e768302015-07-28 14:41:11 +00002160HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002161 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002162 // Update the environments in this graph to have the invoke's environment
2163 // as parent.
2164 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002165 // Skip the entry block, we do not need to update the entry's suspend check.
2166 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002167 for (HInstructionIterator instr_it(block->GetInstructions());
2168 !instr_it.Done();
2169 instr_it.Advance()) {
2170 HInstruction* current = instr_it.Current();
2171 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002172 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002173 current->GetEnvironment()->SetAndCopyParentChain(
2174 outer_graph->GetArena(), invoke->GetEnvironment());
2175 }
2176 }
2177 }
2178 }
2179 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002180
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002181 if (HasBoundsChecks()) {
2182 outer_graph->SetHasBoundsChecks(true);
2183 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002184 if (HasLoops()) {
2185 outer_graph->SetHasLoops(true);
2186 }
2187 if (HasIrreducibleLoops()) {
2188 outer_graph->SetHasIrreducibleLoops(true);
2189 }
2190 if (HasTryCatch()) {
2191 outer_graph->SetHasTryCatch(true);
2192 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002193 if (HasSIMD()) {
2194 outer_graph->SetHasSIMD(true);
2195 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002196
Calin Juravle2e768302015-07-28 14:41:11 +00002197 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002198 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002199 // Inliner already made sure we don't inline methods that always throw.
2200 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002201 // Simple case of an entry block, a body block, and an exit block.
2202 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002203 HBasicBlock* body = GetBlocks()[1];
2204 DCHECK(GetBlocks()[0]->IsEntryBlock());
2205 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002206 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002207 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002208 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002209
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002210 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2211 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002212 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002213
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002214 // Replace the invoke with the return value of the inlined graph.
2215 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002216 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002217 } else {
2218 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002219 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002220
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002221 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002222 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002223 // Need to inline multiple blocks. We split `invoke`'s block
2224 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002225 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002226 // with the second half.
2227 ArenaAllocator* allocator = outer_graph->GetArena();
2228 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002229 // Note that we split before the invoke only to simplify polymorphic inlining.
2230 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002231
Vladimir Markoec7802a2015-10-01 20:57:57 +01002232 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002233 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002234 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002235 exit_block_->ReplaceWith(to);
2236
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002237 // Update the meta information surrounding blocks:
2238 // (1) the graph they are now in,
2239 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002240 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002241 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002242 // Note that we do not need to update catch phi inputs because they
2243 // correspond to the register file of the outer method which the inlinee
2244 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002245
2246 // We don't add the entry block, the exit block, and the first block, which
2247 // has been merged with `at`.
2248 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2249
2250 // We add the `to` block.
2251 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002252 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002253 + kNumberOfNewBlocksInCaller;
2254
2255 // Find the location of `at` in the outer graph's reverse post order. The new
2256 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002257 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002258 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2259
David Brazdil95177982015-10-30 12:56:58 -05002260 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2261 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002262 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002263 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002264 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002265 DCHECK(current->GetGraph() == this);
2266 current->SetGraph(outer_graph);
2267 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002268 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002269 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002270 }
2271 }
2272
David Brazdil95177982015-10-30 12:56:58 -05002273 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002274 to->SetGraph(outer_graph);
2275 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002276 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002277 // Only `to` can become a back edge, as the inlined blocks
2278 // are predecessors of `to`.
2279 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002280
David Brazdil3f523062016-02-29 16:53:33 +00002281 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002282 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2283 // to now get the outer graph exit block as successor. Note that the inliner
2284 // currently doesn't support inlining methods with try/catch.
2285 HPhi* return_value_phi = nullptr;
2286 bool rerun_dominance = false;
2287 bool rerun_loop_analysis = false;
2288 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2289 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002290 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002291 if (last->IsThrow()) {
2292 DCHECK(!at->IsTryBlock());
2293 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2294 --pred;
2295 // We need to re-run dominance information, as the exit block now has
2296 // a new dominator.
2297 rerun_dominance = true;
2298 if (predecessor->GetLoopInformation() != nullptr) {
2299 // The exit block and blocks post dominated by the exit block do not belong
2300 // to any loop. Because we do not compute the post dominators, we need to re-run
2301 // loop analysis to get the loop information correct.
2302 rerun_loop_analysis = true;
2303 }
2304 } else {
2305 if (last->IsReturnVoid()) {
2306 DCHECK(return_value == nullptr);
2307 DCHECK(return_value_phi == nullptr);
2308 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002309 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002310 if (return_value_phi != nullptr) {
2311 return_value_phi->AddInput(last->InputAt(0));
2312 } else if (return_value == nullptr) {
2313 return_value = last->InputAt(0);
2314 } else {
2315 // There will be multiple returns.
2316 return_value_phi = new (allocator) HPhi(
2317 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2318 to->AddPhi(return_value_phi);
2319 return_value_phi->AddInput(return_value);
2320 return_value_phi->AddInput(last->InputAt(0));
2321 return_value = return_value_phi;
2322 }
David Brazdil3f523062016-02-29 16:53:33 +00002323 }
2324 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2325 predecessor->RemoveInstruction(last);
2326 }
2327 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002328 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002329 DCHECK(!outer_graph->HasIrreducibleLoops())
2330 << "Recomputing loop information in graphs with irreducible loops "
2331 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002332 outer_graph->ClearLoopInformation();
2333 outer_graph->ClearDominanceInformation();
2334 outer_graph->BuildDominatorTree();
2335 } else if (rerun_dominance) {
2336 outer_graph->ClearDominanceInformation();
2337 outer_graph->ComputeDominanceInformation();
2338 }
David Brazdil3f523062016-02-29 16:53:33 +00002339 }
David Brazdil05144f42015-04-16 15:18:00 +01002340
2341 // Walk over the entry block and:
2342 // - Move constants from the entry block to the outer_graph's entry block,
2343 // - Replace HParameterValue instructions with their real value.
2344 // - Remove suspend checks, that hold an environment.
2345 // We must do this after the other blocks have been inlined, otherwise ids of
2346 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002347 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002348 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2349 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002350 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002351 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002352 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002353 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002354 replacement = outer_graph->GetIntConstant(
2355 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002356 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002357 replacement = outer_graph->GetLongConstant(
2358 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002359 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002360 replacement = outer_graph->GetFloatConstant(
2361 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002362 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002363 replacement = outer_graph->GetDoubleConstant(
2364 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002365 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002366 if (kIsDebugBuild
2367 && invoke->IsInvokeStaticOrDirect()
2368 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2369 // Ensure we do not use the last input of `invoke`, as it
2370 // contains a clinit check which is not an actual argument.
2371 size_t last_input_index = invoke->InputCount() - 1;
2372 DCHECK(parameter_index != last_input_index);
2373 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002374 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002375 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002376 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002377 } else {
2378 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2379 entry_block_->RemoveInstruction(current);
2380 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002381 if (replacement != nullptr) {
2382 current->ReplaceWith(replacement);
2383 // If the current is the return value then we need to update the latter.
2384 if (current == return_value) {
2385 DCHECK_EQ(entry_block_, return_value->GetBlock());
2386 return_value = replacement;
2387 }
2388 }
2389 }
2390
Calin Juravle2e768302015-07-28 14:41:11 +00002391 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002392}
2393
Mingyao Yang3584bce2015-05-19 16:01:59 -07002394/*
2395 * Loop will be transformed to:
2396 * old_pre_header
2397 * |
2398 * if_block
2399 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002400 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002401 * \ /
2402 * new_pre_header
2403 * |
2404 * header
2405 */
2406void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2407 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002408 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002409
Aart Bik3fc7f352015-11-20 22:03:03 -08002410 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002411 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002412 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2413 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002414 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2415 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002416 AddBlock(true_block);
2417 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002418 AddBlock(new_pre_header);
2419
Aart Bik3fc7f352015-11-20 22:03:03 -08002420 header->ReplacePredecessor(old_pre_header, new_pre_header);
2421 old_pre_header->successors_.clear();
2422 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002423
Aart Bik3fc7f352015-11-20 22:03:03 -08002424 old_pre_header->AddSuccessor(if_block);
2425 if_block->AddSuccessor(true_block); // True successor
2426 if_block->AddSuccessor(false_block); // False successor
2427 true_block->AddSuccessor(new_pre_header);
2428 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002429
Aart Bik3fc7f352015-11-20 22:03:03 -08002430 old_pre_header->dominated_blocks_.push_back(if_block);
2431 if_block->SetDominator(old_pre_header);
2432 if_block->dominated_blocks_.push_back(true_block);
2433 true_block->SetDominator(if_block);
2434 if_block->dominated_blocks_.push_back(false_block);
2435 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002436 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002437 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002438 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002439 header->SetDominator(new_pre_header);
2440
Aart Bik3fc7f352015-11-20 22:03:03 -08002441 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002442 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002443 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002444 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002445 reverse_post_order_[index_of_header++] = true_block;
2446 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002447 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002448
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002449 // The pre_header can never be a back edge of a loop.
2450 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2451 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2452 UpdateLoopAndTryInformationOfNewBlock(
2453 if_block, old_pre_header, /* replace_if_back_edge */ false);
2454 UpdateLoopAndTryInformationOfNewBlock(
2455 true_block, old_pre_header, /* replace_if_back_edge */ false);
2456 UpdateLoopAndTryInformationOfNewBlock(
2457 false_block, old_pre_header, /* replace_if_back_edge */ false);
2458 UpdateLoopAndTryInformationOfNewBlock(
2459 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002460}
2461
Aart Bikf8f5a162017-02-06 15:35:29 -08002462HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2463 HBasicBlock* body,
2464 HBasicBlock* exit) {
2465 DCHECK(header->IsLoopHeader());
2466 HLoopInformation* loop = header->GetLoopInformation();
2467
2468 // Add new loop blocks.
2469 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2470 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2471 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2472 AddBlock(new_pre_header);
2473 AddBlock(new_header);
2474 AddBlock(new_body);
2475
2476 // Set up control flow.
2477 header->ReplaceSuccessor(exit, new_pre_header);
2478 new_pre_header->AddSuccessor(new_header);
2479 new_header->AddSuccessor(exit);
2480 new_header->AddSuccessor(new_body);
2481 new_body->AddSuccessor(new_header);
2482
2483 // Set up dominators.
2484 header->ReplaceDominatedBlock(exit, new_pre_header);
2485 new_pre_header->SetDominator(header);
2486 new_pre_header->dominated_blocks_.push_back(new_header);
2487 new_header->SetDominator(new_pre_header);
2488 new_header->dominated_blocks_.push_back(new_body);
2489 new_body->SetDominator(new_header);
2490 new_header->dominated_blocks_.push_back(exit);
2491 exit->SetDominator(new_header);
2492
2493 // Fix reverse post order.
2494 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2495 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2496 reverse_post_order_[++index_of_header] = new_pre_header;
2497 reverse_post_order_[++index_of_header] = new_header;
2498 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2499 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2500 reverse_post_order_[index_of_body] = new_body;
2501
Aart Bikb07d1bc2017-04-05 10:03:15 -07002502 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002503 new_pre_header->AddInstruction(new (arena_) HGoto());
2504 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2505 new_header->AddInstruction(suspend_check);
2506 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002507 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2508 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002509
2510 // Update loop information.
2511 new_header->AddBackEdge(new_body);
2512 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2513 new_header->GetLoopInformation()->Populate();
2514 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2515 HLoopInformationOutwardIterator it(*new_header);
2516 for (it.Advance(); !it.Done(); it.Advance()) {
2517 it.Current()->Add(new_pre_header);
2518 it.Current()->Add(new_header);
2519 it.Current()->Add(new_body);
2520 }
2521 return new_pre_header;
2522}
2523
David Brazdilf5552582015-12-27 13:36:12 +00002524static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002525 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002526 if (rti.IsValid()) {
2527 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2528 << " upper_bound_rti: " << upper_bound_rti
2529 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002530 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2531 << " upper_bound_rti: " << upper_bound_rti
2532 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002533 }
2534}
2535
Calin Juravle2e768302015-07-28 14:41:11 +00002536void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2537 if (kIsDebugBuild) {
2538 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2539 ScopedObjectAccess soa(Thread::Current());
2540 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2541 if (IsBoundType()) {
2542 // Having the test here spares us from making the method virtual just for
2543 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002544 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002545 }
2546 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002547 reference_type_handle_ = rti.GetTypeHandle();
2548 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002549}
2550
David Brazdilf5552582015-12-27 13:36:12 +00002551void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2552 if (kIsDebugBuild) {
2553 ScopedObjectAccess soa(Thread::Current());
2554 DCHECK(upper_bound.IsValid());
2555 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2556 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2557 }
2558 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002559 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002560}
2561
Vladimir Markoa1de9182016-02-25 11:37:38 +00002562ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002563 if (kIsDebugBuild) {
2564 ScopedObjectAccess soa(Thread::Current());
2565 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002566 if (!is_exact) {
2567 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2568 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2569 }
Calin Juravle2e768302015-07-28 14:41:11 +00002570 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002571 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002572}
2573
Calin Juravleacf735c2015-02-12 15:25:22 +00002574std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2575 ScopedObjectAccess soa(Thread::Current());
2576 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002577 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002578 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002579 << " is_exact=" << rhs.IsExact()
2580 << " ]";
2581 return os;
2582}
2583
Mark Mendellc4701932015-04-10 13:18:51 -04002584bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2585 // For now, assume that instructions in different blocks may use the
2586 // environment.
2587 // TODO: Use the control flow to decide if this is true.
2588 if (GetBlock() != other->GetBlock()) {
2589 return true;
2590 }
2591
2592 // We know that we are in the same block. Walk from 'this' to 'other',
2593 // checking to see if there is any instruction with an environment.
2594 HInstruction* current = this;
2595 for (; current != other && current != nullptr; current = current->GetNext()) {
2596 // This is a conservative check, as the instruction result may not be in
2597 // the referenced environment.
2598 if (current->HasEnvironment()) {
2599 return true;
2600 }
2601 }
2602
2603 // We should have been called with 'this' before 'other' in the block.
2604 // Just confirm this.
2605 DCHECK(current != nullptr);
2606 return false;
2607}
2608
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002609void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002610 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2611 IntrinsicSideEffects side_effects,
2612 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002613 intrinsic_ = intrinsic;
2614 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002615
Aart Bik5d75afe2015-12-14 11:57:01 -08002616 // Adjust method's side effects from intrinsic table.
2617 switch (side_effects) {
2618 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2619 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2620 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2621 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2622 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002623
2624 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2625 opt.SetDoesNotNeedDexCache();
2626 opt.SetDoesNotNeedEnvironment();
2627 } else {
2628 // If we need an environment, that means there will be a call, which can trigger GC.
2629 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2630 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002631 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002632 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002633}
2634
David Brazdil6de19382016-01-08 17:37:10 +00002635bool HNewInstance::IsStringAlloc() const {
2636 ScopedObjectAccess soa(Thread::Current());
2637 return GetReferenceTypeInfo().IsStringClass();
2638}
2639
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002640bool HInvoke::NeedsEnvironment() const {
2641 if (!IsIntrinsic()) {
2642 return true;
2643 }
2644 IntrinsicOptimizations opt(*this);
2645 return !opt.GetDoesNotNeedEnvironment();
2646}
2647
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002648const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2649 ArtMethod* caller = GetEnvironment()->GetMethod();
2650 ScopedObjectAccess soa(Thread::Current());
2651 // `caller` is null for a top-level graph representing a method whose declaring
2652 // class was not resolved.
2653 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2654}
2655
Vladimir Markodc151b22015-10-15 18:02:30 +01002656bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002657 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002658 return false;
2659 }
2660 if (!IsIntrinsic()) {
2661 return true;
2662 }
2663 IntrinsicOptimizations opt(*this);
2664 return !opt.GetDoesNotNeedDexCache();
2665}
2666
Vladimir Markof64242a2015-12-01 14:58:23 +00002667std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2668 switch (rhs) {
2669 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002670 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002671 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002672 return os << "Recursive";
2673 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2674 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002675 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002676 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002677 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2678 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002679 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2680 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002681 default:
2682 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2683 UNREACHABLE();
2684 }
2685}
2686
Vladimir Markofbb184a2015-11-13 14:47:00 +00002687std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2688 switch (rhs) {
2689 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2690 return os << "explicit";
2691 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2692 return os << "implicit";
2693 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2694 return os << "none";
2695 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002696 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2697 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002698 }
2699}
2700
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002701bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2702 const HLoadClass* other_load_class = other->AsLoadClass();
2703 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2704 // names rather than type indexes. However, we shall also have to re-think the hash code.
2705 if (type_index_ != other_load_class->type_index_ ||
2706 GetPackedFields() != other_load_class->GetPackedFields()) {
2707 return false;
2708 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002709 switch (GetLoadKind()) {
2710 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002711 case LoadKind::kJitTableAddress: {
2712 ScopedObjectAccess soa(Thread::Current());
2713 return GetClass().Get() == other_load_class->GetClass().Get();
2714 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002715 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002716 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002717 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002718 }
2719}
2720
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002721void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002722 SetPackedField<LoadKindField>(load_kind);
2723
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002724 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002725 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002726 RemoveAsUserOfInput(0u);
2727 SetRawInputAt(0u, nullptr);
2728 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002729
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002730 if (!NeedsEnvironment()) {
2731 RemoveEnvironment();
2732 SetSideEffects(SideEffects::None());
2733 }
2734}
2735
2736std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2737 switch (rhs) {
2738 case HLoadClass::LoadKind::kReferrersClass:
2739 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002740 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2741 return os << "BootImageLinkTimePcRelative";
2742 case HLoadClass::LoadKind::kBootImageAddress:
2743 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002744 case HLoadClass::LoadKind::kBssEntry:
2745 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002746 case HLoadClass::LoadKind::kJitTableAddress:
2747 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002748 case HLoadClass::LoadKind::kRuntimeCall:
2749 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002750 default:
2751 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2752 UNREACHABLE();
2753 }
2754}
2755
Vladimir Marko372f10e2016-05-17 16:30:10 +01002756bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2757 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002758 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2759 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002760 if (string_index_ != other_load_string->string_index_ ||
2761 GetPackedFields() != other_load_string->GetPackedFields()) {
2762 return false;
2763 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002764 switch (GetLoadKind()) {
2765 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002766 case LoadKind::kJitTableAddress: {
2767 ScopedObjectAccess soa(Thread::Current());
2768 return GetString().Get() == other_load_string->GetString().Get();
2769 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002770 default:
2771 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002772 }
2773}
2774
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002775void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002776 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002777 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002778 SetPackedField<LoadKindField>(load_kind);
2779
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002780 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002781 RemoveAsUserOfInput(0u);
2782 SetRawInputAt(0u, nullptr);
2783 }
2784 if (!NeedsEnvironment()) {
2785 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002786 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002787 }
2788}
2789
2790std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2791 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002792 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2793 return os << "BootImageLinkTimePcRelative";
2794 case HLoadString::LoadKind::kBootImageAddress:
2795 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002796 case HLoadString::LoadKind::kBssEntry:
2797 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002798 case HLoadString::LoadKind::kJitTableAddress:
2799 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002800 case HLoadString::LoadKind::kRuntimeCall:
2801 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002802 default:
2803 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2804 UNREACHABLE();
2805 }
2806}
2807
Mark Mendellc4701932015-04-10 13:18:51 -04002808void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002809 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2810 HEnvironment* user = use.GetUser();
2811 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002812 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002813 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002814}
2815
Roland Levillainc9b21f82016-03-23 16:36:59 +00002816// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002817HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2818 ArenaAllocator* allocator = GetArena();
2819
2820 if (cond->IsCondition() &&
2821 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2822 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2823 HInstruction* lhs = cond->InputAt(0);
2824 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002825 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002826 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2827 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2828 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2829 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2830 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2831 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2832 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2833 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2834 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2835 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2836 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002837 default:
2838 LOG(FATAL) << "Unexpected condition";
2839 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002840 }
2841 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2842 return replacement;
2843 } else if (cond->IsIntConstant()) {
2844 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002845 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002846 return GetIntConstant(1);
2847 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002848 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002849 return GetIntConstant(0);
2850 }
2851 } else {
2852 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2853 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2854 return replacement;
2855 }
2856}
2857
Roland Levillainc9285912015-12-18 10:38:42 +00002858std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2859 os << "["
2860 << " source=" << rhs.GetSource()
2861 << " destination=" << rhs.GetDestination()
2862 << " type=" << rhs.GetType()
2863 << " instruction=";
2864 if (rhs.GetInstruction() != nullptr) {
2865 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2866 } else {
2867 os << "null";
2868 }
2869 os << " ]";
2870 return os;
2871}
2872
Roland Levillain86503782016-02-11 19:07:30 +00002873std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2874 switch (rhs) {
2875 case TypeCheckKind::kUnresolvedCheck:
2876 return os << "unresolved_check";
2877 case TypeCheckKind::kExactCheck:
2878 return os << "exact_check";
2879 case TypeCheckKind::kClassHierarchyCheck:
2880 return os << "class_hierarchy_check";
2881 case TypeCheckKind::kAbstractClassCheck:
2882 return os << "abstract_class_check";
2883 case TypeCheckKind::kInterfaceCheck:
2884 return os << "interface_check";
2885 case TypeCheckKind::kArrayObjectCheck:
2886 return os << "array_object_check";
2887 case TypeCheckKind::kArrayCheck:
2888 return os << "array_check";
2889 default:
2890 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2891 UNREACHABLE();
2892 }
2893}
2894
Andreas Gampe26de38b2016-07-27 17:53:11 -07002895std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2896 switch (kind) {
2897 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002898 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002899 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002900 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002901 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002902 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002903 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002904 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002905 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002906 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002907
2908 default:
2909 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2910 UNREACHABLE();
2911 }
2912}
2913
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002914} // namespace art