blob: 215fa3e143189e6053272dcd74aa97a293377227 [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
Alex Light86fe9b82020-11-16 16:54:01 +000018#include <algorithm>
Roland Levillain31dd3d62016-02-16 12:21:02 +000019#include <cfloat>
Alex Lightdc281e72021-01-06 12:35:31 -080020#include <functional>
Roland Levillain31dd3d62016-02-16 12:21:02 +000021
Andreas Gampec6ea7d02017-02-01 16:46:28 -080022#include "art_method-inl.h"
Alex Light86fe9b82020-11-16 16:54:01 +000023#include "base/arena_allocator.h"
24#include "base/arena_bit_vector.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "base/bit_utils.h"
26#include "base/bit_vector-inl.h"
Alex Light86fe9b82020-11-16 16:54:01 +000027#include "base/bit_vector.h"
28#include "base/iteration_range.h"
Andreas Gampe85f1c572018-11-21 13:52:48 -080029#include "base/logging.h"
Alex Light86fe9b82020-11-16 16:54:01 +000030#include "base/scoped_arena_allocator.h"
31#include "base/scoped_arena_containers.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070032#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080033#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010034#include "class_root-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040035#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000036#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010037#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010038#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070039#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070040#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000041
Vladimir Marko0a516052019-10-14 13:00:44 +000042namespace art {
Nicolas Geoffray818f2102014-02-18 16:43:35 +000043
Roland Levillain31dd3d62016-02-16 12:21:02 +000044// Enable floating-point static evaluation during constant folding
45// only if all floating-point operations and constants evaluate in the
46// range and precision of the type used (i.e., 32-bit float, 64-bit
47// double).
48static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
49
Vladimir Marko02ca05a2020-05-12 13:58:51 +010050ReferenceTypeInfo::TypeHandle HandleCache::CreateRootHandle(VariableSizedHandleScope* handles,
51 ClassRoot class_root) {
52 // Mutator lock is required for NewHandle and GetClassRoot().
David Brazdilbadd8262016-02-02 16:28:56 +000053 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko02ca05a2020-05-12 13:58:51 +010054 return handles->NewHandle(GetClassRoot(class_root));
David Brazdilbadd8262016-02-02 16:28:56 +000055}
56
Nicolas Geoffray818f2102014-02-18 16:43:35 +000057void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010058 block->SetBlockId(blocks_.size());
59 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000060}
61
Nicolas Geoffray804d0932014-05-02 08:46:00 +010062void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010063 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
64 DCHECK_EQ(visited->GetHighestBitSet(), -1);
65
Vladimir Marko69d310e2017-10-09 14:12:23 +010066 // Allocate memory from local ScopedArenaAllocator.
67 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010068 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010069 ArenaBitVector visiting(
Andreas Gampe3db70682018-12-26 15:12:03 -080070 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +010071 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010072 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010073 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
74 0u,
75 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010076 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010077 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010078 constexpr size_t kDefaultWorklistSize = 8;
79 worklist.reserve(kDefaultWorklistSize);
80 visited->SetBit(entry_block_->GetBlockId());
81 visiting.SetBit(entry_block_->GetBlockId());
82 worklist.push_back(entry_block_);
83
84 while (!worklist.empty()) {
85 HBasicBlock* current = worklist.back();
86 uint32_t current_id = current->GetBlockId();
87 if (successors_visited[current_id] == current->GetSuccessors().size()) {
88 visiting.ClearBit(current_id);
89 worklist.pop_back();
90 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010091 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
92 uint32_t successor_id = successor->GetBlockId();
93 if (visiting.IsBitSet(successor_id)) {
94 DCHECK(ContainsElement(worklist, successor));
95 successor->AddBackEdge(current);
96 } else if (!visited->IsBitSet(successor_id)) {
97 visited->SetBit(successor_id);
98 visiting.SetBit(successor_id);
99 worklist.push_back(successor);
100 }
101 }
102 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103}
104
Artem Serov21c7e6f2017-07-27 16:04:42 +0100105// Remove the environment use records of the instruction for users.
106void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100107 for (HEnvironment* environment = instruction->GetEnvironment();
108 environment != nullptr;
109 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000111 if (environment->GetInstructionAt(i) != nullptr) {
112 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000113 }
114 }
115 }
116}
117
Artem Serov21c7e6f2017-07-27 16:04:42 +0100118// Return whether the instruction has an environment and it's used by others.
119bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
120 for (HEnvironment* environment = instruction->GetEnvironment();
121 environment != nullptr;
122 environment = environment->GetParent()) {
123 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
124 HInstruction* user = environment->GetInstructionAt(i);
125 if (user != nullptr) {
126 return true;
127 }
128 }
129 }
130 return false;
131}
132
133// Reset environment records of the instruction itself.
134void ResetEnvironmentInputRecords(HInstruction* instruction) {
135 for (HEnvironment* environment = instruction->GetEnvironment();
136 environment != nullptr;
137 environment = environment->GetParent()) {
138 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
139 DCHECK(environment->GetHolder() == instruction);
140 if (environment->GetInstructionAt(i) != nullptr) {
141 environment->SetRawEnvAt(i, nullptr);
142 }
143 }
144 }
145}
146
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000147static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100148 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000149 RemoveEnvironmentUses(instruction);
150}
151
Roland Levillainfc600dc2014-12-02 17:16:31 +0000152void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100153 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000154 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100155 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000156 if (block == nullptr) continue;
Nicolas Geoffray2cc9d342019-04-26 14:21:14 +0100157 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
158 RemoveAsUser(it.Current());
159 }
Roland Levillainfc600dc2014-12-02 17:16:31 +0000160 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
161 RemoveAsUser(it.Current());
162 }
163 }
164 }
165}
166
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100167void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100168 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000169 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100170 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000171 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100172 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000173 for (HBasicBlock* successor : block->GetSuccessors()) {
174 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000175 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100176 // Remove the block from the list of blocks, so that further analyses
177 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100178 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600179 if (block->IsExitBlock()) {
180 SetExitBlock(nullptr);
181 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000182 // Mark the block as removed. This is used by the HGraphBuilder to discard
183 // the block as a branch target.
184 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000185 }
186 }
187}
188
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000189GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100190 // Allocate memory from local ScopedArenaAllocator.
191 ScopedArenaAllocator allocator(GetArenaStack());
192
193 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
194 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000195
David Brazdil86ea7ee2016-02-16 09:26:07 +0000196 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000197 FindBackEdges(&visited);
198
David Brazdil86ea7ee2016-02-16 09:26:07 +0000199 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000200 // the initial DFS as users from other instructions, so that
201 // users can be safely removed before uses later.
202 RemoveInstructionsAsUsersFromDeadBlocks(visited);
203
David Brazdil86ea7ee2016-02-16 09:26:07 +0000204 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000205 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000206 // predecessors list of live blocks.
207 RemoveDeadBlocks(visited);
208
David Brazdil86ea7ee2016-02-16 09:26:07 +0000209 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 // dominators and the reverse post order.
211 SimplifyCFG();
212
David Brazdil86ea7ee2016-02-16 09:26:07 +0000213 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100214 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000215
David Brazdil86ea7ee2016-02-16 09:26:07 +0000216 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000217 // set the loop information on each block.
218 GraphAnalysisResult result = AnalyzeLoops();
219 if (result != kAnalysisSuccess) {
220 return result;
221 }
222
David Brazdil86ea7ee2016-02-16 09:26:07 +0000223 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 // which needs the information to build catch block phis from values of
225 // locals at throwing instructions inside try blocks.
226 ComputeTryBlockInformation();
227
228 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229}
230
231void HGraph::ClearDominanceInformation() {
Alex Light210a78d2020-11-30 16:58:05 -0800232 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100233 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100234 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100235 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100236}
237
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000238void HGraph::ClearLoopInformation() {
239 SetHasIrreducibleLoops(false);
Alex Light210a78d2020-11-30 16:58:05 -0800240 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100241 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000242 }
243}
244
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100245void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000246 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100247 dominator_ = nullptr;
248}
249
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000250HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
251 HInstruction* instruction = GetFirstInstruction();
252 while (instruction->IsParallelMove()) {
253 instruction = instruction->GetNext();
254 }
255 return instruction;
256}
257
David Brazdil3f4a5222016-05-06 12:46:21 +0100258static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
259 DCHECK(ContainsElement(block->GetSuccessors(), successor));
260
261 HBasicBlock* old_dominator = successor->GetDominator();
262 HBasicBlock* new_dominator =
263 (old_dominator == nullptr) ? block
264 : CommonDominator::ForPair(old_dominator, block);
265
266 if (old_dominator == new_dominator) {
267 return false;
268 } else {
269 successor->SetDominator(new_dominator);
270 return true;
271 }
272}
273
Alex Light86fe9b82020-11-16 16:54:01 +0000274// TODO Consider moving this entirely into LoadStoreAnalysis/Elimination.
275bool HGraph::PathBetween(uint32_t source_idx, uint32_t dest_idx) const {
276 DCHECK_LT(source_idx, blocks_.size()) << "source not present in graph!";
277 DCHECK_LT(dest_idx, blocks_.size()) << "dest not present in graph!";
278 DCHECK(blocks_[source_idx] != nullptr);
279 DCHECK(blocks_[dest_idx] != nullptr);
280 return reachability_graph_.IsBitSet(source_idx, dest_idx);
281}
282
283bool HGraph::PathBetween(const HBasicBlock* source, const HBasicBlock* dest) const {
284 if (source == nullptr || dest == nullptr) {
285 return false;
286 }
287 size_t source_idx = source->GetBlockId();
288 size_t dest_idx = dest->GetBlockId();
289 return PathBetween(source_idx, dest_idx);
290}
291
292// This function/struct calculates the reachability of every node from every
293// other node by iteratively using DFS to find reachability of each individual
294// block.
295//
296// This is in practice faster then the simpler Floyd-Warshall since while that
297// is O(N**3) this is O(N*(E + N)) where N is the number of blocks and E is the
298// number of edges. Since in practice each block only has a few outgoing edges
299// we can confidently say that E ~ B*N where B is a small number (~3). We also
300// memoize the results as we go allowing us to (potentially) avoid walking the
301// entire graph for every node. To make best use of this memoization we
302// calculate the reachability of blocks in PostOrder. This means that
303// (generally) blocks that are dominated by many other blocks and dominate few
304// blocks themselves will be examined first. This makes it more likely we can
305// use our memoized results.
306class ReachabilityAnalysisHelper {
307 public:
308 ReachabilityAnalysisHelper(const HGraph* graph,
309 ArenaBitVectorArray* reachability_graph,
310 ArenaStack* arena_stack)
311 : graph_(graph),
312 reachability_graph_(reachability_graph),
313 arena_stack_(arena_stack),
314 temporaries_(arena_stack_),
315 block_size_(RoundUp(graph_->GetBlocks().size(), BitVector::kWordBits)),
316 all_visited_nodes_(
317 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph),
318 not_post_order_visited_(
319 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph) {
320 // We can't adjust the size of reachability graph any more without breaking
321 // our allocator invariants so it had better be large enough.
322 CHECK_GE(reachability_graph_->NumRows(), graph_->GetBlocks().size());
323 CHECK_GE(reachability_graph_->NumColumns(), graph_->GetBlocks().size());
324 not_post_order_visited_.SetInitialBits(graph_->GetBlocks().size());
325 }
326
327 void CalculateReachability() {
328 // Calculate what blocks connect using repeated DFS
329 //
330 // Going in PostOrder should generally give memoization a good shot of
331 // hitting.
332 for (const HBasicBlock* blk : graph_->GetPostOrder()) {
333 if (blk == nullptr) {
334 continue;
335 }
336 not_post_order_visited_.ClearBit(blk->GetBlockId());
337 CalculateConnectednessOn(blk);
338 all_visited_nodes_.SetBit(blk->GetBlockId());
339 }
340 // Get all other bits
341 for (auto idx : not_post_order_visited_.Indexes()) {
342 const HBasicBlock* blk = graph_->GetBlocks()[idx];
343 if (blk == nullptr) {
344 continue;
345 }
346 CalculateConnectednessOn(blk);
347 all_visited_nodes_.SetBit(blk->GetBlockId());
348 }
349 }
350
351 private:
352 void AddEdge(uint32_t source, const HBasicBlock* dest) {
353 reachability_graph_->SetBit(source, dest->GetBlockId());
354 }
355
356 // Union the reachability of 'idx' into 'update_block_idx'. This is done to
357 // implement memoization. In order to improve performance we do this in 4-byte
358 // blocks. Clang should be able to optimize this to larger blocks if possible.
359 void UnionBlock(size_t update_block_idx, size_t idx) {
360 reachability_graph_->UnionRows(update_block_idx, idx);
361 }
362
363 // Single DFS to get connectedness of a single block
364 void CalculateConnectednessOn(const HBasicBlock* const target_block) {
365 const uint32_t target_idx = target_block->GetBlockId();
366 ScopedArenaAllocator connectedness_temps(arena_stack_);
367 // What nodes we have already discovered and either have processed or are
368 // already on the queue.
369 ArenaBitVector discovered(
370 &connectedness_temps, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph);
371 // The work stack. What blocks we still need to process.
372 ScopedArenaVector<const HBasicBlock*> work_stack(
373 connectedness_temps.Adapter(kArenaAllocReachabilityGraph));
374 // Known max size since otherwise we'd have blocks multiple times. Avoids
375 // re-allocation
376 work_stack.reserve(graph_->GetBlocks().size());
377 discovered.SetBit(target_idx);
378 work_stack.push_back(target_block);
379 // Main DFS Loop.
380 while (!work_stack.empty()) {
381 const HBasicBlock* cur = work_stack.back();
382 work_stack.pop_back();
383 // Memoization of previous runs.
384 if (all_visited_nodes_.IsBitSet(cur->GetBlockId())) {
385 DCHECK_NE(target_block, cur);
386 // Already explored from here. Just use that data.
387 UnionBlock(target_idx, cur->GetBlockId());
388 continue;
389 }
390 for (const HBasicBlock* succ : cur->GetSuccessors()) {
391 AddEdge(target_idx, succ);
392 if (!discovered.IsBitSet(succ->GetBlockId())) {
393 work_stack.push_back(succ);
394 discovered.SetBit(succ->GetBlockId());
395 }
396 }
397 }
398 }
399
400 const HGraph* graph_;
401 // The graph's reachability_graph_ on the main allocator.
402 ArenaBitVectorArray* reachability_graph_;
403 ArenaStack* arena_stack_;
404 // An allocator for temporary bit-vectors used by this algorithm. The
405 // 'SetBit,ClearBit' on reachability_graph_ prior to the construction of this
406 // object should be the only allocation on the main allocator so it's safe to
407 // make a sub-allocator here.
408 ScopedArenaAllocator temporaries_;
409 // number of columns
410 const size_t block_size_;
411 // Where we've already completely calculated connectedness.
412 ArenaBitVector all_visited_nodes_;
413 // What we never visited and need to do later
414 ArenaBitVector not_post_order_visited_;
415
416 DISALLOW_COPY_AND_ASSIGN(ReachabilityAnalysisHelper);
417};
418
419void HGraph::ComputeReachabilityInformation() {
420 DCHECK_EQ(reachability_graph_.GetRawData().NumSetBits(), 0u);
421 DCHECK(reachability_graph_.IsExpandable());
422 // Reserve all the bits we'll need. This is the only allocation on the
423 // standard allocator we do here, enabling us to create a new ScopedArena for
424 // use with temporaries.
425 //
426 // reachability_graph_ acts as |N| x |N| graph for PathBetween. Array is
427 // padded so each row starts on an BitVector::kWordBits-bit alignment for
428 // simplicity and performance, allowing us to union blocks together without
429 // going bit-by-bit.
430 reachability_graph_.Resize(blocks_.size(), blocks_.size(), /*clear=*/false);
431 ReachabilityAnalysisHelper helper(this, &reachability_graph_, GetArenaStack());
432 helper.CalculateReachability();
433}
434
435void HGraph::ClearReachabilityInformation() {
436 reachability_graph_.Clear();
437}
438
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100439void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100440 DCHECK(reverse_post_order_.empty());
441 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100442 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100443
Vladimir Marko69d310e2017-10-09 14:12:23 +0100444 // Allocate memory from local ScopedArenaAllocator.
445 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100446 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100447 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100448 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100449 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
450 0u,
451 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100452 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100453 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100454 constexpr size_t kDefaultWorklistSize = 8;
455 worklist.reserve(kDefaultWorklistSize);
456 worklist.push_back(entry_block_);
457
458 while (!worklist.empty()) {
459 HBasicBlock* current = worklist.back();
460 uint32_t current_id = current->GetBlockId();
461 if (successors_visited[current_id] == current->GetSuccessors().size()) {
462 worklist.pop_back();
463 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100464 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100465 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100466
467 // Once all the forward edges have been visited, we know the immediate
468 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100469 if (++visits[successor->GetBlockId()] ==
470 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100471 reverse_post_order_.push_back(successor);
472 worklist.push_back(successor);
473 }
474 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000475 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000476
David Brazdil3f4a5222016-05-06 12:46:21 +0100477 // Check if the graph has back edges not dominated by their respective headers.
478 // If so, we need to update the dominators of those headers and recursively of
479 // their successors. We do that with a fix-point iteration over all blocks.
480 // The algorithm is guaranteed to terminate because it loops only if the sum
481 // of all dominator chains has decreased in the current iteration.
482 bool must_run_fix_point = false;
483 for (HBasicBlock* block : blocks_) {
484 if (block != nullptr &&
485 block->IsLoopHeader() &&
486 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
487 must_run_fix_point = true;
488 break;
489 }
490 }
491 if (must_run_fix_point) {
492 bool update_occurred = true;
493 while (update_occurred) {
494 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100495 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100496 for (HBasicBlock* successor : block->GetSuccessors()) {
497 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
498 }
499 }
500 }
501 }
502
503 // Make sure that there are no remaining blocks whose dominator information
504 // needs to be updated.
505 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100506 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100507 for (HBasicBlock* successor : block->GetSuccessors()) {
508 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
509 }
510 }
511 }
512
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000513 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000514 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100515 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000516 if (!block->IsEntryBlock()) {
517 block->GetDominator()->AddDominatedBlock(block);
518 }
519 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000520}
521
David Brazdilfc6a86a2015-06-26 10:33:45 +0000522HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100523 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000524 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000525 // Use `InsertBetween` to ensure the predecessor index and successor index of
526 // `block` and `successor` are preserved.
527 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000528 return new_block;
529}
530
531void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
532 // Insert a new node between `block` and `successor` to split the
533 // critical edge.
534 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100535 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100536 if (successor->IsLoopHeader()) {
537 // If we split at a back edge boundary, make the new block the back edge.
538 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000539 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100540 info->RemoveBackEdge(block);
541 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100542 }
543 }
544}
545
Artem Serovc73ee372017-07-31 15:08:40 +0100546// Reorder phi inputs to match reordering of the block's predecessors.
547static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
548 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
549 HPhi* phi = it.Current()->AsPhi();
550 HInstruction* first_instr = phi->InputAt(first);
551 HInstruction* second_instr = phi->InputAt(second);
552 phi->ReplaceInput(first_instr, second);
553 phi->ReplaceInput(second_instr, first);
554 }
555}
556
557// Make sure that the first predecessor of a loop header is the incoming block.
558void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
559 DCHECK(header->IsLoopHeader());
560 HLoopInformation* info = header->GetLoopInformation();
561 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
562 HBasicBlock* to_swap = header->GetPredecessors()[0];
563 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
564 HBasicBlock* predecessor = header->GetPredecessors()[pred];
565 if (!info->IsBackEdge(*predecessor)) {
566 header->predecessors_[pred] = to_swap;
567 header->predecessors_[0] = predecessor;
568 FixPhisAfterPredecessorsReodering(header, 0, pred);
569 break;
570 }
571 }
572 }
573}
574
Artem Serov09faaea2017-12-07 14:36:01 +0000575// Transform control flow of the loop to a single preheader format (don't touch the data flow).
576// New_preheader can be already among the header predecessors - this situation will be correctly
577// processed.
578static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
579 HLoopInformation* loop_info = header->GetLoopInformation();
580 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
581 HBasicBlock* predecessor = header->GetPredecessors()[pred];
582 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
583 predecessor->ReplaceSuccessor(header, new_preheader);
584 pred--;
585 }
586 }
587}
588
589// == Before == == After ==
590// _________ _________ _________ _________
591// | B0 | | B1 | (old preheaders) | B0 | | B1 |
592// |=========| |=========| |=========| |=========|
593// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
594// |_________| |_________| |_________| |_________|
595// \ / \ /
596// \ / ___v____________v___
597// \ / (new preheader) | B20 <- B0, B1 |
598// | | |====================|
599// | | | i20 = phi(i0, i1) |
600// | | |____________________|
601// | | |
602// /\ | | /\ /\ | /\
603// / v_______v_________v_______v \ / v___________v_____________v \
604// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
605// | |===========================| | (header) | |===========================| |
606// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
607// | |___________________________| | | |___________________________| |
608// | / \ | | / \ |
609// | ... ... | | ... ... |
610// | _________ _________ | | _________ _________ |
611// | | B2 | | B3 | | | | B2 | | B3 | |
612// | |=========| |=========| | (back edges) | |=========| |=========| |
613// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
614// | |_________| |_________| | | |_________| |_________| |
615// \ / \ / \ / \ /
616// \___/ \___/ \___/ \___/
617//
618void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
619 HLoopInformation* loop_info = header->GetLoopInformation();
620
621 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
622 AddBlock(preheader);
623 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
624
625 // If the old header has no Phis then we only need to fix the control flow.
626 if (header->GetPhis().IsEmpty()) {
627 FixControlForNewSinglePreheader(header, preheader);
628 preheader->AddSuccessor(header);
629 return;
630 }
631
632 // Find the first non-back edge block in the header's predecessors list.
633 size_t first_nonbackedge_pred_pos = 0;
634 bool found = false;
635 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
636 HBasicBlock* predecessor = header->GetPredecessors()[pred];
637 if (!loop_info->IsBackEdge(*predecessor)) {
638 first_nonbackedge_pred_pos = pred;
639 found = true;
640 break;
641 }
642 }
643
644 DCHECK(found);
645
646 // Fix the data-flow.
647 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
648 HPhi* header_phi = it.Current()->AsPhi();
649
650 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
651 header_phi->GetRegNumber(),
652 0,
653 header_phi->GetType());
654 if (header_phi->GetType() == DataType::Type::kReference) {
655 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
656 }
657 preheader->AddPhi(preheader_phi);
658
659 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
660 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
661 preheader_phi->AddInput(orig_input);
662
663 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
664 input_pos < header_phi->InputCount();
665 input_pos++) {
666 HInstruction* input = header_phi->InputAt(input_pos);
667 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
668
669 if (loop_info->Contains(*pred_block)) {
670 DCHECK(loop_info->IsBackEdge(*pred_block));
671 } else {
672 preheader_phi->AddInput(input);
673 header_phi->RemoveInputAt(input_pos);
674 input_pos--;
675 }
676 }
677 }
678
679 // Fix the control-flow.
680 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
681 preheader->InsertBetween(first_pred, header);
682
683 FixControlForNewSinglePreheader(header, preheader);
684}
685
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100686void HGraph::SimplifyLoop(HBasicBlock* header) {
687 HLoopInformation* info = header->GetLoopInformation();
688
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100689 // Make sure the loop has only one pre header. This simplifies SSA building by having
690 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000691 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
692 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000693 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000694 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000695 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100696 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100697
Artem Serovc73ee372017-07-31 15:08:40 +0100698 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100699
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100700 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000701 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
702 // Called from DeadBlockElimination. Update SuspendCheck pointer.
703 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100704 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100705}
706
David Brazdilffee3d32015-07-06 11:48:53 +0100707void HGraph::ComputeTryBlockInformation() {
708 // Iterate in reverse post order to propagate try membership information from
709 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100710 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100711 if (block->IsEntryBlock() || block->IsCatchBlock()) {
712 // Catch blocks after simplification have only exceptional predecessors
713 // and hence are never in tries.
714 continue;
715 }
716
717 // Infer try membership from the first predecessor. Having simplified loops,
718 // the first predecessor can never be a back edge and therefore it must have
719 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100720 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100721 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100722 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000723 if (try_entry != nullptr &&
724 (block->GetTryCatchInformation() == nullptr ||
725 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
726 // We are either setting try block membership for the first time or it
727 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100728 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100729 }
David Brazdilffee3d32015-07-06 11:48:53 +0100730 }
731}
732
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100733void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000734// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100735 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000736 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100737 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
738 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
739 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
740 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100741 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000742 if (block->GetSuccessors().size() > 1) {
743 // Only split normal-flow edges. We cannot split exceptional edges as they
744 // are synthesized (approximate real control flow), and we do not need to
745 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000746 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
747 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
748 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100749 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000750 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000751 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
752 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000753 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000754 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100755 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000756 // SplitCriticalEdge could have invalidated the `normal_successors`
757 // ArrayRef. We must re-acquire it.
758 normal_successors = block->GetNormalSuccessors();
759 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
760 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100761 }
762 }
763 }
764 if (block->IsLoopHeader()) {
765 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000766 } else if (!block->IsEntryBlock() &&
767 block->GetFirstInstruction() != nullptr &&
768 block->GetFirstInstruction()->IsSuspendCheck()) {
769 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000770 // a loop got dismantled. Just remove the suspend check.
771 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100772 }
773 }
774}
775
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000776GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100777 // We iterate post order to ensure we visit inner loops before outer loops.
778 // `PopulateRecursive` needs this guarantee to know whether a natural loop
779 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100780 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100781 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100782 if (block->IsCatchBlock()) {
783 // TODO: Dealing with exceptional back edges could be tricky because
784 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000785 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000786 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100787 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000788 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100789 }
790 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000791 return kAnalysisSuccess;
792}
793
794void HLoopInformation::Dump(std::ostream& os) {
795 os << "header: " << header_->GetBlockId() << std::endl;
796 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
797 for (HBasicBlock* block : back_edges_) {
798 os << "back edge: " << block->GetBlockId() << std::endl;
799 }
800 for (HBasicBlock* block : header_->GetPredecessors()) {
801 os << "predecessor: " << block->GetBlockId() << std::endl;
802 }
803 for (uint32_t idx : blocks_.Indexes()) {
804 os << " in loop: " << idx << std::endl;
805 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100806}
807
David Brazdil8d5b8b22015-03-24 10:51:52 +0000808void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000809 // New constants are inserted before the SuspendCheck at the bottom of the
810 // entry block. Note that this method can be called from the graph builder and
811 // the entry block therefore may not end with SuspendCheck->Goto yet.
812 HInstruction* insert_before = nullptr;
813
814 HInstruction* gota = entry_block_->GetLastInstruction();
815 if (gota != nullptr && gota->IsGoto()) {
816 HInstruction* suspend_check = gota->GetPrevious();
817 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
818 insert_before = suspend_check;
819 } else {
820 insert_before = gota;
821 }
822 }
823
824 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000825 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000826 } else {
827 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000828 }
829}
830
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600831HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100832 // For simplicity, don't bother reviving the cached null constant if it is
833 // not null and not in a block. Otherwise, we need to clear the instruction
834 // id and/or any invariants the graph is assuming when adding new instructions.
835 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100836 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100837 cached_null_constant_->SetReferenceTypeInfo(GetInexactObjectRti());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000838 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000839 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000840 if (kIsDebugBuild) {
841 ScopedObjectAccess soa(Thread::Current());
842 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
843 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000844 return cached_null_constant_;
845}
846
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100847HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100848 // For simplicity, don't bother reviving the cached current method if it is
849 // not null and not in a block. Otherwise, we need to clear the instruction
850 // id and/or any invariants the graph is assuming when adding new instructions.
851 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100852 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100853 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600854 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100855 if (entry_block_->GetFirstInstruction() == nullptr) {
856 entry_block_->AddInstruction(cached_current_method_);
857 } else {
858 entry_block_->InsertInstructionBefore(
859 cached_current_method_, entry_block_->GetFirstInstruction());
860 }
861 }
862 return cached_current_method_;
863}
864
Igor Murashkind01745e2017-04-05 16:40:31 -0700865const char* HGraph::GetMethodName() const {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800866 const dex::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
Igor Murashkind01745e2017-04-05 16:40:31 -0700867 return dex_file_.GetMethodName(method_id);
868}
869
870std::string HGraph::PrettyMethod(bool with_signature) const {
871 return dex_file_.PrettyMethod(method_idx_, with_signature);
872}
873
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100874HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000875 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100876 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000877 DCHECK(IsUint<1>(value));
878 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100879 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100880 case DataType::Type::kInt8:
881 case DataType::Type::kUint16:
882 case DataType::Type::kInt16:
883 case DataType::Type::kInt32:
884 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600885 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000886
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100887 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600888 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000889
890 default:
891 LOG(FATAL) << "Unsupported constant type";
892 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000893 }
David Brazdil46e2a392015-03-16 17:31:52 +0000894}
895
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000896void HGraph::CacheFloatConstant(HFloatConstant* constant) {
897 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
898 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
899 cached_float_constants_.Overwrite(value, constant);
900}
901
902void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
903 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
904 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
905 cached_double_constants_.Overwrite(value, constant);
906}
907
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000908void HLoopInformation::Add(HBasicBlock* block) {
909 blocks_.SetBit(block->GetBlockId());
910}
911
David Brazdil46e2a392015-03-16 17:31:52 +0000912void HLoopInformation::Remove(HBasicBlock* block) {
913 blocks_.ClearBit(block->GetBlockId());
914}
915
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100916void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
917 if (blocks_.IsBitSet(block->GetBlockId())) {
918 return;
919 }
920
921 blocks_.SetBit(block->GetBlockId());
922 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100923 if (block->IsLoopHeader()) {
924 // We're visiting loops in post-order, so inner loops must have been
925 // populated already.
926 DCHECK(block->GetLoopInformation()->IsPopulated());
927 if (block->GetLoopInformation()->IsIrreducible()) {
928 contains_irreducible_loop_ = true;
929 }
930 }
Vladimir Marko60584552015-09-03 13:35:12 +0000931 for (HBasicBlock* predecessor : block->GetPredecessors()) {
932 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100933 }
934}
935
David Brazdilc2e8af92016-04-05 17:15:19 +0100936void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
937 size_t block_id = block->GetBlockId();
938
939 // If `block` is in `finalized`, we know its membership in the loop has been
940 // decided and it does not need to be revisited.
941 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000942 return;
943 }
944
David Brazdilc2e8af92016-04-05 17:15:19 +0100945 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000946 if (block->IsLoopHeader()) {
947 // If we hit a loop header in an irreducible loop, we first check if the
948 // pre header of that loop belongs to the currently analyzed loop. If it does,
949 // then we visit the back edges.
950 // Note that we cannot use GetPreHeader, as the loop may have not been populated
951 // yet.
952 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100953 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000954 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000955 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100956 blocks_.SetBit(block_id);
957 finalized->SetBit(block_id);
958 is_finalized = true;
959
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000960 HLoopInformation* info = block->GetLoopInformation();
961 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100962 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000963 }
964 }
965 } else {
966 // Visit all predecessors. If one predecessor is part of the loop, this
967 // block is also part of this loop.
968 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100969 PopulateIrreducibleRecursive(predecessor, finalized);
970 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000971 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100972 blocks_.SetBit(block_id);
973 finalized->SetBit(block_id);
974 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000975 }
976 }
977 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100978
979 // All predecessors have been recursively visited. Mark finalized if not marked yet.
980 if (!is_finalized) {
981 finalized->SetBit(block_id);
982 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000983}
984
985void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100986 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000987 // Populate this loop: starting with the back edge, recursively add predecessors
988 // that are not already part of that loop. Set the header as part of the loop
989 // to end the recursion.
990 // This is a recursive implementation of the algorithm described in
991 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100992 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000993 blocks_.SetBit(header_->GetBlockId());
994 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100995
David Brazdil3f4a5222016-05-06 12:46:21 +0100996 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100997
998 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100999 // Allocate memory from local ScopedArenaAllocator.
1000 ScopedArenaAllocator allocator(graph->GetArenaStack());
1001 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +01001002 graph->GetBlocks().size(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001003 /* expandable= */ false,
David Brazdilc2e8af92016-04-05 17:15:19 +01001004 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +01001005 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +01001006 // Stop marking blocks at the loop header.
1007 visited.SetBit(header_->GetBlockId());
1008
David Brazdilc2e8af92016-04-05 17:15:19 +01001009 for (HBasicBlock* back_edge : GetBackEdges()) {
1010 PopulateIrreducibleRecursive(back_edge, &visited);
1011 }
1012 } else {
1013 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001014 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001015 }
David Brazdila4b8c212015-05-07 09:59:30 +01001016 }
David Brazdilc2e8af92016-04-05 17:15:19 +01001017
Vladimir Markofd66c502016-04-18 15:37:01 +01001018 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
1019 // When compiling in OSR mode, all loops in the compiled method may be entered
1020 // from the interpreter. We treat this OSR entry point just like an extra entry
1021 // to an irreducible loop, so we need to mark the method's loops as irreducible.
1022 // This does not apply to inlined loops which do not act as OSR entry points.
1023 if (suspend_check_ == nullptr) {
1024 // Just building the graph in OSR mode, this loop is not inlined. We never build an
1025 // inner graph in OSR mode as we can do OSR transition only from the outer method.
1026 is_irreducible_loop = true;
1027 } else {
1028 // Look at the suspend check's environment to determine if the loop was inlined.
1029 DCHECK(suspend_check_->HasEnvironment());
1030 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
1031 is_irreducible_loop = true;
1032 }
1033 }
1034 }
1035 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001036 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +01001037 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +01001038 graph->SetHasIrreducibleLoops(true);
1039 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08001040 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +01001041}
1042
Artem Serov7f4aff62017-06-21 17:02:18 +01001043void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
1044 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
1045 blocks_.Union(&inner_loop->blocks_);
1046 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
1047 if (outer_loop != nullptr) {
1048 outer_loop->PopulateInnerLoopUpwards(this);
1049 }
1050}
1051
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001052HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001053 HBasicBlock* block = header_->GetPredecessors()[0];
1054 DCHECK(irreducible_ || (block == header_->GetDominator()));
1055 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001056}
1057
1058bool HLoopInformation::Contains(const HBasicBlock& block) const {
1059 return blocks_.IsBitSet(block.GetBlockId());
1060}
1061
1062bool HLoopInformation::IsIn(const HLoopInformation& other) const {
1063 return other.blocks_.IsBitSet(header_->GetBlockId());
1064}
1065
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001066bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
1067 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -07001068}
1069
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001070size_t HLoopInformation::GetLifetimeEnd() const {
1071 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001072 for (HBasicBlock* back_edge : GetBackEdges()) {
1073 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001074 }
1075 return last_position;
1076}
1077
David Brazdil3f4a5222016-05-06 12:46:21 +01001078bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
1079 for (HBasicBlock* back_edge : GetBackEdges()) {
1080 DCHECK(back_edge->GetDominator() != nullptr);
1081 if (!header_->Dominates(back_edge)) {
1082 return true;
1083 }
1084 }
1085 return false;
1086}
1087
Anton Shaminf89381f2016-05-16 16:44:13 +06001088bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
1089 for (HBasicBlock* back_edge : GetBackEdges()) {
1090 if (!block->Dominates(back_edge)) {
1091 return false;
1092 }
1093 }
1094 return true;
1095}
1096
David Sehrc757dec2016-11-04 15:48:34 -07001097
1098bool HLoopInformation::HasExitEdge() const {
1099 // Determine if this loop has at least one exit edge.
1100 HBlocksInLoopReversePostOrderIterator it_loop(*this);
1101 for (; !it_loop.Done(); it_loop.Advance()) {
1102 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1103 if (!Contains(*successor)) {
1104 return true;
1105 }
1106 }
1107 }
1108 return false;
1109}
1110
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001111bool HBasicBlock::Dominates(HBasicBlock* other) const {
1112 // Walk up the dominator tree from `other`, to find out if `this`
1113 // is an ancestor.
1114 HBasicBlock* current = other;
1115 while (current != nullptr) {
1116 if (current == this) {
1117 return true;
1118 }
1119 current = current->GetDominator();
1120 }
1121 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122}
1123
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001124static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +01001125 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001126 for (size_t i = 0; i < inputs.size(); ++i) {
1127 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001128 }
1129 // Environment should be created later.
1130 DCHECK(!instruction->HasEnvironment());
1131}
1132
Artem Serovcced8ba2017-07-19 18:18:09 +01001133void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
1134 DCHECK(initial->GetBlock() == this);
1135 InsertPhiAfter(replacement, initial);
1136 initial->ReplaceWith(replacement);
1137 RemovePhi(initial);
1138}
1139
Roland Levillainccc07a92014-09-16 14:48:16 +01001140void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
1141 HInstruction* replacement) {
1142 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -04001143 if (initial->IsControlFlow()) {
1144 // We can only replace a control flow instruction with another control flow instruction.
1145 DCHECK(replacement->IsControlFlow());
1146 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001147 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -04001148 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001149 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +01001150 DCHECK(initial->GetUses().empty());
1151 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -04001152 replacement->SetBlock(this);
1153 replacement->SetId(GetGraph()->GetNextInstructionId());
1154 instructions_.InsertInstructionBefore(replacement, initial);
1155 UpdateInputsUsers(replacement);
1156 } else {
1157 InsertInstructionBefore(replacement, initial);
1158 initial->ReplaceWith(replacement);
1159 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001160 RemoveInstruction(initial);
1161}
1162
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001163static void Add(HInstructionList* instruction_list,
1164 HBasicBlock* block,
1165 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +00001166 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +00001167 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001168 instruction->SetBlock(block);
1169 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001170 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001171 instruction_list->AddInstruction(instruction);
1172}
1173
1174void HBasicBlock::AddInstruction(HInstruction* instruction) {
1175 Add(&instructions_, this, instruction);
1176}
1177
1178void HBasicBlock::AddPhi(HPhi* phi) {
1179 Add(&phis_, this, phi);
1180}
1181
David Brazdilc3d743f2015-04-22 13:40:50 +01001182void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1183 DCHECK(!cursor->IsPhi());
1184 DCHECK(!instruction->IsPhi());
1185 DCHECK_EQ(instruction->GetId(), -1);
1186 DCHECK_NE(cursor->GetId(), -1);
1187 DCHECK_EQ(cursor->GetBlock(), this);
1188 DCHECK(!instruction->IsControlFlow());
1189 instruction->SetBlock(this);
1190 instruction->SetId(GetGraph()->GetNextInstructionId());
1191 UpdateInputsUsers(instruction);
1192 instructions_.InsertInstructionBefore(instruction, cursor);
1193}
1194
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001195void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1196 DCHECK(!cursor->IsPhi());
1197 DCHECK(!instruction->IsPhi());
1198 DCHECK_EQ(instruction->GetId(), -1);
1199 DCHECK_NE(cursor->GetId(), -1);
1200 DCHECK_EQ(cursor->GetBlock(), this);
1201 DCHECK(!instruction->IsControlFlow());
1202 DCHECK(!cursor->IsControlFlow());
1203 instruction->SetBlock(this);
1204 instruction->SetId(GetGraph()->GetNextInstructionId());
1205 UpdateInputsUsers(instruction);
1206 instructions_.InsertInstructionAfter(instruction, cursor);
1207}
1208
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001209void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1210 DCHECK_EQ(phi->GetId(), -1);
1211 DCHECK_NE(cursor->GetId(), -1);
1212 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001213 phi->SetBlock(this);
1214 phi->SetId(GetGraph()->GetNextInstructionId());
1215 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001216 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001217}
1218
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001219static void Remove(HInstructionList* instruction_list,
1220 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001221 HInstruction* instruction,
1222 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001223 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001224 instruction->SetBlock(nullptr);
1225 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001226 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001227 DCHECK(instruction->GetUses().empty());
1228 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001229 RemoveAsUser(instruction);
1230 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001231}
1232
David Brazdil1abb4192015-02-17 18:33:36 +00001233void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001234 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001235 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001236}
1237
David Brazdil1abb4192015-02-17 18:33:36 +00001238void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1239 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001240}
1241
David Brazdilc7508e92015-04-27 13:28:57 +01001242void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1243 if (instruction->IsPhi()) {
1244 RemovePhi(instruction->AsPhi(), ensure_safety);
1245 } else {
1246 RemoveInstruction(instruction, ensure_safety);
1247 }
1248}
1249
Vladimir Marko69d310e2017-10-09 14:12:23 +01001250void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001251 for (size_t i = 0; i < locals.size(); i++) {
1252 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001253 SetRawEnvAt(i, instruction);
1254 if (instruction != nullptr) {
1255 instruction->AddEnvUseAt(this, i);
1256 }
1257 }
1258}
1259
David Brazdiled596192015-01-23 10:39:45 +00001260void HEnvironment::CopyFrom(HEnvironment* env) {
1261 for (size_t i = 0; i < env->Size(); i++) {
1262 HInstruction* instruction = env->GetInstructionAt(i);
1263 SetRawEnvAt(i, instruction);
1264 if (instruction != nullptr) {
1265 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001266 }
David Brazdiled596192015-01-23 10:39:45 +00001267 }
1268}
1269
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001270void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1271 HBasicBlock* loop_header) {
1272 DCHECK(loop_header->IsLoopHeader());
1273 for (size_t i = 0; i < env->Size(); i++) {
1274 HInstruction* instruction = env->GetInstructionAt(i);
1275 SetRawEnvAt(i, instruction);
1276 if (instruction == nullptr) {
1277 continue;
1278 }
1279 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1280 // At the end of the loop pre-header, the corresponding value for instruction
1281 // is the first input of the phi.
1282 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001283 SetRawEnvAt(i, initial);
1284 initial->AddEnvUseAt(this, i);
1285 } else {
1286 instruction->AddEnvUseAt(this, i);
1287 }
1288 }
1289}
1290
David Brazdil1abb4192015-02-17 18:33:36 +00001291void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001292 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1293 HInstruction* user = env_use.GetInstruction();
1294 auto before_env_use_node = env_use.GetBeforeUseNode();
1295 user->env_uses_.erase_after(before_env_use_node);
1296 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001297}
1298
Artem Serovca210e32017-12-15 13:43:20 +00001299void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1300 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1301 HInstruction* orig_instr = env_use_record.GetInstruction();
1302
1303 DCHECK(orig_instr != replacement);
1304
1305 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1306 // Note: fixup_end remains valid across splice_after().
1307 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1308 : ++replacement->env_uses_.begin();
1309 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1310 env_use_record.GetInstruction()->env_uses_,
1311 before_use_node);
1312 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1313 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1314}
1315
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001316std::ostream& HInstruction::Dump(std::ostream& os, bool dump_args) {
1317 HGraph* graph = GetBlock()->GetGraph();
1318 HGraphVisualizer::DumpInstruction(&os, graph, this);
1319 if (dump_args) {
1320 // Allocate memory from local ScopedArenaAllocator.
1321 ScopedArenaAllocator allocator(graph->GetArenaStack());
1322 // Instructions that we already visited. We print each instruction only once.
1323 ArenaBitVector visited(
1324 &allocator, graph->GetCurrentInstructionId(), /* expandable= */ false, kArenaAllocMisc);
1325 visited.ClearAllBits();
1326 visited.SetBit(GetId());
1327 // Keep a queue of instructions with their indentations.
1328 ScopedArenaDeque<std::pair<HInstruction*, size_t>> queue(allocator.Adapter(kArenaAllocMisc));
1329 auto add_args = [&queue](HInstruction* instruction, size_t indentation) {
1330 for (HInstruction* arg : ReverseRange(instruction->GetInputs())) {
1331 queue.emplace_front(arg, indentation);
1332 }
1333 };
1334 add_args(this, /*indentation=*/ 1u);
1335 while (!queue.empty()) {
1336 HInstruction* instruction;
1337 size_t indentation;
1338 std::tie(instruction, indentation) = queue.front();
1339 queue.pop_front();
1340 if (!visited.IsBitSet(instruction->GetId())) {
1341 visited.SetBit(instruction->GetId());
1342 os << '\n';
1343 for (size_t i = 0; i != indentation; ++i) {
1344 os << " ";
1345 }
1346 HGraphVisualizer::DumpInstruction(&os, graph, instruction);
1347 add_args(instruction, indentation + 1u);
1348 }
1349 }
1350 }
1351 return os;
1352}
1353
Calin Juravle77520bc2015-01-12 18:45:46 +00001354HInstruction* HInstruction::GetNextDisregardingMoves() const {
1355 HInstruction* next = GetNext();
1356 while (next != nullptr && next->IsParallelMove()) {
1357 next = next->GetNext();
1358 }
1359 return next;
1360}
1361
1362HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1363 HInstruction* previous = GetPrevious();
1364 while (previous != nullptr && previous->IsParallelMove()) {
1365 previous = previous->GetPrevious();
1366 }
1367 return previous;
1368}
1369
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001370void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001371 if (first_instruction_ == nullptr) {
1372 DCHECK(last_instruction_ == nullptr);
1373 first_instruction_ = last_instruction_ = instruction;
1374 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001375 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001376 last_instruction_->next_ = instruction;
1377 instruction->previous_ = last_instruction_;
1378 last_instruction_ = instruction;
1379 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001380}
1381
David Brazdilc3d743f2015-04-22 13:40:50 +01001382void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1383 DCHECK(Contains(cursor));
1384 if (cursor == first_instruction_) {
1385 cursor->previous_ = instruction;
1386 instruction->next_ = cursor;
1387 first_instruction_ = instruction;
1388 } else {
1389 instruction->previous_ = cursor->previous_;
1390 instruction->next_ = cursor;
1391 cursor->previous_ = instruction;
1392 instruction->previous_->next_ = instruction;
1393 }
1394}
1395
1396void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1397 DCHECK(Contains(cursor));
1398 if (cursor == last_instruction_) {
1399 cursor->next_ = instruction;
1400 instruction->previous_ = cursor;
1401 last_instruction_ = instruction;
1402 } else {
1403 instruction->next_ = cursor->next_;
1404 instruction->previous_ = cursor;
1405 cursor->next_ = instruction;
1406 instruction->next_->previous_ = instruction;
1407 }
1408}
1409
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001410void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1411 if (instruction->previous_ != nullptr) {
1412 instruction->previous_->next_ = instruction->next_;
1413 }
1414 if (instruction->next_ != nullptr) {
1415 instruction->next_->previous_ = instruction->previous_;
1416 }
1417 if (instruction == first_instruction_) {
1418 first_instruction_ = instruction->next_;
1419 }
1420 if (instruction == last_instruction_) {
1421 last_instruction_ = instruction->previous_;
1422 }
1423}
1424
Roland Levillain6b469232014-09-25 10:10:38 +01001425bool HInstructionList::Contains(HInstruction* instruction) const {
1426 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1427 if (it.Current() == instruction) {
1428 return true;
1429 }
1430 }
1431 return false;
1432}
1433
Roland Levillainccc07a92014-09-16 14:48:16 +01001434bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1435 const HInstruction* instruction2) const {
1436 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1437 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1438 if (it.Current() == instruction1) {
1439 return true;
1440 }
1441 if (it.Current() == instruction2) {
1442 return false;
1443 }
1444 }
1445 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001446 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001447}
1448
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001449bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001450 if (other_instruction == this) {
1451 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001452 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001453 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001454 HBasicBlock* block = GetBlock();
1455 HBasicBlock* other_block = other_instruction->GetBlock();
1456 if (block != other_block) {
1457 return GetBlock()->Dominates(other_instruction->GetBlock());
1458 } else {
1459 // If both instructions are in the same block, ensure this
1460 // instruction comes before `other_instruction`.
1461 if (IsPhi()) {
1462 if (!other_instruction->IsPhi()) {
1463 // Phis appear before non phi-instructions so this instruction
1464 // dominates `other_instruction`.
1465 return true;
1466 } else {
1467 // There is no order among phis.
1468 LOG(FATAL) << "There is no dominance between phis of a same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001469 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001470 }
1471 } else {
1472 // `this` is not a phi.
1473 if (other_instruction->IsPhi()) {
1474 // Phis appear before non phi-instructions so this instruction
1475 // does not dominate `other_instruction`.
1476 return false;
1477 } else {
1478 // Check whether this instruction comes before
1479 // `other_instruction` in the instruction list.
1480 return block->GetInstructions().FoundBefore(this, other_instruction);
1481 }
1482 }
1483 }
1484}
1485
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001486void HInstruction::RemoveEnvironment() {
1487 RemoveEnvironmentUses(this);
1488 environment_ = nullptr;
1489}
1490
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001491void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001492 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001493 // Note: fixup_end remains valid across splice_after().
1494 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1495 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1496 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001497
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001498 // Note: env_fixup_end remains valid across splice_after().
1499 auto env_fixup_end =
1500 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1501 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1502 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001503
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001504 DCHECK(uses_.empty());
1505 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001506}
1507
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001508void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001509 const HUseList<HInstruction*>& uses = GetUses();
1510 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1511 HInstruction* user = it->GetUser();
1512 size_t index = it->GetIndex();
1513 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1514 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001515 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001516 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001517 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1518 // If the input flows from a block dominated by `dominator`, we can replace it.
1519 // We do not perform this for catch phis as we don't have control flow support
1520 // for their inputs.
1521 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1522 HBasicBlock* predecessor = predecessors[index];
1523 if (dominator->GetBlock()->Dominates(predecessor)) {
1524 user->ReplaceInput(replacement, index);
1525 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001526 }
1527 }
1528}
1529
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001530void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1531 const HUseList<HEnvironment*>& uses = GetEnvUses();
1532 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1533 HEnvironment* user = it->GetUser();
1534 size_t index = it->GetIndex();
1535 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1536 ++it;
1537 if (dominator->StrictlyDominates(user->GetHolder())) {
1538 user->ReplaceInput(replacement, index);
1539 }
1540 }
1541}
1542
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001543void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001544 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001545 if (input_use.GetInstruction() == replacement) {
1546 // Nothing to do.
1547 return;
1548 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001549 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001550 // Note: fixup_end remains valid across splice_after().
1551 auto fixup_end =
1552 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1553 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1554 input_use.GetInstruction()->uses_,
1555 before_use_node);
1556 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1557 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001558}
1559
Nicolas Geoffray39468442014-09-02 15:17:15 +01001560size_t HInstruction::EnvironmentSize() const {
1561 return HasEnvironment() ? environment_->Size() : 0;
1562}
1563
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001564void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001565 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001566 inputs_.push_back(HUserRecord<HInstruction*>(input));
1567 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001568}
1569
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001570void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1571 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1572 input->AddUseAt(this, index);
1573 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1574 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1575 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1576 inputs_[i].GetUseNode()->SetIndex(i);
1577 }
1578}
1579
1580void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001581 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001582 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001583 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1584 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1585 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1586 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001587 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001588}
1589
Igor Murashkind01745e2017-04-05 16:40:31 -07001590void HVariableInputSizeInstruction::RemoveAllInputs() {
1591 RemoveAsUserOfAllInputs();
1592 DCHECK(!HasNonEnvironmentUses());
1593
1594 inputs_.clear();
1595 DCHECK_EQ(0u, InputCount());
1596}
1597
Igor Murashkin6ef45672017-08-08 13:59:55 -07001598size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001599 DCHECK(instruction->GetBlock() != nullptr);
1600 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001602
Igor Murashkin6ef45672017-08-08 13:59:55 -07001603 // Return how many instructions were removed for statistic purposes.
1604 size_t remove_count = 0;
1605
Igor Murashkind01745e2017-04-05 16:40:31 -07001606 // Efficient implementation that simultaneously (in one pass):
1607 // * Scans the uses list for all constructor fences.
1608 // * Deletes that constructor fence from the uses list of `instruction`.
1609 // * Deletes `instruction` from the constructor fence's inputs.
1610 // * Deletes the constructor fence if it now has 0 inputs.
1611
1612 const HUseList<HInstruction*>& uses = instruction->GetUses();
1613 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1614 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1615 const HUseListNode<HInstruction*>& use_node = *it;
1616 HInstruction* const use_instruction = use_node.GetUser();
1617
1618 // Advance the iterator immediately once we fetch the use_node.
1619 // Warning: If the input is removed, the current iterator becomes invalid.
1620 ++it;
1621
1622 if (use_instruction->IsConstructorFence()) {
1623 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1624 size_t input_index = use_node.GetIndex();
1625
1626 // Process the candidate instruction for removal
1627 // from the graph.
1628
1629 // Constructor fence instructions are never
1630 // used by other instructions.
1631 //
1632 // If we wanted to make this more generic, it
1633 // could be a runtime if statement.
1634 DCHECK(!ctor_fence->HasUses());
1635
1636 // A constructor fence's return type is "kPrimVoid"
1637 // and therefore it can't have any environment uses.
1638 DCHECK(!ctor_fence->HasEnvironmentUses());
1639
1640 // Remove the inputs first, otherwise removing the instruction
1641 // will try to remove its uses while we are already removing uses
1642 // and this operation will fail.
1643 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1644
1645 // Removing the input will also remove the `use_node`.
1646 // (Do not look at `use_node` after this, it will be a dangling reference).
1647 ctor_fence->RemoveInputAt(input_index);
1648
1649 // Once all inputs are removed, the fence is considered dead and
1650 // is removed.
1651 if (ctor_fence->InputCount() == 0u) {
1652 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001653 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001654 }
1655 }
1656 }
1657
1658 if (kIsDebugBuild) {
1659 // Post-condition checks:
1660 // * None of the uses of `instruction` are a constructor fence.
1661 // * The `instruction` itself did not get removed from a block.
1662 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1663 CHECK(!use_node.GetUser()->IsConstructorFence());
1664 }
1665 CHECK(instruction->GetBlock() != nullptr);
1666 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001667
1668 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001669}
1670
Igor Murashkindd018df2017-08-09 10:38:31 -07001671void HConstructorFence::Merge(HConstructorFence* other) {
1672 // Do not delete yourself from the graph.
1673 DCHECK(this != other);
1674 // Don't try to merge with an instruction not associated with a block.
1675 DCHECK(other->GetBlock() != nullptr);
1676 // A constructor fence's return type is "kPrimVoid"
1677 // and therefore it cannot have any environment uses.
1678 DCHECK(!other->HasEnvironmentUses());
1679
1680 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1681 // Check if `haystack` has `needle` as any of its inputs.
1682 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1683 if (haystack->InputAt(input_count) == needle) {
1684 return true;
1685 }
1686 }
1687 return false;
1688 };
1689
1690 // Add any inputs from `other` into `this` if it wasn't already an input.
1691 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1692 HInstruction* other_input = other->InputAt(input_count);
1693 if (!has_input(this, other_input)) {
1694 AddInput(other_input);
1695 }
1696 }
1697
1698 other->GetBlock()->RemoveInstruction(other);
1699}
1700
1701HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001702 HInstruction* new_instance_inst = GetPrevious();
1703 // Check if the immediately preceding instruction is a new-instance/new-array.
1704 // Otherwise this fence is for protecting final fields.
1705 if (new_instance_inst != nullptr &&
1706 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001707 if (ignore_inputs) {
1708 // If inputs are ignored, simply check if the predecessor is
1709 // *any* HNewInstance/HNewArray.
1710 //
1711 // Inputs are normally only ignored for prepare_for_register_allocation,
1712 // at which point *any* prior HNewInstance/Array can be considered
1713 // associated.
1714 return new_instance_inst;
1715 } else {
1716 // Normal case: There must be exactly 1 input and the previous instruction
1717 // must be that input.
1718 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1719 return new_instance_inst;
1720 }
1721 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001722 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001723 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001724}
1725
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001726#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001727void H##name::Accept(HGraphVisitor* visitor) { \
1728 visitor->Visit##name(this); \
1729}
1730
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001731FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001732
1733#undef DEFINE_ACCEPT
1734
1735void HGraphVisitor::VisitInsertionOrder() {
Alex Light210a78d2020-11-30 16:58:05 -08001736 for (HBasicBlock* block : graph_->GetActiveBlocks()) {
1737 VisitBasicBlock(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001738 }
1739}
1740
Roland Levillain633021e2014-10-01 14:12:25 +01001741void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001742 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1743 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001744 }
1745}
1746
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001747void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001748 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001749 it.Current()->Accept(this);
1750 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001751 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001752 it.Current()->Accept(this);
1753 }
1754}
1755
Mark Mendelle82549b2015-05-06 10:55:34 -04001756HConstant* HTypeConversion::TryStaticEvaluation() const {
1757 HGraph* graph = GetBlock()->GetGraph();
1758 if (GetInput()->IsIntConstant()) {
1759 int32_t value = GetInput()->AsIntConstant()->GetValue();
1760 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001761 case DataType::Type::kInt8:
1762 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1763 case DataType::Type::kUint8:
1764 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1765 case DataType::Type::kInt16:
1766 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1767 case DataType::Type::kUint16:
1768 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001769 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001770 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001771 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001772 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001773 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001774 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001775 default:
1776 return nullptr;
1777 }
1778 } else if (GetInput()->IsLongConstant()) {
1779 int64_t value = GetInput()->AsLongConstant()->GetValue();
1780 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001781 case DataType::Type::kInt8:
1782 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1783 case DataType::Type::kUint8:
1784 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1785 case DataType::Type::kInt16:
1786 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1787 case DataType::Type::kUint16:
1788 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001789 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001790 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001791 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001792 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001793 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001794 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001795 default:
1796 return nullptr;
1797 }
1798 } else if (GetInput()->IsFloatConstant()) {
1799 float value = GetInput()->AsFloatConstant()->GetValue();
1800 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001801 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001802 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001803 return graph->GetIntConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001804 if (value >= static_cast<float>(kPrimIntMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001805 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001806 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001807 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1808 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001809 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001810 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001811 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001812 if (value >= static_cast<float>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001813 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001814 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001815 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1816 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001817 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001818 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001819 default:
1820 return nullptr;
1821 }
1822 } else if (GetInput()->IsDoubleConstant()) {
1823 double value = GetInput()->AsDoubleConstant()->GetValue();
1824 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001825 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001826 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001827 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001828 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001829 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001830 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001831 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1832 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001833 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001834 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001835 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001836 if (value >= static_cast<double>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001837 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001838 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001839 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1840 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001841 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001842 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001843 default:
1844 return nullptr;
1845 }
1846 }
1847 return nullptr;
1848}
1849
Roland Levillain9240d6a2014-10-20 16:47:04 +01001850HConstant* HUnaryOperation::TryStaticEvaluation() const {
1851 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001852 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001853 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001854 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001855 } else if (kEnableFloatingPointStaticEvaluation) {
1856 if (GetInput()->IsFloatConstant()) {
1857 return Evaluate(GetInput()->AsFloatConstant());
1858 } else if (GetInput()->IsDoubleConstant()) {
1859 return Evaluate(GetInput()->AsDoubleConstant());
1860 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001861 }
1862 return nullptr;
1863}
1864
1865HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001866 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1867 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001868 } else if (GetLeft()->IsLongConstant()) {
1869 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001870 // The binop(long, int) case is only valid for shifts and rotations.
1871 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001872 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1873 } else if (GetRight()->IsLongConstant()) {
1874 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001875 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001876 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001877 // The binop(null, null) case is only valid for equal and not-equal conditions.
1878 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001879 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001880 } else if (kEnableFloatingPointStaticEvaluation) {
1881 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1882 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1883 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1884 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1885 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001886 }
1887 return nullptr;
1888}
Dave Allison20dfc792014-06-16 20:44:29 -07001889
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001890HConstant* HBinaryOperation::GetConstantRight() const {
1891 if (GetRight()->IsConstant()) {
1892 return GetRight()->AsConstant();
1893 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1894 return GetLeft()->AsConstant();
1895 } else {
1896 return nullptr;
1897 }
1898}
1899
1900// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001901// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001902HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1903 HInstruction* most_constant_right = GetConstantRight();
1904 if (most_constant_right == nullptr) {
1905 return nullptr;
1906 } else if (most_constant_right == GetLeft()) {
1907 return GetRight();
1908 } else {
1909 return GetLeft();
1910 }
1911}
1912
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001913std::ostream& operator<<(std::ostream& os, ComparisonBias rhs) {
1914 // TODO: Replace with auto-generated operator<<.
Roland Levillain31dd3d62016-02-16 12:21:02 +00001915 switch (rhs) {
1916 case ComparisonBias::kNoBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001917 return os << "none";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001918 case ComparisonBias::kGtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001919 return os << "gt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001920 case ComparisonBias::kLtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001921 return os << "lt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001922 default:
1923 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1924 UNREACHABLE();
1925 }
1926}
1927
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001928bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1929 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001930}
1931
Vladimir Marko372f10e2016-05-17 16:30:10 +01001932bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001933 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001934 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001935 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001936 HConstInputsRef inputs = GetInputs();
1937 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001938 if (inputs.size() != other_inputs.size()) return false;
1939 for (size_t i = 0; i != inputs.size(); ++i) {
1940 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001941 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001942
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001943 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001944 return true;
1945}
1946
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001947std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001948#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1949 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01001950 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001951 default:
1952 os << "Unknown instruction kind " << static_cast<int>(rhs);
1953 break;
1954 }
1955#undef DECLARE_CASE
1956 return os;
1957}
1958
Alex Lightdc281e72021-01-06 12:35:31 -08001959std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs) {
1960 // TODO Really this should be const but that would require const-ifying
1961 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
1962 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ false);
1963}
1964
1965std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs) {
1966 // TODO Really this should be const but that would require const-ifying
1967 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
1968 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ true);
1969}
1970
1971std::ostream& operator<<(std::ostream& os, const HInstruction& rhs) {
1972 return os << rhs.DumpWithoutArgs();
1973}
1974
1975std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst) {
1976 os << "Instructions[";
1977 bool first = true;
1978 for (const auto& hi : lst) {
1979 if (!first) {
1980 os << ", ";
1981 }
1982 first = false;
1983 os << hi.GetUser()->DebugName() << "[id: " << hi.GetUser()->GetId()
1984 << ", blk: " << hi.GetUser()->GetBlock()->GetBlockId() << "]@" << hi.GetIndex();
1985 }
1986 os << "]";
1987 return os;
1988}
1989
1990std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst) {
1991 os << "Environments[";
1992 bool first = true;
1993 for (const auto& hi : lst) {
1994 if (!first) {
1995 os << ", ";
1996 }
1997 first = false;
1998 os << *hi.GetUser()->GetHolder() << "@" << hi.GetIndex();
1999 }
2000 os << "]";
2001 return os;
2002}
2003
2004std::ostream& HGraph::Dump(std::ostream& os,
2005 std::optional<std::reference_wrapper<const BlockNamer>> namer) {
2006 HGraphVisualizer vis(&os, this, nullptr, namer);
2007 vis.DumpGraphDebug();
2008 return os;
2009}
2010
Alexandre Rames22aa54b2016-10-18 09:32:29 +01002011void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
2012 if (do_checks) {
2013 DCHECK(!IsPhi());
2014 DCHECK(!IsControlFlow());
2015 DCHECK(CanBeMoved() ||
2016 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
2017 IsShouldDeoptimizeFlag());
2018 DCHECK(!cursor->IsPhi());
2019 }
David Brazdild6c205e2016-06-07 14:20:52 +01002020
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002021 next_->previous_ = previous_;
2022 if (previous_ != nullptr) {
2023 previous_->next_ = next_;
2024 }
2025 if (block_->instructions_.first_instruction_ == this) {
2026 block_->instructions_.first_instruction_ = next_;
2027 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002028 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002029
2030 previous_ = cursor->previous_;
2031 if (previous_ != nullptr) {
2032 previous_->next_ = this;
2033 }
2034 next_ = cursor;
2035 cursor->previous_ = this;
2036 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002037
2038 if (block_->instructions_.first_instruction_ == cursor) {
2039 block_->instructions_.first_instruction_ = this;
2040 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002041}
2042
Vladimir Markofb337ea2015-11-25 15:25:10 +00002043void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
2044 DCHECK(!CanThrow());
2045 DCHECK(!HasSideEffects());
2046 DCHECK(!HasEnvironmentUses());
2047 DCHECK(HasNonEnvironmentUses());
2048 DCHECK(!IsPhi()); // Makes no sense for Phi.
2049 DCHECK_EQ(InputCount(), 0u);
2050
2051 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01002052 auto uses_it = GetUses().begin();
2053 auto uses_end = GetUses().end();
2054 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
2055 ++uses_it;
2056 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
2057 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00002058 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002059 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00002060 // This instruction has uses in two or more blocks. Find the common dominator.
2061 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01002062 for (; uses_it != uses_end; ++uses_it) {
2063 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00002064 }
2065 target_block = finder.Get();
2066 DCHECK(target_block != nullptr);
2067 }
2068 // Move to the first dominator not in a loop.
2069 while (target_block->IsInLoop()) {
2070 target_block = target_block->GetDominator();
2071 DCHECK(target_block != nullptr);
2072 }
2073
2074 // Find insertion position.
2075 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01002076 for (const HUseListNode<HInstruction*>& use : GetUses()) {
2077 if (use.GetUser()->GetBlock() == target_block &&
2078 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
2079 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00002080 }
2081 }
2082 if (insert_pos == nullptr) {
2083 // No user in `target_block`, insert before the control flow instruction.
2084 insert_pos = target_block->GetLastInstruction();
2085 DCHECK(insert_pos->IsControlFlow());
2086 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
2087 if (insert_pos->IsIf()) {
2088 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
2089 if (if_input == insert_pos->GetPrevious()) {
2090 insert_pos = if_input;
2091 }
2092 }
2093 }
2094 MoveBefore(insert_pos);
2095}
2096
David Brazdilfc6a86a2015-06-26 10:33:45 +00002097HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00002098 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00002099 DCHECK_EQ(cursor->GetBlock(), this);
2100
Vladimir Markoca6fff82017-10-03 14:49:14 +01002101 HBasicBlock* new_block =
2102 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002103 new_block->instructions_.first_instruction_ = cursor;
2104 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2105 instructions_.last_instruction_ = cursor->previous_;
2106 if (cursor->previous_ == nullptr) {
2107 instructions_.first_instruction_ = nullptr;
2108 } else {
2109 cursor->previous_->next_ = nullptr;
2110 cursor->previous_ = nullptr;
2111 }
2112
2113 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002114 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00002115
Vladimir Marko60584552015-09-03 13:35:12 +00002116 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002117 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00002118 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002119 new_block->successors_.swap(successors_);
2120 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002121 AddSuccessor(new_block);
2122
David Brazdil56e1acc2015-06-30 15:41:36 +01002123 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00002124 return new_block;
2125}
2126
David Brazdild7558da2015-09-22 13:04:14 +01002127HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00002128 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01002129 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
2130
Vladimir Markoca6fff82017-10-03 14:49:14 +01002131 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01002132
2133 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01002134 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
2135 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002136 new_block->predecessors_.swap(predecessors_);
2137 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01002138 AddPredecessor(new_block);
2139
2140 GetGraph()->AddBlock(new_block);
2141 return new_block;
2142}
2143
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002144HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
2145 DCHECK_EQ(cursor->GetBlock(), this);
2146
Vladimir Markoca6fff82017-10-03 14:49:14 +01002147 HBasicBlock* new_block =
2148 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002149 new_block->instructions_.first_instruction_ = cursor;
2150 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2151 instructions_.last_instruction_ = cursor->previous_;
2152 if (cursor->previous_ == nullptr) {
2153 instructions_.first_instruction_ = nullptr;
2154 } else {
2155 cursor->previous_->next_ = nullptr;
2156 cursor->previous_ = nullptr;
2157 }
2158
2159 new_block->instructions_.SetBlockOfInstructions(new_block);
2160
2161 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002162 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2163 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002164 new_block->successors_.swap(successors_);
2165 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002166
2167 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2168 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002169 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002170 new_block->dominated_blocks_.swap(dominated_blocks_);
2171 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002172 return new_block;
2173}
2174
2175HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002176 DCHECK(!cursor->IsControlFlow());
2177 DCHECK_NE(instructions_.last_instruction_, cursor);
2178 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002179
Vladimir Markoca6fff82017-10-03 14:49:14 +01002180 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002181 new_block->instructions_.first_instruction_ = cursor->GetNext();
2182 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2183 cursor->next_->previous_ = nullptr;
2184 cursor->next_ = nullptr;
2185 instructions_.last_instruction_ = cursor;
2186
2187 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002188 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002189 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002190 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002191 new_block->successors_.swap(successors_);
2192 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002193
Vladimir Marko60584552015-09-03 13:35:12 +00002194 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002195 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002196 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002197 new_block->dominated_blocks_.swap(dominated_blocks_);
2198 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002199 return new_block;
2200}
2201
David Brazdilec16f792015-08-19 15:04:01 +01002202const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01002203 if (EndsWithTryBoundary()) {
2204 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
2205 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01002206 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01002207 return try_boundary;
2208 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002209 DCHECK(IsTryBlock());
2210 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01002211 return nullptr;
2212 }
David Brazdilec16f792015-08-19 15:04:01 +01002213 } else if (IsTryBlock()) {
2214 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01002215 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002216 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01002217 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00002218}
2219
Aart Bik75ff2c92018-04-21 01:28:11 +00002220bool HBasicBlock::HasThrowingInstructions() const {
2221 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2222 if (it.Current()->CanThrow()) {
2223 return true;
2224 }
2225 }
2226 return false;
2227}
2228
David Brazdilfc6a86a2015-06-26 10:33:45 +00002229static bool HasOnlyOneInstruction(const HBasicBlock& block) {
2230 return block.GetPhis().IsEmpty()
2231 && !block.GetInstructions().IsEmpty()
2232 && block.GetFirstInstruction() == block.GetLastInstruction();
2233}
2234
David Brazdil46e2a392015-03-16 17:31:52 +00002235bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00002236 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
2237}
2238
Mads Ager16e52892017-07-14 13:11:37 +02002239bool HBasicBlock::IsSingleReturn() const {
2240 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
2241}
2242
Mingyao Yang46721ef2017-10-05 14:45:17 -07002243bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
2244 return (GetFirstInstruction() == GetLastInstruction()) &&
2245 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2246}
2247
David Brazdilfc6a86a2015-06-26 10:33:45 +00002248bool HBasicBlock::IsSingleTryBoundary() const {
2249 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00002250}
2251
David Brazdil8d5b8b22015-03-24 10:51:52 +00002252bool HBasicBlock::EndsWithControlFlowInstruction() const {
2253 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
2254}
2255
Aart Bik4dc09e72018-05-11 14:40:31 -07002256bool HBasicBlock::EndsWithReturn() const {
2257 return !GetInstructions().IsEmpty() &&
2258 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2259}
2260
David Brazdilb2bd1c52015-03-25 11:17:37 +00002261bool HBasicBlock::EndsWithIf() const {
2262 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2263}
2264
David Brazdilffee3d32015-07-06 11:48:53 +01002265bool HBasicBlock::EndsWithTryBoundary() const {
2266 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2267}
2268
David Brazdilb2bd1c52015-03-25 11:17:37 +00002269bool HBasicBlock::HasSinglePhi() const {
2270 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2271}
2272
David Brazdild26a4112015-11-10 11:07:31 +00002273ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2274 if (EndsWithTryBoundary()) {
2275 // The normal-flow successor of HTryBoundary is always stored at index zero.
2276 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2277 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2278 } else {
2279 // All successors of blocks not ending with TryBoundary are normal.
2280 return ArrayRef<HBasicBlock* const>(successors_);
2281 }
2282}
2283
2284ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2285 if (EndsWithTryBoundary()) {
2286 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2287 } else {
2288 // Blocks not ending with TryBoundary do not have exceptional successors.
2289 return ArrayRef<HBasicBlock* const>();
2290 }
2291}
2292
David Brazdilffee3d32015-07-06 11:48:53 +01002293bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002294 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2295 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2296
2297 size_t length = handlers1.size();
2298 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002299 return false;
2300 }
2301
David Brazdilb618ade2015-07-29 10:31:29 +01002302 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002303 for (size_t i = 0; i < length; ++i) {
2304 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002305 return false;
2306 }
2307 }
2308 return true;
2309}
2310
David Brazdil2d7352b2015-04-20 14:52:42 +01002311size_t HInstructionList::CountSize() const {
2312 size_t size = 0;
2313 HInstruction* current = first_instruction_;
2314 for (; current != nullptr; current = current->GetNext()) {
2315 size++;
2316 }
2317 return size;
2318}
2319
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002320void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2321 for (HInstruction* current = first_instruction_;
2322 current != nullptr;
2323 current = current->GetNext()) {
2324 current->SetBlock(block);
2325 }
2326}
2327
2328void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2329 DCHECK(Contains(cursor));
2330 if (!instruction_list.IsEmpty()) {
2331 if (cursor == last_instruction_) {
2332 last_instruction_ = instruction_list.last_instruction_;
2333 } else {
2334 cursor->next_->previous_ = instruction_list.last_instruction_;
2335 }
2336 instruction_list.last_instruction_->next_ = cursor->next_;
2337 cursor->next_ = instruction_list.first_instruction_;
2338 instruction_list.first_instruction_->previous_ = cursor;
2339 }
2340}
2341
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002342void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2343 DCHECK(Contains(cursor));
2344 if (!instruction_list.IsEmpty()) {
2345 if (cursor == first_instruction_) {
2346 first_instruction_ = instruction_list.first_instruction_;
2347 } else {
2348 cursor->previous_->next_ = instruction_list.first_instruction_;
2349 }
2350 instruction_list.last_instruction_->next_ = cursor;
2351 instruction_list.first_instruction_->previous_ = cursor->previous_;
2352 cursor->previous_ = instruction_list.last_instruction_;
2353 }
2354}
2355
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002356void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002357 if (IsEmpty()) {
2358 first_instruction_ = instruction_list.first_instruction_;
2359 last_instruction_ = instruction_list.last_instruction_;
2360 } else {
2361 AddAfter(last_instruction_, instruction_list);
2362 }
2363}
2364
David Brazdil04ff4e82015-12-10 13:54:52 +00002365// Should be called on instructions in a dead block in post order. This method
2366// assumes `insn` has been removed from all users with the exception of catch
2367// phis because of missing exceptional edges in the graph. It removes the
2368// instruction from catch phi uses, together with inputs of other catch phis in
2369// the catch block at the same index, as these must be dead too.
2370static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2371 DCHECK(!insn->HasEnvironmentUses());
2372 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002373 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2374 size_t use_index = use.GetIndex();
2375 HBasicBlock* user_block = use.GetUser()->GetBlock();
2376 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002377 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2378 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2379 }
2380 }
2381}
2382
David Brazdil2d7352b2015-04-20 14:52:42 +01002383void HBasicBlock::DisconnectAndDelete() {
2384 // Dominators must be removed after all the blocks they dominate. This way
2385 // a loop header is removed last, a requirement for correct loop information
2386 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002387 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002388
David Brazdil9eeebf62016-03-24 11:18:15 +00002389 // The following steps gradually remove the block from all its dependants in
2390 // post order (b/27683071).
2391
2392 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2393 // We need to do this before step (4) which destroys the predecessor list.
2394 HBasicBlock* loop_update_start = this;
2395 if (IsLoopHeader()) {
2396 HLoopInformation* loop_info = GetLoopInformation();
2397 // All other blocks in this loop should have been removed because the header
2398 // was their dominator.
2399 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2400 DCHECK(!loop_info->IsIrreducible());
2401 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2402 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2403 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002404 }
2405
David Brazdil9eeebf62016-03-24 11:18:15 +00002406 // (2) Disconnect the block from its successors and update their phis.
2407 for (HBasicBlock* successor : successors_) {
2408 // Delete this block from the list of predecessors.
2409 size_t this_index = successor->GetPredecessorIndexOf(this);
2410 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2411
2412 // Check that `successor` has other predecessors, otherwise `this` is the
2413 // dominator of `successor` which violates the order DCHECKed at the top.
2414 DCHECK(!successor->predecessors_.empty());
2415
2416 // Remove this block's entries in the successor's phis. Skip exceptional
2417 // successors because catch phi inputs do not correspond to predecessor
2418 // blocks but throwing instructions. The inputs of the catch phis will be
2419 // updated in step (3).
2420 if (!successor->IsCatchBlock()) {
2421 if (successor->predecessors_.size() == 1u) {
2422 // The successor has just one predecessor left. Replace phis with the only
2423 // remaining input.
2424 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2425 HPhi* phi = phi_it.Current()->AsPhi();
2426 phi->ReplaceWith(phi->InputAt(1 - this_index));
2427 successor->RemovePhi(phi);
2428 }
2429 } else {
2430 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2431 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2432 }
2433 }
2434 }
2435 }
2436 successors_.clear();
2437
2438 // (3) Remove instructions and phis. Instructions should have no remaining uses
2439 // except in catch phis. If an instruction is used by a catch phi at `index`,
2440 // remove `index`-th input of all phis in the catch block since they are
2441 // guaranteed dead. Note that we may miss dead inputs this way but the
2442 // graph will always remain consistent.
2443 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2444 HInstruction* insn = it.Current();
2445 RemoveUsesOfDeadInstruction(insn);
2446 RemoveInstruction(insn);
2447 }
2448 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2449 HPhi* insn = it.Current()->AsPhi();
2450 RemoveUsesOfDeadInstruction(insn);
2451 RemovePhi(insn);
2452 }
2453
2454 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002455 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002456 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002457 // We should not see any back edges as they would have been removed by step (3).
2458 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2459
David Brazdil2d7352b2015-04-20 14:52:42 +01002460 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002461 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2462 // This block is the only normal-flow successor of the TryBoundary which
2463 // makes `predecessor` dead. Since DCE removes blocks in post order,
2464 // exception handlers of this TryBoundary were already visited and any
2465 // remaining handlers therefore must be live. We remove `predecessor` from
2466 // their list of predecessors.
2467 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2468 while (predecessor->GetSuccessors().size() > 1) {
2469 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2470 DCHECK(handler->IsCatchBlock());
2471 predecessor->RemoveSuccessor(handler);
2472 handler->RemovePredecessor(predecessor);
2473 }
2474 }
2475
David Brazdil2d7352b2015-04-20 14:52:42 +01002476 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002477 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2478 if (num_pred_successors == 1u) {
2479 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002480 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2481 // successor. Replace those with a HGoto.
2482 DCHECK(last_instruction->IsIf() ||
2483 last_instruction->IsPackedSwitch() ||
2484 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002485 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002486 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002487 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002488 // The predecessor has no remaining successors and therefore must be dead.
2489 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002490 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002491 predecessor->RemoveInstruction(last_instruction);
2492 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002493 // There are multiple successors left. The removed block might be a successor
2494 // of a PackedSwitch which will be completely removed (perhaps replaced with
2495 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2496 // case, leave `last_instruction` as is for now.
2497 DCHECK(last_instruction->IsPackedSwitch() ||
2498 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002499 }
David Brazdil46e2a392015-03-16 17:31:52 +00002500 }
Vladimir Marko60584552015-09-03 13:35:12 +00002501 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002502
David Brazdil9eeebf62016-03-24 11:18:15 +00002503 // (5) Remove the block from all loops it is included in. Skip the inner-most
2504 // loop if this is the loop header (see definition of `loop_update_start`)
2505 // because the loop header's predecessor list has been destroyed in step (4).
2506 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2507 HLoopInformation* loop_info = it.Current();
2508 loop_info->Remove(this);
2509 if (loop_info->IsBackEdge(*this)) {
2510 // If this was the last back edge of the loop, we deliberately leave the
2511 // loop in an inconsistent state and will fail GraphChecker unless the
2512 // entire loop is removed during the pass.
2513 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002514 }
2515 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002516
David Brazdil9eeebf62016-03-24 11:18:15 +00002517 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002518 dominator_->RemoveDominatedBlock(this);
2519 SetDominator(nullptr);
2520
David Brazdil9eeebf62016-03-24 11:18:15 +00002521 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002522 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002523 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002524}
2525
Aart Bik6b69e0a2017-01-11 10:20:43 -08002526void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2527 DCHECK(EndsWithControlFlowInstruction());
2528 RemoveInstruction(GetLastInstruction());
2529 instructions_.Add(other->GetInstructions());
2530 other->instructions_.SetBlockOfInstructions(this);
2531 other->instructions_.Clear();
2532}
2533
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002534void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002535 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002536 DCHECK(ContainsElement(dominated_blocks_, other));
2537 DCHECK_EQ(GetSingleSuccessor(), other);
2538 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002539 DCHECK(other->GetPhis().IsEmpty());
2540
David Brazdil2d7352b2015-04-20 14:52:42 +01002541 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002542 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002543
David Brazdil2d7352b2015-04-20 14:52:42 +01002544 // Remove `other` from the loops it is included in.
2545 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2546 HLoopInformation* loop_info = it.Current();
2547 loop_info->Remove(other);
2548 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002549 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002550 }
2551 }
2552
2553 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002554 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002555 for (HBasicBlock* successor : other->GetSuccessors()) {
2556 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002557 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002558 successors_.swap(other->successors_);
2559 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002560
David Brazdil2d7352b2015-04-20 14:52:42 +01002561 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002562 RemoveDominatedBlock(other);
2563 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002564 dominated->SetDominator(this);
2565 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002566 dominated_blocks_.insert(
2567 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002568 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002569 other->dominator_ = nullptr;
2570
2571 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002572 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002573
2574 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002575 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002576 other->SetGraph(nullptr);
2577}
2578
2579void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2580 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002581 DCHECK(GetDominatedBlocks().empty());
2582 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002583 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002584 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002585 DCHECK(other->GetPhis().IsEmpty());
2586 DCHECK(!other->IsInLoop());
2587
2588 // Move instructions from `other` to `this`.
2589 instructions_.Add(other->GetInstructions());
2590 other->instructions_.SetBlockOfInstructions(this);
2591
2592 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002593 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002594 for (HBasicBlock* successor : other->GetSuccessors()) {
2595 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002596 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002597 successors_.swap(other->successors_);
2598 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002599
2600 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002601 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002602 dominated->SetDominator(this);
2603 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002604 dominated_blocks_.insert(
2605 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002606 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002607 other->dominator_ = nullptr;
2608 other->graph_ = nullptr;
2609}
2610
2611void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002612 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002613 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002614 predecessor->ReplaceSuccessor(this, other);
2615 }
Vladimir Marko60584552015-09-03 13:35:12 +00002616 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002617 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002618 successor->ReplacePredecessor(this, other);
2619 }
Vladimir Marko60584552015-09-03 13:35:12 +00002620 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2621 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002622 }
2623 GetDominator()->ReplaceDominatedBlock(this, other);
2624 other->SetDominator(GetDominator());
2625 dominator_ = nullptr;
2626 graph_ = nullptr;
2627}
2628
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002629void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002630 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002631 DCHECK(block->GetSuccessors().empty());
2632 DCHECK(block->GetPredecessors().empty());
2633 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002634 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002635 DCHECK(block->GetInstructions().IsEmpty());
2636 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002637
David Brazdilc7af85d2015-05-26 12:05:55 +01002638 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002639 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002640 }
2641
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002642 RemoveElement(reverse_post_order_, block);
2643 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002644 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002645}
2646
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002647void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2648 HBasicBlock* reference,
2649 bool replace_if_back_edge) {
2650 if (block->IsLoopHeader()) {
2651 // Clear the information of which blocks are contained in that loop. Since the
2652 // information is stored as a bit vector based on block ids, we have to update
2653 // it, as those block ids were specific to the callee graph and we are now adding
2654 // these blocks to the caller graph.
2655 block->GetLoopInformation()->ClearAllBlocks();
2656 }
2657
2658 // If not already in a loop, update the loop information.
2659 if (!block->IsInLoop()) {
2660 block->SetLoopInformation(reference->GetLoopInformation());
2661 }
2662
2663 // If the block is in a loop, update all its outward loops.
2664 HLoopInformation* loop_info = block->GetLoopInformation();
2665 if (loop_info != nullptr) {
2666 for (HLoopInformationOutwardIterator loop_it(*block);
2667 !loop_it.Done();
2668 loop_it.Advance()) {
2669 loop_it.Current()->Add(block);
2670 }
2671 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2672 loop_info->ReplaceBackEdge(reference, block);
2673 }
2674 }
2675
2676 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2677 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2678 ? reference->GetTryCatchInformation()
2679 : nullptr;
2680 block->SetTryCatchInformation(try_catch_info);
2681}
2682
Calin Juravle2e768302015-07-28 14:41:11 +00002683HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002684 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002685 // Update the environments in this graph to have the invoke's environment
2686 // as parent.
2687 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002688 // Skip the entry block, we do not need to update the entry's suspend check.
2689 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002690 for (HInstructionIterator instr_it(block->GetInstructions());
2691 !instr_it.Done();
2692 instr_it.Advance()) {
2693 HInstruction* current = instr_it.Current();
2694 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002695 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002696 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002697 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002698 }
2699 }
2700 }
2701 }
2702 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002703
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002704 if (HasBoundsChecks()) {
2705 outer_graph->SetHasBoundsChecks(true);
2706 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002707 if (HasLoops()) {
2708 outer_graph->SetHasLoops(true);
2709 }
2710 if (HasIrreducibleLoops()) {
2711 outer_graph->SetHasIrreducibleLoops(true);
2712 }
Vladimir Markod3e9c622020-08-05 12:20:28 +01002713 if (HasDirectCriticalNativeCall()) {
2714 outer_graph->SetHasDirectCriticalNativeCall(true);
2715 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002716 if (HasTryCatch()) {
2717 outer_graph->SetHasTryCatch(true);
2718 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002719 if (HasSIMD()) {
2720 outer_graph->SetHasSIMD(true);
2721 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002722
Calin Juravle2e768302015-07-28 14:41:11 +00002723 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002724 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002725 // Inliner already made sure we don't inline methods that always throw.
2726 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002727 // Simple case of an entry block, a body block, and an exit block.
2728 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002729 HBasicBlock* body = GetBlocks()[1];
2730 DCHECK(GetBlocks()[0]->IsEntryBlock());
2731 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002732 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002733 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002734 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002735
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002736 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2737 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002738 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002739
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002740 // Replace the invoke with the return value of the inlined graph.
2741 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002742 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002743 } else {
2744 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002745 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002746
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002747 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002748 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002749 // Need to inline multiple blocks. We split `invoke`'s block
2750 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002751 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002752 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002753 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002754 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002755 // Note that we split before the invoke only to simplify polymorphic inlining.
2756 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002757
Vladimir Markoec7802a2015-10-01 20:57:57 +01002758 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002759 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002760 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002761 exit_block_->ReplaceWith(to);
2762
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002763 // Update the meta information surrounding blocks:
2764 // (1) the graph they are now in,
2765 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002766 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002767 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002768 // Note that we do not need to update catch phi inputs because they
2769 // correspond to the register file of the outer method which the inlinee
2770 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002771
2772 // We don't add the entry block, the exit block, and the first block, which
2773 // has been merged with `at`.
2774 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2775
2776 // We add the `to` block.
2777 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002778 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002779 + kNumberOfNewBlocksInCaller;
2780
2781 // Find the location of `at` in the outer graph's reverse post order. The new
2782 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002783 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002784 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2785
David Brazdil95177982015-10-30 12:56:58 -05002786 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2787 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002788 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002789 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002790 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002791 DCHECK(current->GetGraph() == this);
2792 current->SetGraph(outer_graph);
2793 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002794 outer_graph->reverse_post_order_[++index_of_at] = current;
Andreas Gampe3db70682018-12-26 15:12:03 -08002795 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge= */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002796 }
2797 }
2798
David Brazdil95177982015-10-30 12:56:58 -05002799 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002800 to->SetGraph(outer_graph);
2801 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002802 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002803 // Only `to` can become a back edge, as the inlined blocks
2804 // are predecessors of `to`.
Andreas Gampe3db70682018-12-26 15:12:03 -08002805 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002806
David Brazdil3f523062016-02-29 16:53:33 +00002807 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002808 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2809 // to now get the outer graph exit block as successor. Note that the inliner
2810 // currently doesn't support inlining methods with try/catch.
2811 HPhi* return_value_phi = nullptr;
2812 bool rerun_dominance = false;
2813 bool rerun_loop_analysis = false;
2814 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2815 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002816 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002817 if (last->IsThrow()) {
2818 DCHECK(!at->IsTryBlock());
2819 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2820 --pred;
2821 // We need to re-run dominance information, as the exit block now has
2822 // a new dominator.
2823 rerun_dominance = true;
2824 if (predecessor->GetLoopInformation() != nullptr) {
2825 // The exit block and blocks post dominated by the exit block do not belong
2826 // to any loop. Because we do not compute the post dominators, we need to re-run
2827 // loop analysis to get the loop information correct.
2828 rerun_loop_analysis = true;
2829 }
2830 } else {
2831 if (last->IsReturnVoid()) {
2832 DCHECK(return_value == nullptr);
2833 DCHECK(return_value_phi == nullptr);
2834 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002835 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002836 if (return_value_phi != nullptr) {
2837 return_value_phi->AddInput(last->InputAt(0));
2838 } else if (return_value == nullptr) {
2839 return_value = last->InputAt(0);
2840 } else {
2841 // There will be multiple returns.
2842 return_value_phi = new (allocator) HPhi(
2843 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2844 to->AddPhi(return_value_phi);
2845 return_value_phi->AddInput(return_value);
2846 return_value_phi->AddInput(last->InputAt(0));
2847 return_value = return_value_phi;
2848 }
David Brazdil3f523062016-02-29 16:53:33 +00002849 }
2850 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2851 predecessor->RemoveInstruction(last);
2852 }
2853 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002854 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002855 DCHECK(!outer_graph->HasIrreducibleLoops())
2856 << "Recomputing loop information in graphs with irreducible loops "
2857 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002858 outer_graph->ClearLoopInformation();
2859 outer_graph->ClearDominanceInformation();
2860 outer_graph->BuildDominatorTree();
2861 } else if (rerun_dominance) {
2862 outer_graph->ClearDominanceInformation();
2863 outer_graph->ComputeDominanceInformation();
2864 }
David Brazdil3f523062016-02-29 16:53:33 +00002865 }
David Brazdil05144f42015-04-16 15:18:00 +01002866
2867 // Walk over the entry block and:
2868 // - Move constants from the entry block to the outer_graph's entry block,
2869 // - Replace HParameterValue instructions with their real value.
2870 // - Remove suspend checks, that hold an environment.
2871 // We must do this after the other blocks have been inlined, otherwise ids of
2872 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002873 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002874 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2875 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002876 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002877 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002878 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002879 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002880 replacement = outer_graph->GetIntConstant(
2881 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002882 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002883 replacement = outer_graph->GetLongConstant(
2884 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002885 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002886 replacement = outer_graph->GetFloatConstant(
2887 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002888 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002889 replacement = outer_graph->GetDoubleConstant(
2890 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002891 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002892 if (kIsDebugBuild
2893 && invoke->IsInvokeStaticOrDirect()
2894 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2895 // Ensure we do not use the last input of `invoke`, as it
2896 // contains a clinit check which is not an actual argument.
2897 size_t last_input_index = invoke->InputCount() - 1;
2898 DCHECK(parameter_index != last_input_index);
2899 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002900 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002901 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002902 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002903 } else {
2904 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2905 entry_block_->RemoveInstruction(current);
2906 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002907 if (replacement != nullptr) {
2908 current->ReplaceWith(replacement);
2909 // If the current is the return value then we need to update the latter.
2910 if (current == return_value) {
2911 DCHECK_EQ(entry_block_, return_value->GetBlock());
2912 return_value = replacement;
2913 }
2914 }
2915 }
2916
Calin Juravle2e768302015-07-28 14:41:11 +00002917 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002918}
2919
Mingyao Yang3584bce2015-05-19 16:01:59 -07002920/*
2921 * Loop will be transformed to:
2922 * old_pre_header
2923 * |
2924 * if_block
2925 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002926 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002927 * \ /
2928 * new_pre_header
2929 * |
2930 * header
2931 */
2932void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2933 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002934 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002935
Aart Bik3fc7f352015-11-20 22:03:03 -08002936 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002937 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2938 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2939 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2940 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002941 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002942 AddBlock(true_block);
2943 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002944 AddBlock(new_pre_header);
2945
Aart Bik3fc7f352015-11-20 22:03:03 -08002946 header->ReplacePredecessor(old_pre_header, new_pre_header);
2947 old_pre_header->successors_.clear();
2948 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002949
Aart Bik3fc7f352015-11-20 22:03:03 -08002950 old_pre_header->AddSuccessor(if_block);
2951 if_block->AddSuccessor(true_block); // True successor
2952 if_block->AddSuccessor(false_block); // False successor
2953 true_block->AddSuccessor(new_pre_header);
2954 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002955
Aart Bik3fc7f352015-11-20 22:03:03 -08002956 old_pre_header->dominated_blocks_.push_back(if_block);
2957 if_block->SetDominator(old_pre_header);
2958 if_block->dominated_blocks_.push_back(true_block);
2959 true_block->SetDominator(if_block);
2960 if_block->dominated_blocks_.push_back(false_block);
2961 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002962 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002963 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002964 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002965 header->SetDominator(new_pre_header);
2966
Aart Bik3fc7f352015-11-20 22:03:03 -08002967 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002968 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002969 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002970 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002971 reverse_post_order_[index_of_header++] = true_block;
2972 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002973 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002974
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002975 // The pre_header can never be a back edge of a loop.
2976 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2977 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2978 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002979 if_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002980 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002981 true_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002982 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002983 false_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002984 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002985 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002986}
2987
Aart Bikf8f5a162017-02-06 15:35:29 -08002988HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2989 HBasicBlock* body,
2990 HBasicBlock* exit) {
2991 DCHECK(header->IsLoopHeader());
2992 HLoopInformation* loop = header->GetLoopInformation();
2993
2994 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002995 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2996 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2997 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002998 AddBlock(new_pre_header);
2999 AddBlock(new_header);
3000 AddBlock(new_body);
3001
3002 // Set up control flow.
3003 header->ReplaceSuccessor(exit, new_pre_header);
3004 new_pre_header->AddSuccessor(new_header);
3005 new_header->AddSuccessor(exit);
3006 new_header->AddSuccessor(new_body);
3007 new_body->AddSuccessor(new_header);
3008
3009 // Set up dominators.
3010 header->ReplaceDominatedBlock(exit, new_pre_header);
3011 new_pre_header->SetDominator(header);
3012 new_pre_header->dominated_blocks_.push_back(new_header);
3013 new_header->SetDominator(new_pre_header);
3014 new_header->dominated_blocks_.push_back(new_body);
3015 new_body->SetDominator(new_header);
3016 new_header->dominated_blocks_.push_back(exit);
3017 exit->SetDominator(new_header);
3018
3019 // Fix reverse post order.
3020 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
3021 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
3022 reverse_post_order_[++index_of_header] = new_pre_header;
3023 reverse_post_order_[++index_of_header] = new_header;
3024 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
3025 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
3026 reverse_post_order_[index_of_body] = new_body;
3027
Aart Bikb07d1bc2017-04-05 10:03:15 -07003028 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01003029 new_pre_header->AddInstruction(new (allocator_) HGoto());
3030 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08003031 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01003032 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07003033 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
3034 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08003035
3036 // Update loop information.
3037 new_header->AddBackEdge(new_body);
3038 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
3039 new_header->GetLoopInformation()->Populate();
3040 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
3041 HLoopInformationOutwardIterator it(*new_header);
3042 for (it.Advance(); !it.Done(); it.Advance()) {
3043 it.Current()->Add(new_pre_header);
3044 it.Current()->Add(new_header);
3045 it.Current()->Add(new_body);
3046 }
3047 return new_pre_header;
3048}
3049
David Brazdilf5552582015-12-27 13:36:12 +00003050static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003051 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00003052 if (rti.IsValid()) {
3053 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
3054 << " upper_bound_rti: " << upper_bound_rti
3055 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003056 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
3057 << " upper_bound_rti: " << upper_bound_rti
3058 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00003059 }
3060}
3061
Calin Juravle2e768302015-07-28 14:41:11 +00003062void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
3063 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003064 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00003065 ScopedObjectAccess soa(Thread::Current());
3066 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
3067 if (IsBoundType()) {
3068 // Having the test here spares us from making the method virtual just for
3069 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00003070 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00003071 }
3072 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003073 reference_type_handle_ = rti.GetTypeHandle();
3074 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00003075}
3076
Artem Serov4d277ba2018-06-05 20:54:42 +01003077bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
3078 const HBoundType* other_bt = other->AsBoundType();
3079 ScopedObjectAccess soa(Thread::Current());
3080 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
3081 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
3082 CanBeNull() == other_bt->CanBeNull();
3083}
3084
David Brazdilf5552582015-12-27 13:36:12 +00003085void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
3086 if (kIsDebugBuild) {
3087 ScopedObjectAccess soa(Thread::Current());
3088 DCHECK(upper_bound.IsValid());
3089 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
3090 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
3091 }
3092 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00003093 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00003094}
3095
Vladimir Markoa1de9182016-02-25 11:37:38 +00003096ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00003097 if (kIsDebugBuild) {
3098 ScopedObjectAccess soa(Thread::Current());
3099 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003100 if (!is_exact) {
3101 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
3102 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
3103 }
Calin Juravle2e768302015-07-28 14:41:11 +00003104 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003105 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00003106}
3107
Calin Juravleacf735c2015-02-12 15:25:22 +00003108std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
3109 ScopedObjectAccess soa(Thread::Current());
3110 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00003111 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07003112 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00003113 << " is_exact=" << rhs.IsExact()
3114 << " ]";
3115 return os;
3116}
3117
Mark Mendellc4701932015-04-10 13:18:51 -04003118bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
3119 // For now, assume that instructions in different blocks may use the
3120 // environment.
3121 // TODO: Use the control flow to decide if this is true.
3122 if (GetBlock() != other->GetBlock()) {
3123 return true;
3124 }
3125
3126 // We know that we are in the same block. Walk from 'this' to 'other',
3127 // checking to see if there is any instruction with an environment.
3128 HInstruction* current = this;
3129 for (; current != other && current != nullptr; current = current->GetNext()) {
3130 // This is a conservative check, as the instruction result may not be in
3131 // the referenced environment.
3132 if (current->HasEnvironment()) {
3133 return true;
3134 }
3135 }
3136
3137 // We should have been called with 'this' before 'other' in the block.
3138 // Just confirm this.
3139 DCHECK(current != nullptr);
3140 return false;
3141}
3142
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003143void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003144 IntrinsicNeedsEnvironment needs_env,
Aart Bik5d75afe2015-12-14 11:57:01 -08003145 IntrinsicSideEffects side_effects,
3146 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003147 intrinsic_ = intrinsic;
3148 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003149
Aart Bik5d75afe2015-12-14 11:57:01 -08003150 // Adjust method's side effects from intrinsic table.
3151 switch (side_effects) {
3152 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
3153 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
3154 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
3155 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
3156 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003157
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003158 if (needs_env == kNoEnvironment) {
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003159 opt.SetDoesNotNeedEnvironment();
3160 } else {
3161 // If we need an environment, that means there will be a call, which can trigger GC.
3162 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
3163 }
Aart Bik5d75afe2015-12-14 11:57:01 -08003164 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08003165 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003166}
3167
David Brazdil6de19382016-01-08 17:37:10 +00003168bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07003169 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00003170}
3171
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003172bool HInvoke::NeedsEnvironment() const {
3173 if (!IsIntrinsic()) {
3174 return true;
3175 }
3176 IntrinsicOptimizations opt(*this);
3177 return !opt.GetDoesNotNeedEnvironment();
3178}
3179
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00003180const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
3181 ArtMethod* caller = GetEnvironment()->GetMethod();
3182 ScopedObjectAccess soa(Thread::Current());
3183 // `caller` is null for a top-level graph representing a method whose declaring
3184 // class was not resolved.
3185 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
3186}
3187
Vladimir Markofbb184a2015-11-13 14:47:00 +00003188std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
3189 switch (rhs) {
3190 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
3191 return os << "explicit";
3192 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
3193 return os << "implicit";
3194 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
3195 return os << "none";
3196 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00003197 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
3198 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00003199 }
3200}
3201
Vladimir Markoac27ac02021-02-01 09:31:02 +00003202bool HInvokeVirtual::CanDoImplicitNullCheckOn(HInstruction* obj) const {
3203 if (obj != InputAt(0)) {
3204 return false;
3205 }
3206 switch (GetIntrinsic()) {
Vladimir Marko5e060ee2021-02-23 10:56:42 +00003207 case Intrinsics::kNone:
3208 return true;
Vladimir Markoac27ac02021-02-01 09:31:02 +00003209 case Intrinsics::kReferenceRefersTo:
3210 return true;
3211 default:
3212 // TODO: Add implicit null checks in more intrinsics.
3213 return false;
3214 }
3215}
3216
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003217bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
3218 const HLoadClass* other_load_class = other->AsLoadClass();
3219 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
3220 // names rather than type indexes. However, we shall also have to re-think the hash code.
3221 if (type_index_ != other_load_class->type_index_ ||
3222 GetPackedFields() != other_load_class->GetPackedFields()) {
3223 return false;
3224 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003225 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003226 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003227 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003228 case LoadKind::kJitTableAddress: {
3229 ScopedObjectAccess soa(Thread::Current());
3230 return GetClass().Get() == other_load_class->GetClass().Get();
3231 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003232 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00003233 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003234 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003235 }
3236}
3237
Vladimir Marko372f10e2016-05-17 16:30:10 +01003238bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3239 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003240 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3241 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003242 if (string_index_ != other_load_string->string_index_ ||
3243 GetPackedFields() != other_load_string->GetPackedFields()) {
3244 return false;
3245 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003246 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003247 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003248 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003249 case LoadKind::kJitTableAddress: {
3250 ScopedObjectAccess soa(Thread::Current());
3251 return GetString().Get() == other_load_string->GetString().Get();
3252 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003253 default:
3254 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003255 }
3256}
3257
Mark Mendellc4701932015-04-10 13:18:51 -04003258void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003259 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3260 HEnvironment* user = use.GetUser();
3261 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003262 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003263 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003264}
3265
Artem Serovcced8ba2017-07-19 18:18:09 +01003266HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3267 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3268 HBasicBlock* block = instr->GetBlock();
3269
3270 if (instr->IsPhi()) {
3271 HPhi* phi = instr->AsPhi();
3272 DCHECK(!phi->HasEnvironment());
3273 HPhi* phi_clone = clone->AsPhi();
3274 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3275 } else {
3276 block->ReplaceAndRemoveInstructionWith(instr, clone);
3277 if (instr->HasEnvironment()) {
3278 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3279 HLoopInformation* loop_info = block->GetLoopInformation();
3280 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3281 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3282 }
3283 }
3284 }
3285 return clone;
3286}
3287
Roland Levillainc9b21f82016-03-23 16:36:59 +00003288// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003289HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003290 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003291
3292 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003293 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003294 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3295 HInstruction* lhs = cond->InputAt(0);
3296 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003297 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003298 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3299 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3300 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3301 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3302 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3303 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3304 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3305 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3306 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3307 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3308 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003309 default:
3310 LOG(FATAL) << "Unexpected condition";
3311 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003312 }
3313 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3314 return replacement;
3315 } else if (cond->IsIntConstant()) {
3316 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003317 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003318 return GetIntConstant(1);
3319 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003320 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003321 return GetIntConstant(0);
3322 }
3323 } else {
3324 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3325 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3326 return replacement;
3327 }
3328}
3329
Roland Levillainc9285912015-12-18 10:38:42 +00003330std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3331 os << "["
3332 << " source=" << rhs.GetSource()
3333 << " destination=" << rhs.GetDestination()
3334 << " type=" << rhs.GetType()
3335 << " instruction=";
3336 if (rhs.GetInstruction() != nullptr) {
3337 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3338 } else {
3339 os << "null";
3340 }
3341 os << " ]";
3342 return os;
3343}
3344
Roland Levillain86503782016-02-11 19:07:30 +00003345std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3346 switch (rhs) {
3347 case TypeCheckKind::kUnresolvedCheck:
3348 return os << "unresolved_check";
3349 case TypeCheckKind::kExactCheck:
3350 return os << "exact_check";
3351 case TypeCheckKind::kClassHierarchyCheck:
3352 return os << "class_hierarchy_check";
3353 case TypeCheckKind::kAbstractClassCheck:
3354 return os << "abstract_class_check";
3355 case TypeCheckKind::kInterfaceCheck:
3356 return os << "interface_check";
3357 case TypeCheckKind::kArrayObjectCheck:
3358 return os << "array_object_check";
3359 case TypeCheckKind::kArrayCheck:
3360 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003361 case TypeCheckKind::kBitstringCheck:
3362 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003363 default:
3364 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3365 UNREACHABLE();
3366 }
3367}
3368
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003369// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3370#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3371 static_assert( \
3372 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3373 "Instrinsics enumeration space overflow.");
3374#include "intrinsics_list.h"
3375 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3376#undef INTRINSICS_LIST
3377#undef CHECK_INTRINSICS_ENUM_VALUES
3378
3379// Function that returns whether an intrinsic needs an environment or not.
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003380static inline IntrinsicNeedsEnvironment NeedsEnvironmentIntrinsic(Intrinsics i) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003381 switch (i) {
3382 case Intrinsics::kNone:
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003383 return kNeedsEnvironment; // Non-sensical for intrinsic.
3384#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003385 case Intrinsics::k ## Name: \
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003386 return NeedsEnv;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003387#include "intrinsics_list.h"
3388 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3389#undef INTRINSICS_LIST
3390#undef OPTIMIZING_INTRINSICS
3391 }
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003392 return kNeedsEnvironment;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003393}
3394
3395// Function that returns whether an intrinsic has side effects.
3396static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3397 switch (i) {
3398 case Intrinsics::kNone:
3399 return kAllSideEffects;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003400#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003401 case Intrinsics::k ## Name: \
3402 return SideEffects;
3403#include "intrinsics_list.h"
3404 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3405#undef INTRINSICS_LIST
3406#undef OPTIMIZING_INTRINSICS
3407 }
3408 return kAllSideEffects;
3409}
3410
3411// Function that returns whether an intrinsic can throw exceptions.
3412static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3413 switch (i) {
3414 case Intrinsics::kNone:
3415 return kCanThrow;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003416#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003417 case Intrinsics::k ## Name: \
3418 return Exceptions;
3419#include "intrinsics_list.h"
3420 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3421#undef INTRINSICS_LIST
3422#undef OPTIMIZING_INTRINSICS
3423 }
3424 return kCanThrow;
3425}
3426
3427void HInvoke::SetResolvedMethod(ArtMethod* method) {
Andra Danciua0130e82020-07-23 12:34:56 +00003428 if (method != nullptr && method->IsIntrinsic()) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003429 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3430 SetIntrinsic(intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003431 NeedsEnvironmentIntrinsic(intrinsic),
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003432 GetSideEffectsIntrinsic(intrinsic),
3433 GetExceptionsIntrinsic(intrinsic));
3434 }
3435 resolved_method_ = method;
3436}
3437
Evgeny Astigeevichaf92a0f2020-06-26 13:28:33 +01003438bool IsGEZero(HInstruction* instruction) {
3439 DCHECK(instruction != nullptr);
3440 if (instruction->IsArrayLength()) {
3441 return true;
3442 } else if (instruction->IsMin()) {
3443 // Instruction MIN(>=0, >=0) is >= 0.
3444 return IsGEZero(instruction->InputAt(0)) &&
3445 IsGEZero(instruction->InputAt(1));
3446 } else if (instruction->IsAbs()) {
3447 // Instruction ABS(>=0) is >= 0.
3448 // NOTE: ABS(minint) = minint prevents assuming
3449 // >= 0 without looking at the argument.
3450 return IsGEZero(instruction->InputAt(0));
3451 }
3452 int64_t value = -1;
3453 return IsInt64AndGet(instruction, &value) && value >= 0;
3454}
3455
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003456} // namespace art