blob: c99cfab05f122dc3a3f1154e1a64adae5208a518 [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"
Vladimir Markodac82392021-05-10 15:44:24 +000030#include "base/malloc_arena_pool.h"
Alex Light86fe9b82020-11-16 16:54:01 +000031#include "base/scoped_arena_allocator.h"
32#include "base/scoped_arena_containers.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070033#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080034#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010035#include "class_root-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040036#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000037#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010038#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010039#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070041#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000042
VladimĂ­r Marko434d9682022-11-04 14:04:17 +000043namespace art HIDDEN {
Nicolas Geoffray818f2102014-02-18 16:43:35 +000044
Roland Levillain31dd3d62016-02-16 12:21:02 +000045// Enable floating-point static evaluation during constant folding
46// only if all floating-point operations and constants evaluate in the
47// range and precision of the type used (i.e., 32-bit float, 64-bit
48// double).
49static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
50
Vladimir Marko02ca05a2020-05-12 13:58:51 +010051ReferenceTypeInfo::TypeHandle HandleCache::CreateRootHandle(VariableSizedHandleScope* handles,
52 ClassRoot class_root) {
53 // Mutator lock is required for NewHandle and GetClassRoot().
David Brazdilbadd8262016-02-02 16:28:56 +000054 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko02ca05a2020-05-12 13:58:51 +010055 return handles->NewHandle(GetClassRoot(class_root));
David Brazdilbadd8262016-02-02 16:28:56 +000056}
57
Nicolas Geoffray818f2102014-02-18 16:43:35 +000058void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010059 block->SetBlockId(blocks_.size());
60 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000061}
62
Nicolas Geoffray804d0932014-05-02 08:46:00 +010063void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
65 DCHECK_EQ(visited->GetHighestBitSet(), -1);
66
Vladimir Marko69d310e2017-10-09 14:12:23 +010067 // Allocate memory from local ScopedArenaAllocator.
68 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010069 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010070 ArenaBitVector visiting(
Andreas Gampe3db70682018-12-26 15:12:03 -080071 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +010072 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010073 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010074 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
75 0u,
76 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010077 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010078 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 constexpr size_t kDefaultWorklistSize = 8;
80 worklist.reserve(kDefaultWorklistSize);
81 visited->SetBit(entry_block_->GetBlockId());
82 visiting.SetBit(entry_block_->GetBlockId());
83 worklist.push_back(entry_block_);
84
85 while (!worklist.empty()) {
86 HBasicBlock* current = worklist.back();
87 uint32_t current_id = current->GetBlockId();
88 if (successors_visited[current_id] == current->GetSuccessors().size()) {
89 visiting.ClearBit(current_id);
90 worklist.pop_back();
91 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010092 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
93 uint32_t successor_id = successor->GetBlockId();
94 if (visiting.IsBitSet(successor_id)) {
95 DCHECK(ContainsElement(worklist, successor));
96 successor->AddBackEdge(current);
97 } else if (!visited->IsBitSet(successor_id)) {
98 visited->SetBit(successor_id);
99 visiting.SetBit(successor_id);
100 worklist.push_back(successor);
101 }
102 }
103 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Remove the environment use records of the instruction for users.
107void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000112 if (environment->GetInstructionAt(i) != nullptr) {
113 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000114 }
115 }
116 }
117}
118
Artem Serov21c7e6f2017-07-27 16:04:42 +0100119// Return whether the instruction has an environment and it's used by others.
120bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
121 for (HEnvironment* environment = instruction->GetEnvironment();
122 environment != nullptr;
123 environment = environment->GetParent()) {
124 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
125 HInstruction* user = environment->GetInstructionAt(i);
126 if (user != nullptr) {
127 return true;
128 }
129 }
130 }
131 return false;
132}
133
134// Reset environment records of the instruction itself.
135void ResetEnvironmentInputRecords(HInstruction* instruction) {
136 for (HEnvironment* environment = instruction->GetEnvironment();
137 environment != nullptr;
138 environment = environment->GetParent()) {
139 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
140 DCHECK(environment->GetHolder() == instruction);
141 if (environment->GetInstructionAt(i) != nullptr) {
142 environment->SetRawEnvAt(i, nullptr);
143 }
144 }
145 }
146}
147
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000148static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100149 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000150 RemoveEnvironmentUses(instruction);
151}
152
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100153void HGraph::RemoveDeadBlocksInstructionsAsUsersAndDisconnect(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100158
159 // Remove as user.
Nicolas Geoffray2cc9d342019-04-26 14:21:14 +0100160 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
161 RemoveAsUser(it.Current());
162 }
Roland Levillainfc600dc2014-12-02 17:16:31 +0000163 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
164 RemoveAsUser(it.Current());
165 }
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100166
167 // Remove non-catch phi uses, and disconnect the block.
168 block->DisconnectFromSuccessors(&visited);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000169 }
170 }
171}
172
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100173// This method assumes `insn` has been removed from all users with the exception of catch
174// phis because of missing exceptional edges in the graph. It removes the
175// instruction from catch phi uses, together with inputs of other catch phis in
176// the catch block at the same index, as these must be dead too.
177static void RemoveCatchPhiUsesOfDeadInstruction(HInstruction* insn) {
178 DCHECK(!insn->HasEnvironmentUses());
179 while (insn->HasNonEnvironmentUses()) {
180 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
181 size_t use_index = use.GetIndex();
182 HBasicBlock* user_block = use.GetUser()->GetBlock();
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100183 DCHECK(use.GetUser()->IsPhi());
184 DCHECK(user_block->IsCatchBlock());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100185 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
186 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
187 }
188 }
189}
190
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100191void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +0100192 DCHECK(reverse_post_order_.empty()) << "We shouldn't have dominance information.";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100193 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000194 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100195 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000196 if (block == nullptr) continue;
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100197
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100198 // Remove all remaining uses (which should be only catch phi uses), and the instructions.
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +0100199 block->RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ true);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100200
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100201 // Remove the block from the list of blocks, so that further analyses
202 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100203 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600204 if (block->IsExitBlock()) {
205 SetExitBlock(nullptr);
206 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000207 // Mark the block as removed. This is used by the HGraphBuilder to discard
208 // the block as a branch target.
209 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000210 }
211 }
212}
213
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000214GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100215 // Allocate memory from local ScopedArenaAllocator.
216 ScopedArenaAllocator allocator(GetArenaStack());
217
218 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
219 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000220
David Brazdil86ea7ee2016-02-16 09:26:07 +0000221 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000222 FindBackEdges(&visited);
223
David Brazdil86ea7ee2016-02-16 09:26:07 +0000224 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000225 // the initial DFS as users from other instructions, so that
226 // users can be safely removed before uses later.
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100227 // Also disconnect the block from its successors, updating the successor's phis if needed.
228 RemoveDeadBlocksInstructionsAsUsersAndDisconnect(visited);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000229
David Brazdil86ea7ee2016-02-16 09:26:07 +0000230 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000231 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000232 // predecessors list of live blocks.
233 RemoveDeadBlocks(visited);
234
David Brazdil86ea7ee2016-02-16 09:26:07 +0000235 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100236 // dominators and the reverse post order.
237 SimplifyCFG();
238
David Brazdil86ea7ee2016-02-16 09:26:07 +0000239 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100240 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000241
David Brazdil86ea7ee2016-02-16 09:26:07 +0000242 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000243 // set the loop information on each block.
244 GraphAnalysisResult result = AnalyzeLoops();
245 if (result != kAnalysisSuccess) {
246 return result;
247 }
248
David Brazdil86ea7ee2016-02-16 09:26:07 +0000249 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000250 // which needs the information to build catch block phis from values of
251 // locals at throwing instructions inside try blocks.
252 ComputeTryBlockInformation();
253
254 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100255}
256
257void HGraph::ClearDominanceInformation() {
Alex Light210a78d2020-11-30 16:58:05 -0800258 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100259 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100260 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100261 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100262}
263
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000264void HGraph::ClearLoopInformation() {
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000265 SetHasLoops(false);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000266 SetHasIrreducibleLoops(false);
Alex Light210a78d2020-11-30 16:58:05 -0800267 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100268 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000269 }
270}
271
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100272void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000273 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100274 dominator_ = nullptr;
275}
276
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000277HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
278 HInstruction* instruction = GetFirstInstruction();
279 while (instruction->IsParallelMove()) {
280 instruction = instruction->GetNext();
281 }
282 return instruction;
283}
284
David Brazdil3f4a5222016-05-06 12:46:21 +0100285static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
286 DCHECK(ContainsElement(block->GetSuccessors(), successor));
287
288 HBasicBlock* old_dominator = successor->GetDominator();
289 HBasicBlock* new_dominator =
290 (old_dominator == nullptr) ? block
291 : CommonDominator::ForPair(old_dominator, block);
292
293 if (old_dominator == new_dominator) {
294 return false;
295 } else {
296 successor->SetDominator(new_dominator);
297 return true;
298 }
299}
300
Alex Light86fe9b82020-11-16 16:54:01 +0000301// TODO Consider moving this entirely into LoadStoreAnalysis/Elimination.
302bool HGraph::PathBetween(uint32_t source_idx, uint32_t dest_idx) const {
303 DCHECK_LT(source_idx, blocks_.size()) << "source not present in graph!";
304 DCHECK_LT(dest_idx, blocks_.size()) << "dest not present in graph!";
305 DCHECK(blocks_[source_idx] != nullptr);
306 DCHECK(blocks_[dest_idx] != nullptr);
307 return reachability_graph_.IsBitSet(source_idx, dest_idx);
308}
309
310bool HGraph::PathBetween(const HBasicBlock* source, const HBasicBlock* dest) const {
311 if (source == nullptr || dest == nullptr) {
312 return false;
313 }
314 size_t source_idx = source->GetBlockId();
315 size_t dest_idx = dest->GetBlockId();
316 return PathBetween(source_idx, dest_idx);
317}
318
319// This function/struct calculates the reachability of every node from every
320// other node by iteratively using DFS to find reachability of each individual
321// block.
322//
323// This is in practice faster then the simpler Floyd-Warshall since while that
324// is O(N**3) this is O(N*(E + N)) where N is the number of blocks and E is the
325// number of edges. Since in practice each block only has a few outgoing edges
326// we can confidently say that E ~ B*N where B is a small number (~3). We also
327// memoize the results as we go allowing us to (potentially) avoid walking the
328// entire graph for every node. To make best use of this memoization we
329// calculate the reachability of blocks in PostOrder. This means that
330// (generally) blocks that are dominated by many other blocks and dominate few
331// blocks themselves will be examined first. This makes it more likely we can
332// use our memoized results.
333class ReachabilityAnalysisHelper {
334 public:
335 ReachabilityAnalysisHelper(const HGraph* graph,
336 ArenaBitVectorArray* reachability_graph,
337 ArenaStack* arena_stack)
338 : graph_(graph),
339 reachability_graph_(reachability_graph),
340 arena_stack_(arena_stack),
341 temporaries_(arena_stack_),
342 block_size_(RoundUp(graph_->GetBlocks().size(), BitVector::kWordBits)),
343 all_visited_nodes_(
344 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph),
345 not_post_order_visited_(
346 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph) {
347 // We can't adjust the size of reachability graph any more without breaking
348 // our allocator invariants so it had better be large enough.
349 CHECK_GE(reachability_graph_->NumRows(), graph_->GetBlocks().size());
350 CHECK_GE(reachability_graph_->NumColumns(), graph_->GetBlocks().size());
351 not_post_order_visited_.SetInitialBits(graph_->GetBlocks().size());
352 }
353
354 void CalculateReachability() {
355 // Calculate what blocks connect using repeated DFS
356 //
357 // Going in PostOrder should generally give memoization a good shot of
358 // hitting.
359 for (const HBasicBlock* blk : graph_->GetPostOrder()) {
360 if (blk == nullptr) {
361 continue;
362 }
363 not_post_order_visited_.ClearBit(blk->GetBlockId());
364 CalculateConnectednessOn(blk);
365 all_visited_nodes_.SetBit(blk->GetBlockId());
366 }
367 // Get all other bits
368 for (auto idx : not_post_order_visited_.Indexes()) {
369 const HBasicBlock* blk = graph_->GetBlocks()[idx];
370 if (blk == nullptr) {
371 continue;
372 }
373 CalculateConnectednessOn(blk);
374 all_visited_nodes_.SetBit(blk->GetBlockId());
375 }
376 }
377
378 private:
379 void AddEdge(uint32_t source, const HBasicBlock* dest) {
380 reachability_graph_->SetBit(source, dest->GetBlockId());
381 }
382
383 // Union the reachability of 'idx' into 'update_block_idx'. This is done to
384 // implement memoization. In order to improve performance we do this in 4-byte
385 // blocks. Clang should be able to optimize this to larger blocks if possible.
386 void UnionBlock(size_t update_block_idx, size_t idx) {
387 reachability_graph_->UnionRows(update_block_idx, idx);
388 }
389
390 // Single DFS to get connectedness of a single block
391 void CalculateConnectednessOn(const HBasicBlock* const target_block) {
392 const uint32_t target_idx = target_block->GetBlockId();
393 ScopedArenaAllocator connectedness_temps(arena_stack_);
394 // What nodes we have already discovered and either have processed or are
395 // already on the queue.
396 ArenaBitVector discovered(
397 &connectedness_temps, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph);
398 // The work stack. What blocks we still need to process.
399 ScopedArenaVector<const HBasicBlock*> work_stack(
400 connectedness_temps.Adapter(kArenaAllocReachabilityGraph));
401 // Known max size since otherwise we'd have blocks multiple times. Avoids
402 // re-allocation
403 work_stack.reserve(graph_->GetBlocks().size());
404 discovered.SetBit(target_idx);
405 work_stack.push_back(target_block);
406 // Main DFS Loop.
407 while (!work_stack.empty()) {
408 const HBasicBlock* cur = work_stack.back();
409 work_stack.pop_back();
410 // Memoization of previous runs.
411 if (all_visited_nodes_.IsBitSet(cur->GetBlockId())) {
412 DCHECK_NE(target_block, cur);
413 // Already explored from here. Just use that data.
414 UnionBlock(target_idx, cur->GetBlockId());
415 continue;
416 }
417 for (const HBasicBlock* succ : cur->GetSuccessors()) {
418 AddEdge(target_idx, succ);
419 if (!discovered.IsBitSet(succ->GetBlockId())) {
420 work_stack.push_back(succ);
421 discovered.SetBit(succ->GetBlockId());
422 }
423 }
424 }
425 }
426
427 const HGraph* graph_;
428 // The graph's reachability_graph_ on the main allocator.
429 ArenaBitVectorArray* reachability_graph_;
430 ArenaStack* arena_stack_;
431 // An allocator for temporary bit-vectors used by this algorithm. The
432 // 'SetBit,ClearBit' on reachability_graph_ prior to the construction of this
433 // object should be the only allocation on the main allocator so it's safe to
434 // make a sub-allocator here.
435 ScopedArenaAllocator temporaries_;
436 // number of columns
437 const size_t block_size_;
438 // Where we've already completely calculated connectedness.
439 ArenaBitVector all_visited_nodes_;
440 // What we never visited and need to do later
441 ArenaBitVector not_post_order_visited_;
442
443 DISALLOW_COPY_AND_ASSIGN(ReachabilityAnalysisHelper);
444};
445
446void HGraph::ComputeReachabilityInformation() {
447 DCHECK_EQ(reachability_graph_.GetRawData().NumSetBits(), 0u);
448 DCHECK(reachability_graph_.IsExpandable());
449 // Reserve all the bits we'll need. This is the only allocation on the
450 // standard allocator we do here, enabling us to create a new ScopedArena for
451 // use with temporaries.
452 //
453 // reachability_graph_ acts as |N| x |N| graph for PathBetween. Array is
454 // padded so each row starts on an BitVector::kWordBits-bit alignment for
455 // simplicity and performance, allowing us to union blocks together without
456 // going bit-by-bit.
457 reachability_graph_.Resize(blocks_.size(), blocks_.size(), /*clear=*/false);
458 ReachabilityAnalysisHelper helper(this, &reachability_graph_, GetArenaStack());
459 helper.CalculateReachability();
460}
461
462void HGraph::ClearReachabilityInformation() {
463 reachability_graph_.Clear();
464}
465
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100466void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100467 DCHECK(reverse_post_order_.empty());
468 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100469 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100470
Vladimir Marko69d310e2017-10-09 14:12:23 +0100471 // Allocate memory from local ScopedArenaAllocator.
472 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100473 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100474 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100475 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100476 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
477 0u,
478 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100479 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100480 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100481 constexpr size_t kDefaultWorklistSize = 8;
482 worklist.reserve(kDefaultWorklistSize);
483 worklist.push_back(entry_block_);
484
485 while (!worklist.empty()) {
486 HBasicBlock* current = worklist.back();
487 uint32_t current_id = current->GetBlockId();
488 if (successors_visited[current_id] == current->GetSuccessors().size()) {
489 worklist.pop_back();
490 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100491 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100492 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100493
494 // Once all the forward edges have been visited, we know the immediate
495 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100496 if (++visits[successor->GetBlockId()] ==
497 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100498 reverse_post_order_.push_back(successor);
499 worklist.push_back(successor);
500 }
501 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000502 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000503
David Brazdil3f4a5222016-05-06 12:46:21 +0100504 // Check if the graph has back edges not dominated by their respective headers.
505 // If so, we need to update the dominators of those headers and recursively of
506 // their successors. We do that with a fix-point iteration over all blocks.
507 // The algorithm is guaranteed to terminate because it loops only if the sum
508 // of all dominator chains has decreased in the current iteration.
509 bool must_run_fix_point = false;
510 for (HBasicBlock* block : blocks_) {
511 if (block != nullptr &&
512 block->IsLoopHeader() &&
513 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
514 must_run_fix_point = true;
515 break;
516 }
517 }
518 if (must_run_fix_point) {
519 bool update_occurred = true;
520 while (update_occurred) {
521 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100522 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100523 for (HBasicBlock* successor : block->GetSuccessors()) {
524 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
525 }
526 }
527 }
528 }
529
530 // Make sure that there are no remaining blocks whose dominator information
531 // needs to be updated.
532 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100533 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100534 for (HBasicBlock* successor : block->GetSuccessors()) {
535 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
536 }
537 }
538 }
539
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000540 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000541 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100542 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000543 if (!block->IsEntryBlock()) {
544 block->GetDominator()->AddDominatedBlock(block);
545 }
546 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000547}
548
David Brazdilfc6a86a2015-06-26 10:33:45 +0000549HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100550 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000551 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000552 // Use `InsertBetween` to ensure the predecessor index and successor index of
553 // `block` and `successor` are preserved.
554 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000555 return new_block;
556}
557
558void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
559 // Insert a new node between `block` and `successor` to split the
560 // critical edge.
561 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100562 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100563 if (successor->IsLoopHeader()) {
564 // If we split at a back edge boundary, make the new block the back edge.
565 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000566 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100567 info->RemoveBackEdge(block);
568 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100569 }
570 }
571}
572
Santiago Aboy Solanes31242a92022-12-05 14:38:00 +0000573HBasicBlock* HGraph::SplitEdgeAndUpdateRPO(HBasicBlock* block, HBasicBlock* successor) {
574 HBasicBlock* new_block = SplitEdge(block, successor);
575 // In the RPO we have {... , block, ... , successor}. We want to insert `new_block` right after
576 // `block` to have a consistent RPO without recomputing the whole graph's RPO.
577 reverse_post_order_.insert(
578 reverse_post_order_.begin() + IndexOfElement(reverse_post_order_, block) + 1, new_block);
579 return new_block;
580}
581
Artem Serovc73ee372017-07-31 15:08:40 +0100582// Reorder phi inputs to match reordering of the block's predecessors.
583static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
584 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
585 HPhi* phi = it.Current()->AsPhi();
586 HInstruction* first_instr = phi->InputAt(first);
587 HInstruction* second_instr = phi->InputAt(second);
588 phi->ReplaceInput(first_instr, second);
589 phi->ReplaceInput(second_instr, first);
590 }
591}
592
593// Make sure that the first predecessor of a loop header is the incoming block.
594void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
595 DCHECK(header->IsLoopHeader());
596 HLoopInformation* info = header->GetLoopInformation();
597 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
598 HBasicBlock* to_swap = header->GetPredecessors()[0];
599 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
600 HBasicBlock* predecessor = header->GetPredecessors()[pred];
601 if (!info->IsBackEdge(*predecessor)) {
602 header->predecessors_[pred] = to_swap;
603 header->predecessors_[0] = predecessor;
604 FixPhisAfterPredecessorsReodering(header, 0, pred);
605 break;
606 }
607 }
608 }
609}
610
Artem Serov09faaea2017-12-07 14:36:01 +0000611// Transform control flow of the loop to a single preheader format (don't touch the data flow).
612// New_preheader can be already among the header predecessors - this situation will be correctly
613// processed.
614static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
615 HLoopInformation* loop_info = header->GetLoopInformation();
616 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
617 HBasicBlock* predecessor = header->GetPredecessors()[pred];
618 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
619 predecessor->ReplaceSuccessor(header, new_preheader);
620 pred--;
621 }
622 }
623}
624
625// == Before == == After ==
626// _________ _________ _________ _________
627// | B0 | | B1 | (old preheaders) | B0 | | B1 |
628// |=========| |=========| |=========| |=========|
629// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
630// |_________| |_________| |_________| |_________|
631// \ / \ /
632// \ / ___v____________v___
633// \ / (new preheader) | B20 <- B0, B1 |
634// | | |====================|
635// | | | i20 = phi(i0, i1) |
636// | | |____________________|
637// | | |
638// /\ | | /\ /\ | /\
639// / v_______v_________v_______v \ / v___________v_____________v \
640// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
641// | |===========================| | (header) | |===========================| |
642// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
643// | |___________________________| | | |___________________________| |
644// | / \ | | / \ |
645// | ... ... | | ... ... |
646// | _________ _________ | | _________ _________ |
647// | | B2 | | B3 | | | | B2 | | B3 | |
648// | |=========| |=========| | (back edges) | |=========| |=========| |
649// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
650// | |_________| |_________| | | |_________| |_________| |
651// \ / \ / \ / \ /
652// \___/ \___/ \___/ \___/
653//
654void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
655 HLoopInformation* loop_info = header->GetLoopInformation();
656
657 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
658 AddBlock(preheader);
659 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
660
661 // If the old header has no Phis then we only need to fix the control flow.
662 if (header->GetPhis().IsEmpty()) {
663 FixControlForNewSinglePreheader(header, preheader);
664 preheader->AddSuccessor(header);
665 return;
666 }
667
668 // Find the first non-back edge block in the header's predecessors list.
669 size_t first_nonbackedge_pred_pos = 0;
670 bool found = false;
671 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
672 HBasicBlock* predecessor = header->GetPredecessors()[pred];
673 if (!loop_info->IsBackEdge(*predecessor)) {
674 first_nonbackedge_pred_pos = pred;
675 found = true;
676 break;
677 }
678 }
679
680 DCHECK(found);
681
682 // Fix the data-flow.
683 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
684 HPhi* header_phi = it.Current()->AsPhi();
685
686 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
687 header_phi->GetRegNumber(),
688 0,
689 header_phi->GetType());
690 if (header_phi->GetType() == DataType::Type::kReference) {
Santiago Aboy Solanese05bc3e2023-02-20 14:26:23 +0000691 preheader_phi->SetReferenceTypeInfoIfValid(header_phi->GetReferenceTypeInfo());
Artem Serov09faaea2017-12-07 14:36:01 +0000692 }
693 preheader->AddPhi(preheader_phi);
694
695 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
696 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
697 preheader_phi->AddInput(orig_input);
698
699 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
700 input_pos < header_phi->InputCount();
701 input_pos++) {
702 HInstruction* input = header_phi->InputAt(input_pos);
703 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
704
705 if (loop_info->Contains(*pred_block)) {
706 DCHECK(loop_info->IsBackEdge(*pred_block));
707 } else {
708 preheader_phi->AddInput(input);
709 header_phi->RemoveInputAt(input_pos);
710 input_pos--;
711 }
712 }
713 }
714
715 // Fix the control-flow.
716 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
717 preheader->InsertBetween(first_pred, header);
718
719 FixControlForNewSinglePreheader(header, preheader);
720}
721
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100722void HGraph::SimplifyLoop(HBasicBlock* header) {
723 HLoopInformation* info = header->GetLoopInformation();
724
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100725 // Make sure the loop has only one pre header. This simplifies SSA building by having
726 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000727 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
728 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000729 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000730 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000731 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100732 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100733
Artem Serovc73ee372017-07-31 15:08:40 +0100734 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100735
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100736 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000737 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
738 // Called from DeadBlockElimination. Update SuspendCheck pointer.
739 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100740 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100741}
742
David Brazdilffee3d32015-07-06 11:48:53 +0100743void HGraph::ComputeTryBlockInformation() {
744 // Iterate in reverse post order to propagate try membership information from
745 // predecessors to their successors.
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000746 bool graph_has_try_catch = false;
747
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100748 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100749 if (block->IsEntryBlock() || block->IsCatchBlock()) {
750 // Catch blocks after simplification have only exceptional predecessors
751 // and hence are never in tries.
752 continue;
753 }
754
755 // Infer try membership from the first predecessor. Having simplified loops,
756 // the first predecessor can never be a back edge and therefore it must have
757 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100758 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +0000759 DCHECK_IMPLIES(block->IsLoopHeader(),
760 !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100761 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000762 graph_has_try_catch |= try_entry != nullptr;
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000763 if (try_entry != nullptr &&
764 (block->GetTryCatchInformation() == nullptr ||
765 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
766 // We are either setting try block membership for the first time or it
767 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100768 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100769 }
David Brazdilffee3d32015-07-06 11:48:53 +0100770 }
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000771
772 SetHasTryCatch(graph_has_try_catch);
David Brazdilffee3d32015-07-06 11:48:53 +0100773}
774
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100775void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000776// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100777 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000778 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100779 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
780 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
781 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
782 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100783 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000784 if (block->GetSuccessors().size() > 1) {
785 // Only split normal-flow edges. We cannot split exceptional edges as they
786 // are synthesized (approximate real control flow), and we do not need to
787 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000788 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
789 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
790 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100791 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000792 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000793 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
794 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000795 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000796 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100797 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000798 // SplitCriticalEdge could have invalidated the `normal_successors`
799 // ArrayRef. We must re-acquire it.
800 normal_successors = block->GetNormalSuccessors();
801 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
802 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100803 }
804 }
805 }
806 if (block->IsLoopHeader()) {
807 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000808 } else if (!block->IsEntryBlock() &&
809 block->GetFirstInstruction() != nullptr &&
810 block->GetFirstInstruction()->IsSuspendCheck()) {
811 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000812 // a loop got dismantled. Just remove the suspend check.
813 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100814 }
815 }
816}
817
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000818GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100819 // We iterate post order to ensure we visit inner loops before outer loops.
820 // `PopulateRecursive` needs this guarantee to know whether a natural loop
821 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100822 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100823 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100824 if (block->IsCatchBlock()) {
825 // TODO: Dealing with exceptional back edges could be tricky because
826 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000827 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000828 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100829 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000830 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100831 }
832 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000833 return kAnalysisSuccess;
834}
835
836void HLoopInformation::Dump(std::ostream& os) {
837 os << "header: " << header_->GetBlockId() << std::endl;
838 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
839 for (HBasicBlock* block : back_edges_) {
840 os << "back edge: " << block->GetBlockId() << std::endl;
841 }
842 for (HBasicBlock* block : header_->GetPredecessors()) {
843 os << "predecessor: " << block->GetBlockId() << std::endl;
844 }
845 for (uint32_t idx : blocks_.Indexes()) {
846 os << " in loop: " << idx << std::endl;
847 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100848}
849
David Brazdil8d5b8b22015-03-24 10:51:52 +0000850void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000851 // New constants are inserted before the SuspendCheck at the bottom of the
852 // entry block. Note that this method can be called from the graph builder and
853 // the entry block therefore may not end with SuspendCheck->Goto yet.
854 HInstruction* insert_before = nullptr;
855
856 HInstruction* gota = entry_block_->GetLastInstruction();
857 if (gota != nullptr && gota->IsGoto()) {
858 HInstruction* suspend_check = gota->GetPrevious();
859 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
860 insert_before = suspend_check;
861 } else {
862 insert_before = gota;
863 }
864 }
865
866 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000867 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000868 } else {
869 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000870 }
871}
872
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600873HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100874 // For simplicity, don't bother reviving the cached null constant if it is
875 // not null and not in a block. Otherwise, we need to clear the instruction
876 // id and/or any invariants the graph is assuming when adding new instructions.
877 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100878 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100879 cached_null_constant_->SetReferenceTypeInfo(GetInexactObjectRti());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000880 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000881 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000882 if (kIsDebugBuild) {
883 ScopedObjectAccess soa(Thread::Current());
884 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
885 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000886 return cached_null_constant_;
887}
888
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100889HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100890 // For simplicity, don't bother reviving the cached current method if it is
891 // not null and not in a block. Otherwise, we need to clear the instruction
892 // id and/or any invariants the graph is assuming when adding new instructions.
893 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100894 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100895 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600896 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100897 if (entry_block_->GetFirstInstruction() == nullptr) {
898 entry_block_->AddInstruction(cached_current_method_);
899 } else {
900 entry_block_->InsertInstructionBefore(
901 cached_current_method_, entry_block_->GetFirstInstruction());
902 }
903 }
904 return cached_current_method_;
905}
906
Igor Murashkind01745e2017-04-05 16:40:31 -0700907const char* HGraph::GetMethodName() const {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800908 const dex::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
Igor Murashkind01745e2017-04-05 16:40:31 -0700909 return dex_file_.GetMethodName(method_id);
910}
911
912std::string HGraph::PrettyMethod(bool with_signature) const {
913 return dex_file_.PrettyMethod(method_idx_, with_signature);
914}
915
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100916HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000917 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100918 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000919 DCHECK(IsUint<1>(value));
920 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100921 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100922 case DataType::Type::kInt8:
923 case DataType::Type::kUint16:
924 case DataType::Type::kInt16:
925 case DataType::Type::kInt32:
926 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600927 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000928
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100929 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600930 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000931
932 default:
933 LOG(FATAL) << "Unsupported constant type";
934 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000935 }
David Brazdil46e2a392015-03-16 17:31:52 +0000936}
937
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000938void HGraph::CacheFloatConstant(HFloatConstant* constant) {
939 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
940 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
941 cached_float_constants_.Overwrite(value, constant);
942}
943
944void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
945 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
946 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
947 cached_double_constants_.Overwrite(value, constant);
948}
949
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000950void HLoopInformation::Add(HBasicBlock* block) {
951 blocks_.SetBit(block->GetBlockId());
952}
953
David Brazdil46e2a392015-03-16 17:31:52 +0000954void HLoopInformation::Remove(HBasicBlock* block) {
955 blocks_.ClearBit(block->GetBlockId());
956}
957
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100958void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
959 if (blocks_.IsBitSet(block->GetBlockId())) {
960 return;
961 }
962
963 blocks_.SetBit(block->GetBlockId());
964 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100965 if (block->IsLoopHeader()) {
966 // We're visiting loops in post-order, so inner loops must have been
967 // populated already.
968 DCHECK(block->GetLoopInformation()->IsPopulated());
969 if (block->GetLoopInformation()->IsIrreducible()) {
970 contains_irreducible_loop_ = true;
971 }
972 }
Vladimir Marko60584552015-09-03 13:35:12 +0000973 for (HBasicBlock* predecessor : block->GetPredecessors()) {
974 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100975 }
976}
977
David Brazdilc2e8af92016-04-05 17:15:19 +0100978void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
979 size_t block_id = block->GetBlockId();
980
981 // If `block` is in `finalized`, we know its membership in the loop has been
982 // decided and it does not need to be revisited.
983 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000984 return;
985 }
986
David Brazdilc2e8af92016-04-05 17:15:19 +0100987 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000988 if (block->IsLoopHeader()) {
989 // If we hit a loop header in an irreducible loop, we first check if the
990 // pre header of that loop belongs to the currently analyzed loop. If it does,
991 // then we visit the back edges.
992 // Note that we cannot use GetPreHeader, as the loop may have not been populated
993 // yet.
994 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100995 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000996 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000997 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100998 blocks_.SetBit(block_id);
999 finalized->SetBit(block_id);
1000 is_finalized = true;
1001
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001002 HLoopInformation* info = block->GetLoopInformation();
1003 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001004 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001005 }
1006 }
1007 } else {
1008 // Visit all predecessors. If one predecessor is part of the loop, this
1009 // block is also part of this loop.
1010 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001011 PopulateIrreducibleRecursive(predecessor, finalized);
1012 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001013 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +01001014 blocks_.SetBit(block_id);
1015 finalized->SetBit(block_id);
1016 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001017 }
1018 }
1019 }
David Brazdilc2e8af92016-04-05 17:15:19 +01001020
1021 // All predecessors have been recursively visited. Mark finalized if not marked yet.
1022 if (!is_finalized) {
1023 finalized->SetBit(block_id);
1024 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001025}
1026
1027void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +01001028 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001029 // Populate this loop: starting with the back edge, recursively add predecessors
1030 // that are not already part of that loop. Set the header as part of the loop
1031 // to end the recursion.
1032 // This is a recursive implementation of the algorithm described in
1033 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +01001034 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001035 blocks_.SetBit(header_->GetBlockId());
1036 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +01001037
David Brazdil3f4a5222016-05-06 12:46:21 +01001038 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +01001039
1040 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +01001041 // Allocate memory from local ScopedArenaAllocator.
1042 ScopedArenaAllocator allocator(graph->GetArenaStack());
1043 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +01001044 graph->GetBlocks().size(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001045 /* expandable= */ false,
David Brazdilc2e8af92016-04-05 17:15:19 +01001046 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +01001047 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +01001048 // Stop marking blocks at the loop header.
1049 visited.SetBit(header_->GetBlockId());
1050
David Brazdilc2e8af92016-04-05 17:15:19 +01001051 for (HBasicBlock* back_edge : GetBackEdges()) {
1052 PopulateIrreducibleRecursive(back_edge, &visited);
1053 }
1054 } else {
1055 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001056 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001057 }
David Brazdila4b8c212015-05-07 09:59:30 +01001058 }
David Brazdilc2e8af92016-04-05 17:15:19 +01001059
Vladimir Markofd66c502016-04-18 15:37:01 +01001060 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
1061 // When compiling in OSR mode, all loops in the compiled method may be entered
1062 // from the interpreter. We treat this OSR entry point just like an extra entry
1063 // to an irreducible loop, so we need to mark the method's loops as irreducible.
1064 // This does not apply to inlined loops which do not act as OSR entry points.
1065 if (suspend_check_ == nullptr) {
1066 // Just building the graph in OSR mode, this loop is not inlined. We never build an
1067 // inner graph in OSR mode as we can do OSR transition only from the outer method.
1068 is_irreducible_loop = true;
1069 } else {
1070 // Look at the suspend check's environment to determine if the loop was inlined.
1071 DCHECK(suspend_check_->HasEnvironment());
1072 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
1073 is_irreducible_loop = true;
1074 }
1075 }
1076 }
1077 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001078 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +01001079 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +01001080 graph->SetHasIrreducibleLoops(true);
1081 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08001082 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +01001083}
1084
Artem Serov7f4aff62017-06-21 17:02:18 +01001085void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
1086 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
1087 blocks_.Union(&inner_loop->blocks_);
1088 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
1089 if (outer_loop != nullptr) {
1090 outer_loop->PopulateInnerLoopUpwards(this);
1091 }
1092}
1093
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001094HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001095 HBasicBlock* block = header_->GetPredecessors()[0];
1096 DCHECK(irreducible_ || (block == header_->GetDominator()));
1097 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001098}
1099
1100bool HLoopInformation::Contains(const HBasicBlock& block) const {
1101 return blocks_.IsBitSet(block.GetBlockId());
1102}
1103
1104bool HLoopInformation::IsIn(const HLoopInformation& other) const {
1105 return other.blocks_.IsBitSet(header_->GetBlockId());
1106}
1107
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001108bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
1109 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -07001110}
1111
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001112size_t HLoopInformation::GetLifetimeEnd() const {
1113 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001114 for (HBasicBlock* back_edge : GetBackEdges()) {
1115 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001116 }
1117 return last_position;
1118}
1119
David Brazdil3f4a5222016-05-06 12:46:21 +01001120bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
1121 for (HBasicBlock* back_edge : GetBackEdges()) {
1122 DCHECK(back_edge->GetDominator() != nullptr);
1123 if (!header_->Dominates(back_edge)) {
1124 return true;
1125 }
1126 }
1127 return false;
1128}
1129
Anton Shaminf89381f2016-05-16 16:44:13 +06001130bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
1131 for (HBasicBlock* back_edge : GetBackEdges()) {
1132 if (!block->Dominates(back_edge)) {
1133 return false;
1134 }
1135 }
1136 return true;
1137}
1138
David Sehrc757dec2016-11-04 15:48:34 -07001139
1140bool HLoopInformation::HasExitEdge() const {
1141 // Determine if this loop has at least one exit edge.
1142 HBlocksInLoopReversePostOrderIterator it_loop(*this);
1143 for (; !it_loop.Done(); it_loop.Advance()) {
1144 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1145 if (!Contains(*successor)) {
1146 return true;
1147 }
1148 }
1149 }
1150 return false;
1151}
1152
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001153bool HBasicBlock::Dominates(const HBasicBlock* other) const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001154 // Walk up the dominator tree from `other`, to find out if `this`
1155 // is an ancestor.
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001156 const HBasicBlock* current = other;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001157 while (current != nullptr) {
1158 if (current == this) {
1159 return true;
1160 }
1161 current = current->GetDominator();
1162 }
1163 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001164}
1165
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001166static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +01001167 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001168 for (size_t i = 0; i < inputs.size(); ++i) {
1169 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001170 }
1171 // Environment should be created later.
1172 DCHECK(!instruction->HasEnvironment());
1173}
1174
Artem Serovcced8ba2017-07-19 18:18:09 +01001175void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
1176 DCHECK(initial->GetBlock() == this);
1177 InsertPhiAfter(replacement, initial);
1178 initial->ReplaceWith(replacement);
1179 RemovePhi(initial);
1180}
1181
Roland Levillainccc07a92014-09-16 14:48:16 +01001182void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
1183 HInstruction* replacement) {
1184 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -04001185 if (initial->IsControlFlow()) {
1186 // We can only replace a control flow instruction with another control flow instruction.
1187 DCHECK(replacement->IsControlFlow());
1188 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001189 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -04001190 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001191 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +01001192 DCHECK(initial->GetUses().empty());
1193 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -04001194 replacement->SetBlock(this);
1195 replacement->SetId(GetGraph()->GetNextInstructionId());
1196 instructions_.InsertInstructionBefore(replacement, initial);
1197 UpdateInputsUsers(replacement);
1198 } else {
1199 InsertInstructionBefore(replacement, initial);
1200 initial->ReplaceWith(replacement);
1201 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001202 RemoveInstruction(initial);
1203}
1204
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001205static void Add(HInstructionList* instruction_list,
1206 HBasicBlock* block,
1207 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +00001208 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +00001209 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001210 instruction->SetBlock(block);
1211 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001212 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001213 instruction_list->AddInstruction(instruction);
1214}
1215
1216void HBasicBlock::AddInstruction(HInstruction* instruction) {
1217 Add(&instructions_, this, instruction);
1218}
1219
1220void HBasicBlock::AddPhi(HPhi* phi) {
1221 Add(&phis_, this, phi);
1222}
1223
David Brazdilc3d743f2015-04-22 13:40:50 +01001224void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1225 DCHECK(!cursor->IsPhi());
1226 DCHECK(!instruction->IsPhi());
1227 DCHECK_EQ(instruction->GetId(), -1);
1228 DCHECK_NE(cursor->GetId(), -1);
1229 DCHECK_EQ(cursor->GetBlock(), this);
1230 DCHECK(!instruction->IsControlFlow());
1231 instruction->SetBlock(this);
1232 instruction->SetId(GetGraph()->GetNextInstructionId());
1233 UpdateInputsUsers(instruction);
1234 instructions_.InsertInstructionBefore(instruction, cursor);
1235}
1236
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001237void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1238 DCHECK(!cursor->IsPhi());
1239 DCHECK(!instruction->IsPhi());
1240 DCHECK_EQ(instruction->GetId(), -1);
1241 DCHECK_NE(cursor->GetId(), -1);
1242 DCHECK_EQ(cursor->GetBlock(), this);
1243 DCHECK(!instruction->IsControlFlow());
1244 DCHECK(!cursor->IsControlFlow());
1245 instruction->SetBlock(this);
1246 instruction->SetId(GetGraph()->GetNextInstructionId());
1247 UpdateInputsUsers(instruction);
1248 instructions_.InsertInstructionAfter(instruction, cursor);
1249}
1250
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001251void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1252 DCHECK_EQ(phi->GetId(), -1);
1253 DCHECK_NE(cursor->GetId(), -1);
1254 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001255 phi->SetBlock(this);
1256 phi->SetId(GetGraph()->GetNextInstructionId());
1257 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001258 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001259}
1260
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001261static void Remove(HInstructionList* instruction_list,
1262 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001263 HInstruction* instruction,
1264 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001265 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001266 instruction->SetBlock(nullptr);
1267 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001268 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001269 DCHECK(instruction->GetUses().empty());
1270 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001271 RemoveAsUser(instruction);
1272 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001273}
1274
David Brazdil1abb4192015-02-17 18:33:36 +00001275void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001276 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001277 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001278}
1279
David Brazdil1abb4192015-02-17 18:33:36 +00001280void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1281 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001282}
1283
David Brazdilc7508e92015-04-27 13:28:57 +01001284void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1285 if (instruction->IsPhi()) {
1286 RemovePhi(instruction->AsPhi(), ensure_safety);
1287 } else {
1288 RemoveInstruction(instruction, ensure_safety);
1289 }
1290}
1291
Vladimir Marko69d310e2017-10-09 14:12:23 +01001292void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001293 for (size_t i = 0; i < locals.size(); i++) {
1294 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001295 SetRawEnvAt(i, instruction);
1296 if (instruction != nullptr) {
1297 instruction->AddEnvUseAt(this, i);
1298 }
1299 }
1300}
1301
David Brazdiled596192015-01-23 10:39:45 +00001302void HEnvironment::CopyFrom(HEnvironment* env) {
1303 for (size_t i = 0; i < env->Size(); i++) {
1304 HInstruction* instruction = env->GetInstructionAt(i);
1305 SetRawEnvAt(i, instruction);
1306 if (instruction != nullptr) {
1307 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001308 }
David Brazdiled596192015-01-23 10:39:45 +00001309 }
1310}
1311
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001312void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1313 HBasicBlock* loop_header) {
1314 DCHECK(loop_header->IsLoopHeader());
1315 for (size_t i = 0; i < env->Size(); i++) {
1316 HInstruction* instruction = env->GetInstructionAt(i);
1317 SetRawEnvAt(i, instruction);
1318 if (instruction == nullptr) {
1319 continue;
1320 }
1321 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1322 // At the end of the loop pre-header, the corresponding value for instruction
1323 // is the first input of the phi.
1324 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001325 SetRawEnvAt(i, initial);
1326 initial->AddEnvUseAt(this, i);
1327 } else {
1328 instruction->AddEnvUseAt(this, i);
1329 }
1330 }
1331}
1332
David Brazdil1abb4192015-02-17 18:33:36 +00001333void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001334 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1335 HInstruction* user = env_use.GetInstruction();
1336 auto before_env_use_node = env_use.GetBeforeUseNode();
1337 user->env_uses_.erase_after(before_env_use_node);
1338 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001339}
1340
Artem Serovca210e32017-12-15 13:43:20 +00001341void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1342 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1343 HInstruction* orig_instr = env_use_record.GetInstruction();
1344
1345 DCHECK(orig_instr != replacement);
1346
1347 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1348 // Note: fixup_end remains valid across splice_after().
1349 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1350 : ++replacement->env_uses_.begin();
1351 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1352 env_use_record.GetInstruction()->env_uses_,
1353 before_use_node);
1354 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1355 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1356}
1357
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001358std::ostream& HInstruction::Dump(std::ostream& os, bool dump_args) {
Vladimir Markodac82392021-05-10 15:44:24 +00001359 // Note: Handle the case where the instruction has been removed from
1360 // the graph to support debugging output for failed gtests.
1361 HGraph* graph = (GetBlock() != nullptr) ? GetBlock()->GetGraph() : nullptr;
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001362 HGraphVisualizer::DumpInstruction(&os, graph, this);
1363 if (dump_args) {
1364 // Allocate memory from local ScopedArenaAllocator.
Vladimir Markodac82392021-05-10 15:44:24 +00001365 std::optional<MallocArenaPool> local_arena_pool;
1366 std::optional<ArenaStack> local_arena_stack;
1367 if (UNLIKELY(graph == nullptr)) {
1368 local_arena_pool.emplace();
1369 local_arena_stack.emplace(&local_arena_pool.value());
1370 }
1371 ScopedArenaAllocator allocator(
1372 graph != nullptr ? graph->GetArenaStack() : &local_arena_stack.value());
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001373 // Instructions that we already visited. We print each instruction only once.
Vladimir Markodac82392021-05-10 15:44:24 +00001374 ArenaBitVector visited(&allocator,
1375 (graph != nullptr) ? graph->GetCurrentInstructionId() : 0u,
1376 /* expandable= */ (graph == nullptr),
1377 kArenaAllocMisc);
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001378 visited.ClearAllBits();
1379 visited.SetBit(GetId());
1380 // Keep a queue of instructions with their indentations.
1381 ScopedArenaDeque<std::pair<HInstruction*, size_t>> queue(allocator.Adapter(kArenaAllocMisc));
1382 auto add_args = [&queue](HInstruction* instruction, size_t indentation) {
1383 for (HInstruction* arg : ReverseRange(instruction->GetInputs())) {
1384 queue.emplace_front(arg, indentation);
1385 }
1386 };
1387 add_args(this, /*indentation=*/ 1u);
1388 while (!queue.empty()) {
1389 HInstruction* instruction;
1390 size_t indentation;
1391 std::tie(instruction, indentation) = queue.front();
1392 queue.pop_front();
1393 if (!visited.IsBitSet(instruction->GetId())) {
1394 visited.SetBit(instruction->GetId());
1395 os << '\n';
1396 for (size_t i = 0; i != indentation; ++i) {
1397 os << " ";
1398 }
1399 HGraphVisualizer::DumpInstruction(&os, graph, instruction);
1400 add_args(instruction, indentation + 1u);
1401 }
1402 }
1403 }
1404 return os;
1405}
1406
Calin Juravle77520bc2015-01-12 18:45:46 +00001407HInstruction* HInstruction::GetNextDisregardingMoves() const {
1408 HInstruction* next = GetNext();
1409 while (next != nullptr && next->IsParallelMove()) {
1410 next = next->GetNext();
1411 }
1412 return next;
1413}
1414
1415HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1416 HInstruction* previous = GetPrevious();
1417 while (previous != nullptr && previous->IsParallelMove()) {
1418 previous = previous->GetPrevious();
1419 }
1420 return previous;
1421}
1422
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001423void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001424 if (first_instruction_ == nullptr) {
1425 DCHECK(last_instruction_ == nullptr);
1426 first_instruction_ = last_instruction_ = instruction;
1427 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001428 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001429 last_instruction_->next_ = instruction;
1430 instruction->previous_ = last_instruction_;
1431 last_instruction_ = instruction;
1432 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001433}
1434
David Brazdilc3d743f2015-04-22 13:40:50 +01001435void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1436 DCHECK(Contains(cursor));
1437 if (cursor == first_instruction_) {
1438 cursor->previous_ = instruction;
1439 instruction->next_ = cursor;
1440 first_instruction_ = instruction;
1441 } else {
1442 instruction->previous_ = cursor->previous_;
1443 instruction->next_ = cursor;
1444 cursor->previous_ = instruction;
1445 instruction->previous_->next_ = instruction;
1446 }
1447}
1448
1449void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1450 DCHECK(Contains(cursor));
1451 if (cursor == last_instruction_) {
1452 cursor->next_ = instruction;
1453 instruction->previous_ = cursor;
1454 last_instruction_ = instruction;
1455 } else {
1456 instruction->next_ = cursor->next_;
1457 instruction->previous_ = cursor;
1458 cursor->next_ = instruction;
1459 instruction->next_->previous_ = instruction;
1460 }
1461}
1462
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001463void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1464 if (instruction->previous_ != nullptr) {
1465 instruction->previous_->next_ = instruction->next_;
1466 }
1467 if (instruction->next_ != nullptr) {
1468 instruction->next_->previous_ = instruction->previous_;
1469 }
1470 if (instruction == first_instruction_) {
1471 first_instruction_ = instruction->next_;
1472 }
1473 if (instruction == last_instruction_) {
1474 last_instruction_ = instruction->previous_;
1475 }
1476}
1477
Roland Levillain6b469232014-09-25 10:10:38 +01001478bool HInstructionList::Contains(HInstruction* instruction) const {
1479 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1480 if (it.Current() == instruction) {
1481 return true;
1482 }
1483 }
1484 return false;
1485}
1486
Roland Levillainccc07a92014-09-16 14:48:16 +01001487bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1488 const HInstruction* instruction2) const {
1489 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1490 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1491 if (it.Current() == instruction1) {
1492 return true;
1493 }
1494 if (it.Current() == instruction2) {
1495 return false;
1496 }
1497 }
1498 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001499 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001500}
1501
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001502bool HInstruction::Dominates(HInstruction* other_instruction) const {
1503 return other_instruction == this || StrictlyDominates(other_instruction);
1504}
1505
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001506bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001507 if (other_instruction == this) {
1508 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001509 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001510 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001511 HBasicBlock* block = GetBlock();
1512 HBasicBlock* other_block = other_instruction->GetBlock();
1513 if (block != other_block) {
1514 return GetBlock()->Dominates(other_instruction->GetBlock());
1515 } else {
1516 // If both instructions are in the same block, ensure this
1517 // instruction comes before `other_instruction`.
1518 if (IsPhi()) {
1519 if (!other_instruction->IsPhi()) {
1520 // Phis appear before non phi-instructions so this instruction
1521 // dominates `other_instruction`.
1522 return true;
1523 } else {
1524 // There is no order among phis.
1525 LOG(FATAL) << "There is no dominance between phis of a same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001526 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001527 }
1528 } else {
1529 // `this` is not a phi.
1530 if (other_instruction->IsPhi()) {
1531 // Phis appear before non phi-instructions so this instruction
1532 // does not dominate `other_instruction`.
1533 return false;
1534 } else {
1535 // Check whether this instruction comes before
1536 // `other_instruction` in the instruction list.
1537 return block->GetInstructions().FoundBefore(this, other_instruction);
1538 }
1539 }
1540 }
1541}
1542
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001543void HInstruction::RemoveEnvironment() {
1544 RemoveEnvironmentUses(this);
1545 environment_ = nullptr;
1546}
1547
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001548void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001549 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001550 // Note: fixup_end remains valid across splice_after().
1551 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1552 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1553 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001554
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001555 // Note: env_fixup_end remains valid across splice_after().
1556 auto env_fixup_end =
1557 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1558 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1559 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001560
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001561 DCHECK(uses_.empty());
1562 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001563}
1564
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001565void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator,
1566 HInstruction* replacement,
1567 bool strictly_dominated) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001568 const HUseList<HInstruction*>& uses = GetUses();
1569 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1570 HInstruction* user = it->GetUser();
1571 size_t index = it->GetIndex();
1572 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1573 ++it;
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001574 const bool dominated =
1575 strictly_dominated ? dominator->StrictlyDominates(user) : dominator->Dominates(user);
1576
1577 if (dominated) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001578 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001579 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1580 // If the input flows from a block dominated by `dominator`, we can replace it.
1581 // We do not perform this for catch phis as we don't have control flow support
1582 // for their inputs.
1583 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1584 HBasicBlock* predecessor = predecessors[index];
1585 if (dominator->GetBlock()->Dominates(predecessor)) {
1586 user->ReplaceInput(replacement, index);
1587 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001588 }
1589 }
1590}
1591
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001592void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1593 const HUseList<HEnvironment*>& uses = GetEnvUses();
1594 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1595 HEnvironment* user = it->GetUser();
1596 size_t index = it->GetIndex();
1597 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1598 ++it;
1599 if (dominator->StrictlyDominates(user->GetHolder())) {
1600 user->ReplaceInput(replacement, index);
1601 }
1602 }
1603}
1604
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001605void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001606 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001607 if (input_use.GetInstruction() == replacement) {
1608 // Nothing to do.
1609 return;
1610 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001611 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001612 // Note: fixup_end remains valid across splice_after().
1613 auto fixup_end =
1614 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1615 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1616 input_use.GetInstruction()->uses_,
1617 before_use_node);
1618 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1619 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001620}
1621
Nicolas Geoffray39468442014-09-02 15:17:15 +01001622size_t HInstruction::EnvironmentSize() const {
1623 return HasEnvironment() ? environment_->Size() : 0;
1624}
1625
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001626void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001627 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001628 inputs_.push_back(HUserRecord<HInstruction*>(input));
1629 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001630}
1631
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001632void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1633 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1634 input->AddUseAt(this, index);
1635 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1636 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1637 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1638 inputs_[i].GetUseNode()->SetIndex(i);
1639 }
1640}
1641
1642void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001643 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001644 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001645 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1646 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1647 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1648 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001649 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001650}
1651
Igor Murashkind01745e2017-04-05 16:40:31 -07001652void HVariableInputSizeInstruction::RemoveAllInputs() {
1653 RemoveAsUserOfAllInputs();
1654 DCHECK(!HasNonEnvironmentUses());
1655
1656 inputs_.clear();
1657 DCHECK_EQ(0u, InputCount());
1658}
1659
Igor Murashkin6ef45672017-08-08 13:59:55 -07001660size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001661 DCHECK(instruction->GetBlock() != nullptr);
1662 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001663 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001664
Igor Murashkin6ef45672017-08-08 13:59:55 -07001665 // Return how many instructions were removed for statistic purposes.
1666 size_t remove_count = 0;
1667
Igor Murashkind01745e2017-04-05 16:40:31 -07001668 // Efficient implementation that simultaneously (in one pass):
1669 // * Scans the uses list for all constructor fences.
1670 // * Deletes that constructor fence from the uses list of `instruction`.
1671 // * Deletes `instruction` from the constructor fence's inputs.
1672 // * Deletes the constructor fence if it now has 0 inputs.
1673
1674 const HUseList<HInstruction*>& uses = instruction->GetUses();
1675 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1676 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1677 const HUseListNode<HInstruction*>& use_node = *it;
1678 HInstruction* const use_instruction = use_node.GetUser();
1679
1680 // Advance the iterator immediately once we fetch the use_node.
1681 // Warning: If the input is removed, the current iterator becomes invalid.
1682 ++it;
1683
1684 if (use_instruction->IsConstructorFence()) {
1685 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1686 size_t input_index = use_node.GetIndex();
1687
1688 // Process the candidate instruction for removal
1689 // from the graph.
1690
1691 // Constructor fence instructions are never
1692 // used by other instructions.
1693 //
1694 // If we wanted to make this more generic, it
1695 // could be a runtime if statement.
1696 DCHECK(!ctor_fence->HasUses());
1697
1698 // A constructor fence's return type is "kPrimVoid"
1699 // and therefore it can't have any environment uses.
1700 DCHECK(!ctor_fence->HasEnvironmentUses());
1701
1702 // Remove the inputs first, otherwise removing the instruction
1703 // will try to remove its uses while we are already removing uses
1704 // and this operation will fail.
1705 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1706
1707 // Removing the input will also remove the `use_node`.
1708 // (Do not look at `use_node` after this, it will be a dangling reference).
1709 ctor_fence->RemoveInputAt(input_index);
1710
1711 // Once all inputs are removed, the fence is considered dead and
1712 // is removed.
1713 if (ctor_fence->InputCount() == 0u) {
1714 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001715 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001716 }
1717 }
1718 }
1719
1720 if (kIsDebugBuild) {
1721 // Post-condition checks:
1722 // * None of the uses of `instruction` are a constructor fence.
1723 // * The `instruction` itself did not get removed from a block.
1724 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1725 CHECK(!use_node.GetUser()->IsConstructorFence());
1726 }
1727 CHECK(instruction->GetBlock() != nullptr);
1728 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001729
1730 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001731}
1732
Igor Murashkindd018df2017-08-09 10:38:31 -07001733void HConstructorFence::Merge(HConstructorFence* other) {
1734 // Do not delete yourself from the graph.
1735 DCHECK(this != other);
1736 // Don't try to merge with an instruction not associated with a block.
1737 DCHECK(other->GetBlock() != nullptr);
1738 // A constructor fence's return type is "kPrimVoid"
1739 // and therefore it cannot have any environment uses.
1740 DCHECK(!other->HasEnvironmentUses());
1741
1742 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1743 // Check if `haystack` has `needle` as any of its inputs.
1744 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1745 if (haystack->InputAt(input_count) == needle) {
1746 return true;
1747 }
1748 }
1749 return false;
1750 };
1751
1752 // Add any inputs from `other` into `this` if it wasn't already an input.
1753 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1754 HInstruction* other_input = other->InputAt(input_count);
1755 if (!has_input(this, other_input)) {
1756 AddInput(other_input);
1757 }
1758 }
1759
1760 other->GetBlock()->RemoveInstruction(other);
1761}
1762
1763HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001764 HInstruction* new_instance_inst = GetPrevious();
1765 // Check if the immediately preceding instruction is a new-instance/new-array.
1766 // Otherwise this fence is for protecting final fields.
1767 if (new_instance_inst != nullptr &&
1768 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001769 if (ignore_inputs) {
1770 // If inputs are ignored, simply check if the predecessor is
1771 // *any* HNewInstance/HNewArray.
1772 //
1773 // Inputs are normally only ignored for prepare_for_register_allocation,
1774 // at which point *any* prior HNewInstance/Array can be considered
1775 // associated.
1776 return new_instance_inst;
1777 } else {
1778 // Normal case: There must be exactly 1 input and the previous instruction
1779 // must be that input.
1780 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1781 return new_instance_inst;
1782 }
1783 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001784 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001785 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001786}
1787
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001788#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001789void H##name::Accept(HGraphVisitor* visitor) { \
1790 visitor->Visit##name(this); \
1791}
1792
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001793FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001794
1795#undef DEFINE_ACCEPT
1796
1797void HGraphVisitor::VisitInsertionOrder() {
Alex Light210a78d2020-11-30 16:58:05 -08001798 for (HBasicBlock* block : graph_->GetActiveBlocks()) {
1799 VisitBasicBlock(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001800 }
1801}
1802
Roland Levillain633021e2014-10-01 14:12:25 +01001803void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001804 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1805 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001806 }
1807}
1808
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001809void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001810 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001811 it.Current()->Accept(this);
1812 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001813 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001814 it.Current()->Accept(this);
1815 }
1816}
1817
Mark Mendelle82549b2015-05-06 10:55:34 -04001818HConstant* HTypeConversion::TryStaticEvaluation() const {
1819 HGraph* graph = GetBlock()->GetGraph();
1820 if (GetInput()->IsIntConstant()) {
1821 int32_t value = GetInput()->AsIntConstant()->GetValue();
1822 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001823 case DataType::Type::kInt8:
1824 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1825 case DataType::Type::kUint8:
1826 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1827 case DataType::Type::kInt16:
1828 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1829 case DataType::Type::kUint16:
1830 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001831 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001832 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001833 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001834 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001835 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001836 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001837 default:
1838 return nullptr;
1839 }
1840 } else if (GetInput()->IsLongConstant()) {
1841 int64_t value = GetInput()->AsLongConstant()->GetValue();
1842 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001843 case DataType::Type::kInt8:
1844 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1845 case DataType::Type::kUint8:
1846 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1847 case DataType::Type::kInt16:
1848 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1849 case DataType::Type::kUint16:
1850 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001851 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001852 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001853 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001854 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001855 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001856 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001857 default:
1858 return nullptr;
1859 }
1860 } else if (GetInput()->IsFloatConstant()) {
1861 float value = GetInput()->AsFloatConstant()->GetValue();
1862 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001863 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001864 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001865 return graph->GetIntConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001866 if (value >= static_cast<float>(kPrimIntMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001867 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001868 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001869 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1870 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001871 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001872 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001873 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001874 if (value >= static_cast<float>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001875 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001876 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001877 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1878 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001879 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001880 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001881 default:
1882 return nullptr;
1883 }
1884 } else if (GetInput()->IsDoubleConstant()) {
1885 double value = GetInput()->AsDoubleConstant()->GetValue();
1886 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001887 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001888 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001889 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001890 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001891 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001892 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001893 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1894 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001895 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001896 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001897 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001898 if (value >= static_cast<double>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001899 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001900 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001901 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1902 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001903 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001904 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001905 default:
1906 return nullptr;
1907 }
1908 }
1909 return nullptr;
1910}
1911
Roland Levillain9240d6a2014-10-20 16:47:04 +01001912HConstant* HUnaryOperation::TryStaticEvaluation() const {
1913 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001914 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001915 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001916 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001917 } else if (kEnableFloatingPointStaticEvaluation) {
1918 if (GetInput()->IsFloatConstant()) {
1919 return Evaluate(GetInput()->AsFloatConstant());
1920 } else if (GetInput()->IsDoubleConstant()) {
1921 return Evaluate(GetInput()->AsDoubleConstant());
1922 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001923 }
1924 return nullptr;
1925}
1926
1927HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001928 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1929 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001930 } else if (GetLeft()->IsLongConstant()) {
1931 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001932 // The binop(long, int) case is only valid for shifts and rotations.
1933 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001934 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1935 } else if (GetRight()->IsLongConstant()) {
1936 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001937 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001938 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001939 // The binop(null, null) case is only valid for equal and not-equal conditions.
1940 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001941 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001942 } else if (kEnableFloatingPointStaticEvaluation) {
1943 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1944 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1945 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1946 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1947 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001948 }
1949 return nullptr;
1950}
Dave Allison20dfc792014-06-16 20:44:29 -07001951
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001952HConstant* HBinaryOperation::GetConstantRight() const {
1953 if (GetRight()->IsConstant()) {
1954 return GetRight()->AsConstant();
1955 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1956 return GetLeft()->AsConstant();
1957 } else {
1958 return nullptr;
1959 }
1960}
1961
1962// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001963// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001964HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1965 HInstruction* most_constant_right = GetConstantRight();
1966 if (most_constant_right == nullptr) {
1967 return nullptr;
1968 } else if (most_constant_right == GetLeft()) {
1969 return GetRight();
1970 } else {
1971 return GetLeft();
1972 }
1973}
1974
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001975std::ostream& operator<<(std::ostream& os, ComparisonBias rhs) {
1976 // TODO: Replace with auto-generated operator<<.
Roland Levillain31dd3d62016-02-16 12:21:02 +00001977 switch (rhs) {
1978 case ComparisonBias::kNoBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001979 return os << "none";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001980 case ComparisonBias::kGtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001981 return os << "gt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001982 case ComparisonBias::kLtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001983 return os << "lt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001984 default:
1985 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1986 UNREACHABLE();
1987 }
1988}
1989
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001990bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1991 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001992}
1993
Vladimir Marko372f10e2016-05-17 16:30:10 +01001994bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001995 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001996 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001997 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001998 HConstInputsRef inputs = GetInputs();
1999 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01002000 if (inputs.size() != other_inputs.size()) return false;
2001 for (size_t i = 0; i != inputs.size(); ++i) {
2002 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01002003 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01002004
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01002005 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01002006 return true;
2007}
2008
Vladimir Marko9974e3c2020-06-10 16:27:06 +01002009std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002010#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
2011 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01002012 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002013 default:
2014 os << "Unknown instruction kind " << static_cast<int>(rhs);
2015 break;
2016 }
2017#undef DECLARE_CASE
2018 return os;
2019}
2020
Alex Lightdc281e72021-01-06 12:35:31 -08002021std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs) {
2022 // TODO Really this should be const but that would require const-ifying
2023 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
2024 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ false);
2025}
2026
2027std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs) {
2028 // TODO Really this should be const but that would require const-ifying
2029 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
2030 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ true);
2031}
2032
2033std::ostream& operator<<(std::ostream& os, const HInstruction& rhs) {
2034 return os << rhs.DumpWithoutArgs();
2035}
2036
2037std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst) {
2038 os << "Instructions[";
2039 bool first = true;
2040 for (const auto& hi : lst) {
2041 if (!first) {
2042 os << ", ";
2043 }
2044 first = false;
2045 os << hi.GetUser()->DebugName() << "[id: " << hi.GetUser()->GetId()
2046 << ", blk: " << hi.GetUser()->GetBlock()->GetBlockId() << "]@" << hi.GetIndex();
2047 }
2048 os << "]";
2049 return os;
2050}
2051
2052std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst) {
2053 os << "Environments[";
2054 bool first = true;
2055 for (const auto& hi : lst) {
2056 if (!first) {
2057 os << ", ";
2058 }
2059 first = false;
2060 os << *hi.GetUser()->GetHolder() << "@" << hi.GetIndex();
2061 }
2062 os << "]";
2063 return os;
2064}
2065
2066std::ostream& HGraph::Dump(std::ostream& os,
Nicolas Geoffray22df3e02022-01-10 09:31:57 +00002067 CodeGenerator* codegen,
Alex Lightdc281e72021-01-06 12:35:31 -08002068 std::optional<std::reference_wrapper<const BlockNamer>> namer) {
Nicolas Geoffray22df3e02022-01-10 09:31:57 +00002069 HGraphVisualizer vis(&os, this, codegen, namer);
Alex Lightdc281e72021-01-06 12:35:31 -08002070 vis.DumpGraphDebug();
2071 return os;
2072}
2073
Alexandre Rames22aa54b2016-10-18 09:32:29 +01002074void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
2075 if (do_checks) {
2076 DCHECK(!IsPhi());
2077 DCHECK(!IsControlFlow());
2078 DCHECK(CanBeMoved() ||
2079 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
2080 IsShouldDeoptimizeFlag());
2081 DCHECK(!cursor->IsPhi());
2082 }
David Brazdild6c205e2016-06-07 14:20:52 +01002083
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002084 next_->previous_ = previous_;
2085 if (previous_ != nullptr) {
2086 previous_->next_ = next_;
2087 }
2088 if (block_->instructions_.first_instruction_ == this) {
2089 block_->instructions_.first_instruction_ = next_;
2090 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002091 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002092
2093 previous_ = cursor->previous_;
2094 if (previous_ != nullptr) {
2095 previous_->next_ = this;
2096 }
2097 next_ = cursor;
2098 cursor->previous_ = this;
2099 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002100
2101 if (block_->instructions_.first_instruction_ == cursor) {
2102 block_->instructions_.first_instruction_ = this;
2103 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002104}
2105
Vladimir Markofb337ea2015-11-25 15:25:10 +00002106void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
2107 DCHECK(!CanThrow());
2108 DCHECK(!HasSideEffects());
2109 DCHECK(!HasEnvironmentUses());
2110 DCHECK(HasNonEnvironmentUses());
2111 DCHECK(!IsPhi()); // Makes no sense for Phi.
2112 DCHECK_EQ(InputCount(), 0u);
2113
2114 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01002115 auto uses_it = GetUses().begin();
2116 auto uses_end = GetUses().end();
2117 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
2118 ++uses_it;
2119 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
2120 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00002121 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002122 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00002123 // This instruction has uses in two or more blocks. Find the common dominator.
2124 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01002125 for (; uses_it != uses_end; ++uses_it) {
2126 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00002127 }
2128 target_block = finder.Get();
2129 DCHECK(target_block != nullptr);
2130 }
2131 // Move to the first dominator not in a loop.
2132 while (target_block->IsInLoop()) {
2133 target_block = target_block->GetDominator();
2134 DCHECK(target_block != nullptr);
2135 }
2136
2137 // Find insertion position.
2138 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01002139 for (const HUseListNode<HInstruction*>& use : GetUses()) {
2140 if (use.GetUser()->GetBlock() == target_block &&
2141 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
2142 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00002143 }
2144 }
2145 if (insert_pos == nullptr) {
2146 // No user in `target_block`, insert before the control flow instruction.
2147 insert_pos = target_block->GetLastInstruction();
2148 DCHECK(insert_pos->IsControlFlow());
2149 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
2150 if (insert_pos->IsIf()) {
2151 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
2152 if (if_input == insert_pos->GetPrevious()) {
2153 insert_pos = if_input;
2154 }
2155 }
2156 }
2157 MoveBefore(insert_pos);
2158}
2159
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +01002160HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor, bool require_graph_not_in_ssa_form) {
2161 DCHECK_IMPLIES(require_graph_not_in_ssa_form, !graph_->IsInSsaForm())
2162 << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00002163 DCHECK_EQ(cursor->GetBlock(), this);
2164
Vladimir Markoca6fff82017-10-03 14:49:14 +01002165 HBasicBlock* new_block =
2166 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002167 new_block->instructions_.first_instruction_ = cursor;
2168 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2169 instructions_.last_instruction_ = cursor->previous_;
2170 if (cursor->previous_ == nullptr) {
2171 instructions_.first_instruction_ = nullptr;
2172 } else {
2173 cursor->previous_->next_ = nullptr;
2174 cursor->previous_ = nullptr;
2175 }
2176
2177 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002178 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00002179
Vladimir Marko60584552015-09-03 13:35:12 +00002180 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002181 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00002182 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002183 new_block->successors_.swap(successors_);
2184 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002185 AddSuccessor(new_block);
2186
David Brazdil56e1acc2015-06-30 15:41:36 +01002187 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00002188 return new_block;
2189}
2190
David Brazdild7558da2015-09-22 13:04:14 +01002191HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00002192 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01002193 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
2194
Vladimir Markoca6fff82017-10-03 14:49:14 +01002195 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01002196
2197 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01002198 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
2199 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002200 new_block->predecessors_.swap(predecessors_);
2201 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01002202 AddPredecessor(new_block);
2203
2204 GetGraph()->AddBlock(new_block);
2205 return new_block;
2206}
2207
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002208HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
2209 DCHECK_EQ(cursor->GetBlock(), this);
2210
Vladimir Markoca6fff82017-10-03 14:49:14 +01002211 HBasicBlock* new_block =
2212 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002213 new_block->instructions_.first_instruction_ = cursor;
2214 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2215 instructions_.last_instruction_ = cursor->previous_;
2216 if (cursor->previous_ == nullptr) {
2217 instructions_.first_instruction_ = nullptr;
2218 } else {
2219 cursor->previous_->next_ = nullptr;
2220 cursor->previous_ = nullptr;
2221 }
2222
2223 new_block->instructions_.SetBlockOfInstructions(new_block);
2224
2225 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002226 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2227 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002228 new_block->successors_.swap(successors_);
2229 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002230
2231 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2232 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002233 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002234 new_block->dominated_blocks_.swap(dominated_blocks_);
2235 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002236 return new_block;
2237}
2238
2239HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002240 DCHECK(!cursor->IsControlFlow());
2241 DCHECK_NE(instructions_.last_instruction_, cursor);
2242 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002243
Vladimir Markoca6fff82017-10-03 14:49:14 +01002244 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002245 new_block->instructions_.first_instruction_ = cursor->GetNext();
2246 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2247 cursor->next_->previous_ = nullptr;
2248 cursor->next_ = nullptr;
2249 instructions_.last_instruction_ = cursor;
2250
2251 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002252 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002253 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002254 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002255 new_block->successors_.swap(successors_);
2256 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002257
Vladimir Marko60584552015-09-03 13:35:12 +00002258 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002260 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002261 new_block->dominated_blocks_.swap(dominated_blocks_);
2262 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002263 return new_block;
2264}
2265
David Brazdilec16f792015-08-19 15:04:01 +01002266const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01002267 if (EndsWithTryBoundary()) {
2268 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
2269 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01002270 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01002271 return try_boundary;
2272 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002273 DCHECK(IsTryBlock());
2274 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01002275 return nullptr;
2276 }
David Brazdilec16f792015-08-19 15:04:01 +01002277 } else if (IsTryBlock()) {
2278 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01002279 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002280 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01002281 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00002282}
2283
Aart Bik75ff2c92018-04-21 01:28:11 +00002284bool HBasicBlock::HasThrowingInstructions() const {
2285 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2286 if (it.Current()->CanThrow()) {
2287 return true;
2288 }
2289 }
2290 return false;
2291}
2292
David Brazdilfc6a86a2015-06-26 10:33:45 +00002293static bool HasOnlyOneInstruction(const HBasicBlock& block) {
2294 return block.GetPhis().IsEmpty()
2295 && !block.GetInstructions().IsEmpty()
2296 && block.GetFirstInstruction() == block.GetLastInstruction();
2297}
2298
David Brazdil46e2a392015-03-16 17:31:52 +00002299bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00002300 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
2301}
2302
Mads Ager16e52892017-07-14 13:11:37 +02002303bool HBasicBlock::IsSingleReturn() const {
2304 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
2305}
2306
Mingyao Yang46721ef2017-10-05 14:45:17 -07002307bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
2308 return (GetFirstInstruction() == GetLastInstruction()) &&
2309 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2310}
2311
David Brazdilfc6a86a2015-06-26 10:33:45 +00002312bool HBasicBlock::IsSingleTryBoundary() const {
2313 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00002314}
2315
David Brazdil8d5b8b22015-03-24 10:51:52 +00002316bool HBasicBlock::EndsWithControlFlowInstruction() const {
2317 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
2318}
2319
Aart Bik4dc09e72018-05-11 14:40:31 -07002320bool HBasicBlock::EndsWithReturn() const {
2321 return !GetInstructions().IsEmpty() &&
2322 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2323}
2324
David Brazdilb2bd1c52015-03-25 11:17:37 +00002325bool HBasicBlock::EndsWithIf() const {
2326 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2327}
2328
David Brazdilffee3d32015-07-06 11:48:53 +01002329bool HBasicBlock::EndsWithTryBoundary() const {
2330 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2331}
2332
David Brazdilb2bd1c52015-03-25 11:17:37 +00002333bool HBasicBlock::HasSinglePhi() const {
2334 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2335}
2336
David Brazdild26a4112015-11-10 11:07:31 +00002337ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2338 if (EndsWithTryBoundary()) {
2339 // The normal-flow successor of HTryBoundary is always stored at index zero.
2340 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2341 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2342 } else {
2343 // All successors of blocks not ending with TryBoundary are normal.
2344 return ArrayRef<HBasicBlock* const>(successors_);
2345 }
2346}
2347
2348ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2349 if (EndsWithTryBoundary()) {
2350 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2351 } else {
2352 // Blocks not ending with TryBoundary do not have exceptional successors.
2353 return ArrayRef<HBasicBlock* const>();
2354 }
2355}
2356
David Brazdilffee3d32015-07-06 11:48:53 +01002357bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002358 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2359 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2360
2361 size_t length = handlers1.size();
2362 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002363 return false;
2364 }
2365
David Brazdilb618ade2015-07-29 10:31:29 +01002366 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002367 for (size_t i = 0; i < length; ++i) {
2368 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002369 return false;
2370 }
2371 }
2372 return true;
2373}
2374
David Brazdil2d7352b2015-04-20 14:52:42 +01002375size_t HInstructionList::CountSize() const {
2376 size_t size = 0;
2377 HInstruction* current = first_instruction_;
2378 for (; current != nullptr; current = current->GetNext()) {
2379 size++;
2380 }
2381 return size;
2382}
2383
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002384void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2385 for (HInstruction* current = first_instruction_;
2386 current != nullptr;
2387 current = current->GetNext()) {
2388 current->SetBlock(block);
2389 }
2390}
2391
2392void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2393 DCHECK(Contains(cursor));
2394 if (!instruction_list.IsEmpty()) {
2395 if (cursor == last_instruction_) {
2396 last_instruction_ = instruction_list.last_instruction_;
2397 } else {
2398 cursor->next_->previous_ = instruction_list.last_instruction_;
2399 }
2400 instruction_list.last_instruction_->next_ = cursor->next_;
2401 cursor->next_ = instruction_list.first_instruction_;
2402 instruction_list.first_instruction_->previous_ = cursor;
2403 }
2404}
2405
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002406void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2407 DCHECK(Contains(cursor));
2408 if (!instruction_list.IsEmpty()) {
2409 if (cursor == first_instruction_) {
2410 first_instruction_ = instruction_list.first_instruction_;
2411 } else {
2412 cursor->previous_->next_ = instruction_list.first_instruction_;
2413 }
2414 instruction_list.last_instruction_->next_ = cursor;
2415 instruction_list.first_instruction_->previous_ = cursor->previous_;
2416 cursor->previous_ = instruction_list.last_instruction_;
2417 }
2418}
2419
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002420void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002421 if (IsEmpty()) {
2422 first_instruction_ = instruction_list.first_instruction_;
2423 last_instruction_ = instruction_list.last_instruction_;
2424 } else {
2425 AddAfter(last_instruction_, instruction_list);
2426 }
2427}
2428
David Brazdil2d7352b2015-04-20 14:52:42 +01002429void HBasicBlock::DisconnectAndDelete() {
2430 // Dominators must be removed after all the blocks they dominate. This way
2431 // a loop header is removed last, a requirement for correct loop information
2432 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002433 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002434
David Brazdil9eeebf62016-03-24 11:18:15 +00002435 // The following steps gradually remove the block from all its dependants in
2436 // post order (b/27683071).
2437
2438 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2439 // We need to do this before step (4) which destroys the predecessor list.
2440 HBasicBlock* loop_update_start = this;
2441 if (IsLoopHeader()) {
2442 HLoopInformation* loop_info = GetLoopInformation();
2443 // All other blocks in this loop should have been removed because the header
2444 // was their dominator.
2445 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2446 DCHECK(!loop_info->IsIrreducible());
2447 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2448 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2449 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002450 }
2451
David Brazdil9eeebf62016-03-24 11:18:15 +00002452 // (2) Disconnect the block from its successors and update their phis.
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002453 DisconnectFromSuccessors();
David Brazdil9eeebf62016-03-24 11:18:15 +00002454
2455 // (3) Remove instructions and phis. Instructions should have no remaining uses
2456 // except in catch phis. If an instruction is used by a catch phi at `index`,
2457 // remove `index`-th input of all phis in the catch block since they are
2458 // guaranteed dead. Note that we may miss dead inputs this way but the
2459 // graph will always remain consistent.
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002460 RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ false);
David Brazdil9eeebf62016-03-24 11:18:15 +00002461
2462 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002463 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002464 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002465 // We should not see any back edges as they would have been removed by step (3).
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +00002466 DCHECK_IMPLIES(IsInLoop(), !GetLoopInformation()->IsBackEdge(*predecessor));
David Brazdil9eeebf62016-03-24 11:18:15 +00002467
David Brazdil2d7352b2015-04-20 14:52:42 +01002468 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002469 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2470 // This block is the only normal-flow successor of the TryBoundary which
2471 // makes `predecessor` dead. Since DCE removes blocks in post order,
2472 // exception handlers of this TryBoundary were already visited and any
2473 // remaining handlers therefore must be live. We remove `predecessor` from
2474 // their list of predecessors.
2475 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2476 while (predecessor->GetSuccessors().size() > 1) {
2477 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2478 DCHECK(handler->IsCatchBlock());
2479 predecessor->RemoveSuccessor(handler);
2480 handler->RemovePredecessor(predecessor);
2481 }
2482 }
2483
David Brazdil2d7352b2015-04-20 14:52:42 +01002484 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002485 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2486 if (num_pred_successors == 1u) {
2487 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002488 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2489 // successor. Replace those with a HGoto.
2490 DCHECK(last_instruction->IsIf() ||
2491 last_instruction->IsPackedSwitch() ||
2492 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002493 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002494 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002495 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002496 // The predecessor has no remaining successors and therefore must be dead.
2497 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002498 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002499 predecessor->RemoveInstruction(last_instruction);
2500 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002501 // There are multiple successors left. The removed block might be a successor
2502 // of a PackedSwitch which will be completely removed (perhaps replaced with
2503 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2504 // case, leave `last_instruction` as is for now.
2505 DCHECK(last_instruction->IsPackedSwitch() ||
2506 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002507 }
David Brazdil46e2a392015-03-16 17:31:52 +00002508 }
Vladimir Marko60584552015-09-03 13:35:12 +00002509 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002510
David Brazdil9eeebf62016-03-24 11:18:15 +00002511 // (5) Remove the block from all loops it is included in. Skip the inner-most
2512 // loop if this is the loop header (see definition of `loop_update_start`)
2513 // because the loop header's predecessor list has been destroyed in step (4).
2514 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2515 HLoopInformation* loop_info = it.Current();
2516 loop_info->Remove(this);
2517 if (loop_info->IsBackEdge(*this)) {
2518 // If this was the last back edge of the loop, we deliberately leave the
2519 // loop in an inconsistent state and will fail GraphChecker unless the
2520 // entire loop is removed during the pass.
2521 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002522 }
2523 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002524
David Brazdil9eeebf62016-03-24 11:18:15 +00002525 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002526 dominator_->RemoveDominatedBlock(this);
2527 SetDominator(nullptr);
2528
David Brazdil9eeebf62016-03-24 11:18:15 +00002529 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002530 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002531 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002532}
2533
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002534void HBasicBlock::DisconnectFromSuccessors(const ArenaBitVector* visited) {
2535 for (HBasicBlock* successor : successors_) {
2536 // Delete this block from the list of predecessors.
2537 size_t this_index = successor->GetPredecessorIndexOf(this);
2538 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2539
2540 if (visited != nullptr && !visited->IsBitSet(successor->GetBlockId())) {
2541 // `successor` itself is dead. Therefore, there is no need to update its phis.
2542 continue;
2543 }
2544
2545 DCHECK(!successor->predecessors_.empty());
2546
2547 // Remove this block's entries in the successor's phis. Skips exceptional
2548 // successors because catch phi inputs do not correspond to predecessor
2549 // blocks but throwing instructions. They are removed in `RemoveCatchPhiUses`.
2550 if (!successor->IsCatchBlock()) {
2551 if (successor->predecessors_.size() == 1u) {
2552 // The successor has just one predecessor left. Replace phis with the only
2553 // remaining input.
2554 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2555 HPhi* phi = phi_it.Current()->AsPhi();
2556 phi->ReplaceWith(phi->InputAt(1 - this_index));
2557 successor->RemovePhi(phi);
2558 }
2559 } else {
2560 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2561 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2562 }
2563 }
2564 }
2565 }
2566 successors_.clear();
2567}
2568
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002569void HBasicBlock::RemoveCatchPhiUsesAndInstruction(bool building_dominator_tree) {
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002570 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2571 HInstruction* insn = it.Current();
2572 RemoveCatchPhiUsesOfDeadInstruction(insn);
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002573
2574 // If we are building the dominator tree, we removed all input records previously.
2575 // `RemoveInstruction` will try to remove them again but that's not something we support and we
2576 // will crash. We check here since we won't be checking that in RemoveInstruction.
2577 if (building_dominator_tree) {
2578 DCHECK(insn->GetUses().empty());
2579 DCHECK(insn->GetEnvUses().empty());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002580 }
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002581 RemoveInstruction(insn, /* ensure_safety= */ !building_dominator_tree);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002582 }
2583 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2584 HPhi* insn = it.Current()->AsPhi();
2585 RemoveCatchPhiUsesOfDeadInstruction(insn);
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002586
2587 // If we are building the dominator tree, we removed all input records previously.
2588 // `RemovePhi` will try to remove them again but that's not something we support and we
2589 // will crash. We check here since we won't be checking that in RemovePhi.
2590 if (building_dominator_tree) {
2591 DCHECK(insn->GetUses().empty());
2592 DCHECK(insn->GetEnvUses().empty());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002593 }
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002594 RemovePhi(insn, /* ensure_safety= */ !building_dominator_tree);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002595 }
2596}
2597
Aart Bik6b69e0a2017-01-11 10:20:43 -08002598void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2599 DCHECK(EndsWithControlFlowInstruction());
2600 RemoveInstruction(GetLastInstruction());
2601 instructions_.Add(other->GetInstructions());
2602 other->instructions_.SetBlockOfInstructions(this);
2603 other->instructions_.Clear();
2604}
2605
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002606void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002607 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002608 DCHECK(ContainsElement(dominated_blocks_, other));
2609 DCHECK_EQ(GetSingleSuccessor(), other);
2610 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002611 DCHECK(other->GetPhis().IsEmpty());
2612
David Brazdil2d7352b2015-04-20 14:52:42 +01002613 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002614 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002615
David Brazdil2d7352b2015-04-20 14:52:42 +01002616 // Remove `other` from the loops it is included in.
2617 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2618 HLoopInformation* loop_info = it.Current();
2619 loop_info->Remove(other);
2620 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002621 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002622 }
2623 }
2624
2625 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002626 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002627 for (HBasicBlock* successor : other->GetSuccessors()) {
2628 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002629 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002630 successors_.swap(other->successors_);
2631 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002632
David Brazdil2d7352b2015-04-20 14:52:42 +01002633 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002634 RemoveDominatedBlock(other);
2635 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002636 dominated->SetDominator(this);
2637 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002638 dominated_blocks_.insert(
2639 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002640 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002641 other->dominator_ = nullptr;
2642
2643 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002644 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002645
2646 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002647 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002648 other->SetGraph(nullptr);
2649}
2650
2651void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2652 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002653 DCHECK(GetDominatedBlocks().empty());
2654 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002655 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002656 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002657 DCHECK(other->GetPhis().IsEmpty());
2658 DCHECK(!other->IsInLoop());
2659
2660 // Move instructions from `other` to `this`.
2661 instructions_.Add(other->GetInstructions());
2662 other->instructions_.SetBlockOfInstructions(this);
2663
2664 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002665 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002666 for (HBasicBlock* successor : other->GetSuccessors()) {
2667 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002668 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002669 successors_.swap(other->successors_);
2670 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002671
2672 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002673 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002674 dominated->SetDominator(this);
2675 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002676 dominated_blocks_.insert(
2677 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002678 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002679 other->dominator_ = nullptr;
2680 other->graph_ = nullptr;
2681}
2682
2683void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002684 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002685 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002686 predecessor->ReplaceSuccessor(this, other);
2687 }
Vladimir Marko60584552015-09-03 13:35:12 +00002688 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002689 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002690 successor->ReplacePredecessor(this, other);
2691 }
Vladimir Marko60584552015-09-03 13:35:12 +00002692 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2693 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002694 }
2695 GetDominator()->ReplaceDominatedBlock(this, other);
2696 other->SetDominator(GetDominator());
2697 dominator_ = nullptr;
2698 graph_ = nullptr;
2699}
2700
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002701void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002702 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002703 DCHECK(block->GetSuccessors().empty());
2704 DCHECK(block->GetPredecessors().empty());
2705 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002706 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002707 DCHECK(block->GetInstructions().IsEmpty());
2708 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002709
David Brazdilc7af85d2015-05-26 12:05:55 +01002710 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002711 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002712 }
2713
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002714 RemoveElement(reverse_post_order_, block);
2715 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002716 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002717}
2718
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002719void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2720 HBasicBlock* reference,
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002721 bool replace_if_back_edge,
2722 bool has_more_specific_try_catch_info) {
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002723 if (block->IsLoopHeader()) {
2724 // Clear the information of which blocks are contained in that loop. Since the
2725 // information is stored as a bit vector based on block ids, we have to update
2726 // it, as those block ids were specific to the callee graph and we are now adding
2727 // these blocks to the caller graph.
2728 block->GetLoopInformation()->ClearAllBlocks();
2729 }
2730
2731 // If not already in a loop, update the loop information.
2732 if (!block->IsInLoop()) {
2733 block->SetLoopInformation(reference->GetLoopInformation());
2734 }
2735
2736 // If the block is in a loop, update all its outward loops.
2737 HLoopInformation* loop_info = block->GetLoopInformation();
2738 if (loop_info != nullptr) {
2739 for (HLoopInformationOutwardIterator loop_it(*block);
2740 !loop_it.Done();
2741 loop_it.Advance()) {
2742 loop_it.Current()->Add(block);
2743 }
2744 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2745 loop_info->ReplaceBackEdge(reference, block);
2746 }
2747 }
2748
Santiago Aboy Solanes343b9d92022-12-06 18:13:10 +00002749 DCHECK_IMPLIES(has_more_specific_try_catch_info, !reference->IsTryBlock())
2750 << "We don't allow to inline try catches inside of other try blocks.";
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002751
2752 // Update the TryCatchInformation, if we are not inlining a try catch.
2753 if (!has_more_specific_try_catch_info) {
2754 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2755 TryCatchInformation* try_catch_info =
2756 reference->IsTryBlock() ? reference->GetTryCatchInformation() : nullptr;
2757 block->SetTryCatchInformation(try_catch_info);
2758 }
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002759}
2760
Calin Juravle2e768302015-07-28 14:41:11 +00002761HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002762 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002763 // Update the environments in this graph to have the invoke's environment
2764 // as parent.
2765 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002766 // Skip the entry block, we do not need to update the entry's suspend check.
2767 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002768 for (HInstructionIterator instr_it(block->GetInstructions());
2769 !instr_it.Done();
2770 instr_it.Advance()) {
2771 HInstruction* current = instr_it.Current();
2772 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002773 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002774 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002775 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002776 }
2777 }
2778 }
2779 }
2780 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002781
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002782 if (HasBoundsChecks()) {
2783 outer_graph->SetHasBoundsChecks(true);
2784 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002785 if (HasLoops()) {
2786 outer_graph->SetHasLoops(true);
2787 }
2788 if (HasIrreducibleLoops()) {
2789 outer_graph->SetHasIrreducibleLoops(true);
2790 }
Vladimir Markod3e9c622020-08-05 12:20:28 +01002791 if (HasDirectCriticalNativeCall()) {
2792 outer_graph->SetHasDirectCriticalNativeCall(true);
2793 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002794 if (HasTryCatch()) {
2795 outer_graph->SetHasTryCatch(true);
2796 }
Santiago Aboy Solanesbf778f02022-12-15 14:58:21 +00002797 if (HasMonitorOperations()) {
2798 outer_graph->SetHasMonitorOperations(true);
2799 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002800 if (HasSIMD()) {
2801 outer_graph->SetHasSIMD(true);
2802 }
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +01002803 if (HasAlwaysThrowingInvokes()) {
2804 outer_graph->SetHasAlwaysThrowingInvokes(true);
2805 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002806
Calin Juravle2e768302015-07-28 14:41:11 +00002807 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002808 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002809 // Inliner already made sure we don't inline methods that always throw.
2810 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002811 // Simple case of an entry block, a body block, and an exit block.
2812 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002813 HBasicBlock* body = GetBlocks()[1];
2814 DCHECK(GetBlocks()[0]->IsEntryBlock());
2815 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002816 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002817 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002818 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002819
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002820 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2821 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002822 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002823
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002824 // Replace the invoke with the return value of the inlined graph.
2825 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002826 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002827 } else {
2828 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002829 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002830
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002831 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002832 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002833 // Need to inline multiple blocks. We split `invoke`'s block
2834 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002835 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002836 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002837 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002838 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002839 // Note that we split before the invoke only to simplify polymorphic inlining.
2840 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002841
Vladimir Markoec7802a2015-10-01 20:57:57 +01002842 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002843 DCHECK(!first->IsInLoop());
Santiago Aboy Solanes343b9d92022-12-06 18:13:10 +00002844 DCHECK(first->GetTryCatchInformation() == nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002845 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002846 exit_block_->ReplaceWith(to);
2847
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002848 // Update the meta information surrounding blocks:
2849 // (1) the graph they are now in,
2850 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002851 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002852 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002853 // Note that we do not need to update catch phi inputs because they
2854 // correspond to the register file of the outer method which the inlinee
2855 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002856
2857 // We don't add the entry block, the exit block, and the first block, which
2858 // has been merged with `at`.
2859 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2860
2861 // We add the `to` block.
2862 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002863 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002864 + kNumberOfNewBlocksInCaller;
2865
2866 // Find the location of `at` in the outer graph's reverse post order. The new
2867 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002868 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002869 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2870
David Brazdil95177982015-10-30 12:56:58 -05002871 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2872 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002873 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002874 if (current != exit_block_ && current != entry_block_ && current != first) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002875 DCHECK(current->GetGraph() == this);
2876 current->SetGraph(outer_graph);
2877 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002878 outer_graph->reverse_post_order_[++index_of_at] = current;
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002879 UpdateLoopAndTryInformationOfNewBlock(current,
2880 at,
2881 /* replace_if_back_edge= */ false,
2882 current->GetTryCatchInformation() != nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002883 }
2884 }
2885
David Brazdil95177982015-10-30 12:56:58 -05002886 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002887 to->SetGraph(outer_graph);
2888 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002889 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002890 // Only `to` can become a back edge, as the inlined blocks
2891 // are predecessors of `to`.
Andreas Gampe3db70682018-12-26 15:12:03 -08002892 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002893
David Brazdil3f523062016-02-29 16:53:33 +00002894 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002895 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002896 // to now get the outer graph exit block as successor.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002897 HPhi* return_value_phi = nullptr;
2898 bool rerun_dominance = false;
2899 bool rerun_loop_analysis = false;
2900 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2901 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002902 HInstruction* last = predecessor->GetLastInstruction();
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002903
2904 // At this point we might either have:
Santiago Aboy Solanes69293b02022-12-08 19:10:57 +00002905 // A) Return/ReturnVoid/Throw as the last instruction, or
2906 // B) `Return/ReturnVoid/Throw->TryBoundary` as the last instruction chain
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002907
2908 const bool saw_try_boundary = last->IsTryBoundary();
2909 if (saw_try_boundary) {
2910 DCHECK(predecessor->IsSingleTryBoundary());
2911 DCHECK(!last->AsTryBoundary()->IsEntry());
2912 predecessor = predecessor->GetSinglePredecessor();
2913 last = predecessor->GetLastInstruction();
2914 }
2915
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002916 if (last->IsThrow()) {
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002917 if (at->IsTryBlock()) {
2918 DCHECK(!saw_try_boundary) << "We don't support inlining of try blocks into try blocks.";
2919 // Create a TryBoundary of kind:exit and point it to the Exit block.
2920 HBasicBlock* new_block = outer_graph->SplitEdge(predecessor, to);
2921 new_block->AddInstruction(
2922 new (allocator) HTryBoundary(HTryBoundary::BoundaryKind::kExit, last->GetDexPc()));
2923 new_block->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2924
2925 // Copy information from the predecessor.
2926 new_block->SetLoopInformation(predecessor->GetLoopInformation());
2927 TryCatchInformation* try_catch_info = predecessor->GetTryCatchInformation();
2928 new_block->SetTryCatchInformation(try_catch_info);
2929 for (HBasicBlock* xhandler :
2930 try_catch_info->GetTryEntry().GetBlock()->GetExceptionalSuccessors()) {
2931 new_block->AddSuccessor(xhandler);
2932 }
2933 DCHECK(try_catch_info->GetTryEntry().HasSameExceptionHandlersAs(
2934 *new_block->GetLastInstruction()->AsTryBoundary()));
2935 } else {
2936 // We either have `Throw->TryBoundary` or `Throw`. We want to point the whole chain to the
2937 // exit, so we recompute `predecessor`
2938 predecessor = to->GetPredecessors()[pred];
2939 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2940 }
2941
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002942 --pred;
2943 // We need to re-run dominance information, as the exit block now has
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002944 // a new predecessor and potential new dominator.
2945 // TODO(solanes): See if it's worth it to hand-modify the domination chain instead of
2946 // rerunning the dominance for the whole graph.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002947 rerun_dominance = true;
2948 if (predecessor->GetLoopInformation() != nullptr) {
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002949 // The loop information might have changed e.g. `predecessor` might not be in a loop
2950 // anymore. We only do this if `predecessor` has loop information as it is impossible for
2951 // predecessor to end up in a loop if it wasn't in one before.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002952 rerun_loop_analysis = true;
2953 }
2954 } else {
2955 if (last->IsReturnVoid()) {
2956 DCHECK(return_value == nullptr);
2957 DCHECK(return_value_phi == nullptr);
2958 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002959 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002960 if (return_value_phi != nullptr) {
2961 return_value_phi->AddInput(last->InputAt(0));
2962 } else if (return_value == nullptr) {
2963 return_value = last->InputAt(0);
2964 } else {
2965 // There will be multiple returns.
2966 return_value_phi = new (allocator) HPhi(
2967 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2968 to->AddPhi(return_value_phi);
2969 return_value_phi->AddInput(return_value);
2970 return_value_phi->AddInput(last->InputAt(0));
2971 return_value = return_value_phi;
2972 }
David Brazdil3f523062016-02-29 16:53:33 +00002973 }
2974 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2975 predecessor->RemoveInstruction(last);
Santiago Aboy Solanes69293b02022-12-08 19:10:57 +00002976
2977 if (saw_try_boundary) {
2978 predecessor = to->GetPredecessors()[pred];
2979 DCHECK(predecessor->EndsWithTryBoundary());
2980 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
2981 if (predecessor->GetSuccessors()[0]->GetPredecessors().size() > 1) {
2982 outer_graph->SplitCriticalEdge(predecessor, to);
2983 rerun_dominance = true;
2984 if (predecessor->GetLoopInformation() != nullptr) {
2985 rerun_loop_analysis = true;
2986 }
2987 }
2988 }
David Brazdil3f523062016-02-29 16:53:33 +00002989 }
2990 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002991 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002992 DCHECK(!outer_graph->HasIrreducibleLoops())
2993 << "Recomputing loop information in graphs with irreducible loops "
2994 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002995 outer_graph->ClearLoopInformation();
2996 outer_graph->ClearDominanceInformation();
2997 outer_graph->BuildDominatorTree();
2998 } else if (rerun_dominance) {
2999 outer_graph->ClearDominanceInformation();
3000 outer_graph->ComputeDominanceInformation();
3001 }
David Brazdil3f523062016-02-29 16:53:33 +00003002 }
David Brazdil05144f42015-04-16 15:18:00 +01003003
3004 // Walk over the entry block and:
3005 // - Move constants from the entry block to the outer_graph's entry block,
3006 // - Replace HParameterValue instructions with their real value.
3007 // - Remove suspend checks, that hold an environment.
3008 // We must do this after the other blocks have been inlined, otherwise ids of
3009 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01003010 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01003011 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
3012 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01003013 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01003014 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003015 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003016 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003017 replacement = outer_graph->GetIntConstant(
3018 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003019 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003020 replacement = outer_graph->GetLongConstant(
3021 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00003022 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003023 replacement = outer_graph->GetFloatConstant(
3024 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00003025 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003026 replacement = outer_graph->GetDoubleConstant(
3027 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003028 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01003029 if (kIsDebugBuild
3030 && invoke->IsInvokeStaticOrDirect()
3031 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
3032 // Ensure we do not use the last input of `invoke`, as it
3033 // contains a clinit check which is not an actual argument.
3034 size_t last_input_index = invoke->InputCount() - 1;
3035 DCHECK(parameter_index != last_input_index);
3036 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01003037 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01003038 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003039 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01003040 } else {
Mythri Alle5097f832021-11-02 14:52:30 +00003041 // It is OK to ignore MethodEntryHook for inlined functions.
3042 // In debug mode we don't inline and in release mode method
3043 // tracing is best effort so OK to ignore them.
3044 DCHECK(current->IsGoto() || current->IsSuspendCheck() || current->IsMethodEntryHook());
David Brazdil05144f42015-04-16 15:18:00 +01003045 entry_block_->RemoveInstruction(current);
3046 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01003047 if (replacement != nullptr) {
3048 current->ReplaceWith(replacement);
3049 // If the current is the return value then we need to update the latter.
3050 if (current == return_value) {
3051 DCHECK_EQ(entry_block_, return_value->GetBlock());
3052 return_value = replacement;
3053 }
3054 }
3055 }
3056
Calin Juravle2e768302015-07-28 14:41:11 +00003057 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00003058}
3059
Mingyao Yang3584bce2015-05-19 16:01:59 -07003060/*
3061 * Loop will be transformed to:
3062 * old_pre_header
3063 * |
3064 * if_block
3065 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08003066 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07003067 * \ /
3068 * new_pre_header
3069 * |
3070 * header
3071 */
3072void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
3073 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08003074 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07003075
Aart Bik3fc7f352015-11-20 22:03:03 -08003076 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01003077 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3078 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3079 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3080 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07003081 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08003082 AddBlock(true_block);
3083 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003084 AddBlock(new_pre_header);
3085
Aart Bik3fc7f352015-11-20 22:03:03 -08003086 header->ReplacePredecessor(old_pre_header, new_pre_header);
3087 old_pre_header->successors_.clear();
3088 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07003089
Aart Bik3fc7f352015-11-20 22:03:03 -08003090 old_pre_header->AddSuccessor(if_block);
3091 if_block->AddSuccessor(true_block); // True successor
3092 if_block->AddSuccessor(false_block); // False successor
3093 true_block->AddSuccessor(new_pre_header);
3094 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003095
Aart Bik3fc7f352015-11-20 22:03:03 -08003096 old_pre_header->dominated_blocks_.push_back(if_block);
3097 if_block->SetDominator(old_pre_header);
3098 if_block->dominated_blocks_.push_back(true_block);
3099 true_block->SetDominator(if_block);
3100 if_block->dominated_blocks_.push_back(false_block);
3101 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00003102 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003103 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00003104 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003105 header->SetDominator(new_pre_header);
3106
Aart Bik3fc7f352015-11-20 22:03:03 -08003107 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003108 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003109 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003110 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08003111 reverse_post_order_[index_of_header++] = true_block;
3112 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003113 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07003114
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003115 // The pre_header can never be a back edge of a loop.
3116 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
3117 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
3118 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003119 if_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003120 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003121 true_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003122 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003123 false_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003124 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003125 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003126}
3127
Aart Bikf8f5a162017-02-06 15:35:29 -08003128HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
3129 HBasicBlock* body,
3130 HBasicBlock* exit) {
3131 DCHECK(header->IsLoopHeader());
3132 HLoopInformation* loop = header->GetLoopInformation();
3133
3134 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01003135 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3136 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3137 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08003138 AddBlock(new_pre_header);
3139 AddBlock(new_header);
3140 AddBlock(new_body);
3141
3142 // Set up control flow.
3143 header->ReplaceSuccessor(exit, new_pre_header);
3144 new_pre_header->AddSuccessor(new_header);
3145 new_header->AddSuccessor(exit);
3146 new_header->AddSuccessor(new_body);
3147 new_body->AddSuccessor(new_header);
3148
3149 // Set up dominators.
3150 header->ReplaceDominatedBlock(exit, new_pre_header);
3151 new_pre_header->SetDominator(header);
3152 new_pre_header->dominated_blocks_.push_back(new_header);
3153 new_header->SetDominator(new_pre_header);
3154 new_header->dominated_blocks_.push_back(new_body);
3155 new_body->SetDominator(new_header);
3156 new_header->dominated_blocks_.push_back(exit);
3157 exit->SetDominator(new_header);
3158
3159 // Fix reverse post order.
3160 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
3161 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
3162 reverse_post_order_[++index_of_header] = new_pre_header;
3163 reverse_post_order_[++index_of_header] = new_header;
3164 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
3165 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
3166 reverse_post_order_[index_of_body] = new_body;
3167
Aart Bikb07d1bc2017-04-05 10:03:15 -07003168 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01003169 new_pre_header->AddInstruction(new (allocator_) HGoto());
3170 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08003171 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01003172 new_body->AddInstruction(new (allocator_) HGoto());
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +01003173 DCHECK(loop->GetSuspendCheck() != nullptr);
Aart Bikb07d1bc2017-04-05 10:03:15 -07003174 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
3175 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08003176
3177 // Update loop information.
3178 new_header->AddBackEdge(new_body);
3179 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
3180 new_header->GetLoopInformation()->Populate();
3181 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
3182 HLoopInformationOutwardIterator it(*new_header);
3183 for (it.Advance(); !it.Done(); it.Advance()) {
3184 it.Current()->Add(new_pre_header);
3185 it.Current()->Add(new_header);
3186 it.Current()->Add(new_body);
3187 }
3188 return new_pre_header;
3189}
3190
David Brazdilf5552582015-12-27 13:36:12 +00003191static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003192 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00003193 if (rti.IsValid()) {
3194 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
3195 << " upper_bound_rti: " << upper_bound_rti
3196 << " rti: " << rti;
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +00003197 DCHECK_IMPLIES(upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes(), rti.IsExact())
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003198 << " upper_bound_rti: " << upper_bound_rti
3199 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00003200 }
3201}
3202
Calin Juravle2e768302015-07-28 14:41:11 +00003203void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
3204 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003205 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00003206 ScopedObjectAccess soa(Thread::Current());
3207 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
3208 if (IsBoundType()) {
3209 // Having the test here spares us from making the method virtual just for
3210 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00003211 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00003212 }
3213 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003214 reference_type_handle_ = rti.GetTypeHandle();
3215 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00003216}
3217
Santiago Aboy Solanese05bc3e2023-02-20 14:26:23 +00003218void HInstruction::SetReferenceTypeInfoIfValid(ReferenceTypeInfo rti) {
3219 if (rti.IsValid()) {
3220 SetReferenceTypeInfo(rti);
3221 }
3222}
3223
Artem Serov4d277ba2018-06-05 20:54:42 +01003224bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
3225 const HBoundType* other_bt = other->AsBoundType();
3226 ScopedObjectAccess soa(Thread::Current());
3227 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
3228 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
3229 CanBeNull() == other_bt->CanBeNull();
3230}
3231
David Brazdilf5552582015-12-27 13:36:12 +00003232void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
3233 if (kIsDebugBuild) {
3234 ScopedObjectAccess soa(Thread::Current());
3235 DCHECK(upper_bound.IsValid());
3236 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
3237 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
3238 }
3239 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00003240 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00003241}
3242
Vladimir Markoa1de9182016-02-25 11:37:38 +00003243ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00003244 if (kIsDebugBuild) {
3245 ScopedObjectAccess soa(Thread::Current());
3246 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003247 if (!is_exact) {
3248 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
3249 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
3250 }
Calin Juravle2e768302015-07-28 14:41:11 +00003251 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003252 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00003253}
3254
Calin Juravleacf735c2015-02-12 15:25:22 +00003255std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
3256 ScopedObjectAccess soa(Thread::Current());
3257 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00003258 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07003259 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00003260 << " is_exact=" << rhs.IsExact()
3261 << " ]";
3262 return os;
3263}
3264
Mark Mendellc4701932015-04-10 13:18:51 -04003265bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
3266 // For now, assume that instructions in different blocks may use the
3267 // environment.
3268 // TODO: Use the control flow to decide if this is true.
3269 if (GetBlock() != other->GetBlock()) {
3270 return true;
3271 }
3272
3273 // We know that we are in the same block. Walk from 'this' to 'other',
3274 // checking to see if there is any instruction with an environment.
3275 HInstruction* current = this;
3276 for (; current != other && current != nullptr; current = current->GetNext()) {
3277 // This is a conservative check, as the instruction result may not be in
3278 // the referenced environment.
3279 if (current->HasEnvironment()) {
3280 return true;
3281 }
3282 }
3283
3284 // We should have been called with 'this' before 'other' in the block.
3285 // Just confirm this.
3286 DCHECK(current != nullptr);
3287 return false;
3288}
3289
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003290void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003291 IntrinsicNeedsEnvironment needs_env,
Aart Bik5d75afe2015-12-14 11:57:01 -08003292 IntrinsicSideEffects side_effects,
3293 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003294 intrinsic_ = intrinsic;
3295 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003296
Aart Bik5d75afe2015-12-14 11:57:01 -08003297 // Adjust method's side effects from intrinsic table.
3298 switch (side_effects) {
3299 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
3300 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
3301 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
3302 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
3303 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003304
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003305 if (needs_env == kNoEnvironment) {
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003306 opt.SetDoesNotNeedEnvironment();
3307 } else {
3308 // If we need an environment, that means there will be a call, which can trigger GC.
3309 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
3310 }
Aart Bik5d75afe2015-12-14 11:57:01 -08003311 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08003312 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003313}
3314
David Brazdil6de19382016-01-08 17:37:10 +00003315bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07003316 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00003317}
3318
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003319bool HInvoke::NeedsEnvironment() const {
3320 if (!IsIntrinsic()) {
3321 return true;
3322 }
3323 IntrinsicOptimizations opt(*this);
3324 return !opt.GetDoesNotNeedEnvironment();
3325}
3326
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00003327const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
3328 ArtMethod* caller = GetEnvironment()->GetMethod();
3329 ScopedObjectAccess soa(Thread::Current());
3330 // `caller` is null for a top-level graph representing a method whose declaring
3331 // class was not resolved.
3332 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
3333}
3334
Vladimir Markofbb184a2015-11-13 14:47:00 +00003335std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
3336 switch (rhs) {
3337 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
3338 return os << "explicit";
3339 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
3340 return os << "implicit";
3341 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
3342 return os << "none";
3343 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00003344 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
3345 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00003346 }
3347}
3348
Vladimir Markoac27ac02021-02-01 09:31:02 +00003349bool HInvokeVirtual::CanDoImplicitNullCheckOn(HInstruction* obj) const {
3350 if (obj != InputAt(0)) {
3351 return false;
3352 }
3353 switch (GetIntrinsic()) {
Vladimir Marko5e060ee2021-02-23 10:56:42 +00003354 case Intrinsics::kNone:
3355 return true;
Vladimir Markoac27ac02021-02-01 09:31:02 +00003356 case Intrinsics::kReferenceRefersTo:
3357 return true;
3358 default:
3359 // TODO: Add implicit null checks in more intrinsics.
3360 return false;
3361 }
3362}
3363
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003364bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
3365 const HLoadClass* other_load_class = other->AsLoadClass();
3366 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
3367 // names rather than type indexes. However, we shall also have to re-think the hash code.
3368 if (type_index_ != other_load_class->type_index_ ||
3369 GetPackedFields() != other_load_class->GetPackedFields()) {
3370 return false;
3371 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003372 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003373 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003374 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003375 case LoadKind::kJitTableAddress: {
3376 ScopedObjectAccess soa(Thread::Current());
3377 return GetClass().Get() == other_load_class->GetClass().Get();
3378 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003379 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00003380 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003381 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003382 }
3383}
3384
Vladimir Marko372f10e2016-05-17 16:30:10 +01003385bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3386 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003387 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3388 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003389 if (string_index_ != other_load_string->string_index_ ||
3390 GetPackedFields() != other_load_string->GetPackedFields()) {
3391 return false;
3392 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003393 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003394 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003395 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003396 case LoadKind::kJitTableAddress: {
3397 ScopedObjectAccess soa(Thread::Current());
3398 return GetString().Get() == other_load_string->GetString().Get();
3399 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003400 default:
3401 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003402 }
3403}
3404
Mark Mendellc4701932015-04-10 13:18:51 -04003405void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003406 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3407 HEnvironment* user = use.GetUser();
3408 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003409 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003410 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003411}
3412
Artem Serovcced8ba2017-07-19 18:18:09 +01003413HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3414 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3415 HBasicBlock* block = instr->GetBlock();
3416
3417 if (instr->IsPhi()) {
3418 HPhi* phi = instr->AsPhi();
3419 DCHECK(!phi->HasEnvironment());
3420 HPhi* phi_clone = clone->AsPhi();
3421 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3422 } else {
3423 block->ReplaceAndRemoveInstructionWith(instr, clone);
3424 if (instr->HasEnvironment()) {
3425 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3426 HLoopInformation* loop_info = block->GetLoopInformation();
3427 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3428 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3429 }
3430 }
3431 }
3432 return clone;
3433}
3434
Roland Levillainc9b21f82016-03-23 16:36:59 +00003435// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003436HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003437 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003438
3439 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003440 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003441 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3442 HInstruction* lhs = cond->InputAt(0);
3443 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003444 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003445 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3446 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3447 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3448 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3449 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3450 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3451 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3452 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3453 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3454 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3455 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003456 default:
3457 LOG(FATAL) << "Unexpected condition";
3458 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003459 }
3460 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3461 return replacement;
3462 } else if (cond->IsIntConstant()) {
3463 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003464 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003465 return GetIntConstant(1);
3466 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003467 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003468 return GetIntConstant(0);
3469 }
3470 } else {
3471 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3472 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3473 return replacement;
3474 }
3475}
3476
Roland Levillainc9285912015-12-18 10:38:42 +00003477std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3478 os << "["
3479 << " source=" << rhs.GetSource()
3480 << " destination=" << rhs.GetDestination()
3481 << " type=" << rhs.GetType()
3482 << " instruction=";
3483 if (rhs.GetInstruction() != nullptr) {
3484 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3485 } else {
3486 os << "null";
3487 }
3488 os << " ]";
3489 return os;
3490}
3491
Roland Levillain86503782016-02-11 19:07:30 +00003492std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3493 switch (rhs) {
3494 case TypeCheckKind::kUnresolvedCheck:
3495 return os << "unresolved_check";
3496 case TypeCheckKind::kExactCheck:
3497 return os << "exact_check";
3498 case TypeCheckKind::kClassHierarchyCheck:
3499 return os << "class_hierarchy_check";
3500 case TypeCheckKind::kAbstractClassCheck:
3501 return os << "abstract_class_check";
3502 case TypeCheckKind::kInterfaceCheck:
3503 return os << "interface_check";
3504 case TypeCheckKind::kArrayObjectCheck:
3505 return os << "array_object_check";
3506 case TypeCheckKind::kArrayCheck:
3507 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003508 case TypeCheckKind::kBitstringCheck:
3509 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003510 default:
3511 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3512 UNREACHABLE();
3513 }
3514}
3515
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003516// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3517#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3518 static_assert( \
3519 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3520 "Instrinsics enumeration space overflow.");
3521#include "intrinsics_list.h"
3522 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3523#undef INTRINSICS_LIST
3524#undef CHECK_INTRINSICS_ENUM_VALUES
3525
3526// Function that returns whether an intrinsic needs an environment or not.
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003527static inline IntrinsicNeedsEnvironment NeedsEnvironmentIntrinsic(Intrinsics i) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003528 switch (i) {
3529 case Intrinsics::kNone:
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003530 return kNeedsEnvironment; // Non-sensical for intrinsic.
3531#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003532 case Intrinsics::k ## Name: \
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003533 return NeedsEnv;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003534#include "intrinsics_list.h"
3535 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3536#undef INTRINSICS_LIST
3537#undef OPTIMIZING_INTRINSICS
3538 }
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003539 return kNeedsEnvironment;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003540}
3541
3542// Function that returns whether an intrinsic has side effects.
3543static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3544 switch (i) {
3545 case Intrinsics::kNone:
3546 return kAllSideEffects;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003547#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003548 case Intrinsics::k ## Name: \
3549 return SideEffects;
3550#include "intrinsics_list.h"
3551 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3552#undef INTRINSICS_LIST
3553#undef OPTIMIZING_INTRINSICS
3554 }
3555 return kAllSideEffects;
3556}
3557
3558// Function that returns whether an intrinsic can throw exceptions.
3559static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3560 switch (i) {
3561 case Intrinsics::kNone:
3562 return kCanThrow;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003563#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003564 case Intrinsics::k ## Name: \
3565 return Exceptions;
3566#include "intrinsics_list.h"
3567 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3568#undef INTRINSICS_LIST
3569#undef OPTIMIZING_INTRINSICS
3570 }
3571 return kCanThrow;
3572}
3573
3574void HInvoke::SetResolvedMethod(ArtMethod* method) {
Andra Danciua0130e82020-07-23 12:34:56 +00003575 if (method != nullptr && method->IsIntrinsic()) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003576 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3577 SetIntrinsic(intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003578 NeedsEnvironmentIntrinsic(intrinsic),
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003579 GetSideEffectsIntrinsic(intrinsic),
3580 GetExceptionsIntrinsic(intrinsic));
3581 }
3582 resolved_method_ = method;
3583}
3584
Evgeny Astigeevichaf92a0f2020-06-26 13:28:33 +01003585bool IsGEZero(HInstruction* instruction) {
3586 DCHECK(instruction != nullptr);
3587 if (instruction->IsArrayLength()) {
3588 return true;
3589 } else if (instruction->IsMin()) {
3590 // Instruction MIN(>=0, >=0) is >= 0.
3591 return IsGEZero(instruction->InputAt(0)) &&
3592 IsGEZero(instruction->InputAt(1));
3593 } else if (instruction->IsAbs()) {
3594 // Instruction ABS(>=0) is >= 0.
3595 // NOTE: ABS(minint) = minint prevents assuming
3596 // >= 0 without looking at the argument.
3597 return IsGEZero(instruction->InputAt(0));
3598 }
3599 int64_t value = -1;
3600 return IsInt64AndGet(instruction, &value) && value >= 0;
3601}
3602
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003603} // namespace art