1 /*
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 */
16 #include "nodes.h"
17
18 #include <algorithm>
19 #include <cfloat>
20 #include <functional>
21 #include <optional>
22
23 #include "art_method-inl.h"
24 #include "base/arena_allocator.h"
25 #include "base/arena_bit_vector.h"
26 #include "base/bit_utils.h"
27 #include "base/bit_vector-inl.h"
28 #include "base/bit_vector.h"
29 #include "base/iteration_range.h"
30 #include "base/logging.h"
31 #include "base/malloc_arena_pool.h"
32 #include "base/scoped_arena_allocator.h"
33 #include "base/scoped_arena_containers.h"
34 #include "base/stl_util.h"
35 #include "class_linker-inl.h"
36 #include "class_root-inl.h"
37 #include "code_generator.h"
38 #include "common_dominator.h"
39 #include "intrinsic_objects.h"
40 #include "intrinsics.h"
41 #include "intrinsics_list.h"
42 #include "mirror/class-inl.h"
43 #include "scoped_thread_state_change-inl.h"
44 #include "ssa_builder.h"
45
46 namespace art HIDDEN {
47
48 // Enable floating-point static evaluation during constant folding
49 // only if all floating-point operations and constants evaluate in the
50 // range and precision of the type used (i.e., 32-bit float, 64-bit
51 // double).
52 static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
53
AddBlock(HBasicBlock * block)54 void HGraph::AddBlock(HBasicBlock* block) {
55 block->SetBlockId(blocks_.size());
56 blocks_.push_back(block);
57 }
58
FindBackEdges(ArenaBitVector * visited)59 void HGraph::FindBackEdges(ArenaBitVector* visited) {
60 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
61 DCHECK_EQ(visited->GetHighestBitSet(), -1);
62
63 // Allocate memory from local ScopedArenaAllocator.
64 ScopedArenaAllocator allocator(GetArenaStack());
65 // Nodes that we're currently visiting, indexed by block id.
66 ArenaBitVector visiting(
67 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
68 // Number of successors visited from a given node, indexed by block id.
69 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
70 0u,
71 allocator.Adapter(kArenaAllocGraphBuilder));
72 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
73 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
74 constexpr size_t kDefaultWorklistSize = 8;
75 worklist.reserve(kDefaultWorklistSize);
76 visited->SetBit(entry_block_->GetBlockId());
77 visiting.SetBit(entry_block_->GetBlockId());
78 worklist.push_back(entry_block_);
79
80 while (!worklist.empty()) {
81 HBasicBlock* current = worklist.back();
82 uint32_t current_id = current->GetBlockId();
83 if (successors_visited[current_id] == current->GetSuccessors().size()) {
84 visiting.ClearBit(current_id);
85 worklist.pop_back();
86 } else {
87 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
88 uint32_t successor_id = successor->GetBlockId();
89 if (visiting.IsBitSet(successor_id)) {
90 DCHECK(ContainsElement(worklist, successor));
91 successor->AddBackEdge(current);
92 } else if (!visited->IsBitSet(successor_id)) {
93 visited->SetBit(successor_id);
94 visiting.SetBit(successor_id);
95 worklist.push_back(successor);
96 }
97 }
98 }
99 }
100
101 // Remove the environment use records of the instruction for users.
RemoveEnvironmentUses(HInstruction * instruction)102 void RemoveEnvironmentUses(HInstruction* instruction) {
103 for (HEnvironment* environment = instruction->GetEnvironment();
104 environment != nullptr;
105 environment = environment->GetParent()) {
106 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
107 if (environment->GetInstructionAt(i) != nullptr) {
108 environment->RemoveAsUserOfInput(i);
109 }
110 }
111 }
112 }
113
114 // Return whether the instruction has an environment and it's used by others.
HasEnvironmentUsedByOthers(HInstruction * instruction)115 bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
116 for (HEnvironment* environment = instruction->GetEnvironment();
117 environment != nullptr;
118 environment = environment->GetParent()) {
119 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
120 HInstruction* user = environment->GetInstructionAt(i);
121 if (user != nullptr) {
122 return true;
123 }
124 }
125 }
126 return false;
127 }
128
129 // Reset environment records of the instruction itself.
ResetEnvironmentInputRecords(HInstruction * instruction)130 void ResetEnvironmentInputRecords(HInstruction* instruction) {
131 for (HEnvironment* environment = instruction->GetEnvironment();
132 environment != nullptr;
133 environment = environment->GetParent()) {
134 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
135 DCHECK(environment->GetHolder() == instruction);
136 if (environment->GetInstructionAt(i) != nullptr) {
137 environment->SetRawEnvAt(i, nullptr);
138 }
139 }
140 }
141 }
142
RemoveAsUser(HInstruction * instruction)143 static void RemoveAsUser(HInstruction* instruction) {
144 instruction->RemoveAsUserOfAllInputs();
145 RemoveEnvironmentUses(instruction);
146 }
147
RemoveDeadBlocksInstructionsAsUsersAndDisconnect(const ArenaBitVector & visited) const148 void HGraph::RemoveDeadBlocksInstructionsAsUsersAndDisconnect(const ArenaBitVector& visited) const {
149 for (size_t i = 0; i < blocks_.size(); ++i) {
150 if (!visited.IsBitSet(i)) {
151 HBasicBlock* block = blocks_[i];
152 if (block == nullptr) continue;
153
154 // Remove as user.
155 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
156 RemoveAsUser(it.Current());
157 }
158 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
159 RemoveAsUser(it.Current());
160 }
161
162 // Remove non-catch phi uses, and disconnect the block.
163 block->DisconnectFromSuccessors(&visited);
164 }
165 }
166 }
167
168 // This method assumes `insn` has been removed from all users with the exception of catch
169 // phis because of missing exceptional edges in the graph. It removes the
170 // instruction from catch phi uses, together with inputs of other catch phis in
171 // the catch block at the same index, as these must be dead too.
RemoveCatchPhiUsesOfDeadInstruction(HInstruction * insn)172 static void RemoveCatchPhiUsesOfDeadInstruction(HInstruction* insn) {
173 DCHECK(!insn->HasEnvironmentUses());
174 while (insn->HasNonEnvironmentUses()) {
175 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
176 size_t use_index = use.GetIndex();
177 HBasicBlock* user_block = use.GetUser()->GetBlock();
178 DCHECK(use.GetUser()->IsPhi());
179 DCHECK(user_block->IsCatchBlock());
180 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
181 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
182 }
183 }
184 }
185
RemoveDeadBlocks(const ArenaBitVector & visited)186 void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
187 DCHECK(reverse_post_order_.empty()) << "We shouldn't have dominance information.";
188 for (size_t i = 0; i < blocks_.size(); ++i) {
189 if (!visited.IsBitSet(i)) {
190 HBasicBlock* block = blocks_[i];
191 if (block == nullptr) continue;
192
193 // Remove all remaining uses (which should be only catch phi uses), and the instructions.
194 block->RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ true);
195
196 // Remove the block from the list of blocks, so that further analyses
197 // never see it.
198 blocks_[i] = nullptr;
199 if (block->IsExitBlock()) {
200 SetExitBlock(nullptr);
201 }
202 // Mark the block as removed. This is used by the HGraphBuilder to discard
203 // the block as a branch target.
204 block->SetGraph(nullptr);
205 }
206 }
207 }
208
BuildDominatorTree()209 GraphAnalysisResult HGraph::BuildDominatorTree() {
210 // Allocate memory from local ScopedArenaAllocator.
211 ScopedArenaAllocator allocator(GetArenaStack());
212
213 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
214
215 // (1) Find the back edges in the graph doing a DFS traversal.
216 FindBackEdges(&visited);
217
218 // (2) Remove instructions and phis from blocks not visited during
219 // the initial DFS as users from other instructions, so that
220 // users can be safely removed before uses later.
221 // Also disconnect the block from its successors, updating the successor's phis if needed.
222 RemoveDeadBlocksInstructionsAsUsersAndDisconnect(visited);
223
224 // (3) Remove blocks not visited during the initial DFS.
225 // Step (5) requires dead blocks to be removed from the
226 // predecessors list of live blocks.
227 RemoveDeadBlocks(visited);
228
229 // (4) Simplify the CFG now, so that we don't need to recompute
230 // dominators and the reverse post order.
231 SimplifyCFG();
232
233 // (5) Compute the dominance information and the reverse post order.
234 ComputeDominanceInformation();
235
236 // (6) Analyze loops discovered through back edge analysis, and
237 // set the loop information on each block.
238 GraphAnalysisResult result = AnalyzeLoops();
239 if (result != kAnalysisSuccess) {
240 return result;
241 }
242
243 // (7) Precompute per-block try membership before entering the SSA builder,
244 // which needs the information to build catch block phis from values of
245 // locals at throwing instructions inside try blocks.
246 ComputeTryBlockInformation();
247
248 return kAnalysisSuccess;
249 }
250
RecomputeDominatorTree()251 GraphAnalysisResult HGraph::RecomputeDominatorTree() {
252 DCHECK(!HasIrreducibleLoops()) << "Recomputing loop information in graphs with irreducible loops "
253 << "is unsupported, as it could lead to loop header changes";
254 ClearLoopInformation();
255 ClearDominanceInformation();
256 return BuildDominatorTree();
257 }
258
ClearDominanceInformation()259 void HGraph::ClearDominanceInformation() {
260 for (HBasicBlock* block : GetActiveBlocks()) {
261 block->ClearDominanceInformation();
262 }
263 reverse_post_order_.clear();
264 }
265
ClearLoopInformation()266 void HGraph::ClearLoopInformation() {
267 SetHasLoops(false);
268 SetHasIrreducibleLoops(false);
269 for (HBasicBlock* block : GetActiveBlocks()) {
270 block->SetLoopInformation(nullptr);
271 }
272 }
273
ClearDominanceInformation()274 void HBasicBlock::ClearDominanceInformation() {
275 dominated_blocks_.clear();
276 dominator_ = nullptr;
277 }
278
GetFirstInstructionDisregardMoves() const279 HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
280 HInstruction* instruction = GetFirstInstruction();
281 while (instruction->IsParallelMove()) {
282 instruction = instruction->GetNext();
283 }
284 return instruction;
285 }
286
UpdateDominatorOfSuccessor(HBasicBlock * block,HBasicBlock * successor)287 static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
288 DCHECK(ContainsElement(block->GetSuccessors(), successor));
289
290 HBasicBlock* old_dominator = successor->GetDominator();
291 HBasicBlock* new_dominator =
292 (old_dominator == nullptr) ? block
293 : CommonDominator::ForPair(old_dominator, block);
294
295 if (old_dominator == new_dominator) {
296 return false;
297 } else {
298 successor->SetDominator(new_dominator);
299 return true;
300 }
301 }
302
ComputeDominanceInformation()303 void HGraph::ComputeDominanceInformation() {
304 DCHECK(reverse_post_order_.empty());
305 reverse_post_order_.reserve(blocks_.size());
306 reverse_post_order_.push_back(entry_block_);
307
308 // Allocate memory from local ScopedArenaAllocator.
309 ScopedArenaAllocator allocator(GetArenaStack());
310 // Number of visits of a given node, indexed by block id.
311 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
312 // Number of successors visited from a given node, indexed by block id.
313 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
314 0u,
315 allocator.Adapter(kArenaAllocGraphBuilder));
316 // Nodes for which we need to visit successors.
317 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
318 constexpr size_t kDefaultWorklistSize = 8;
319 worklist.reserve(kDefaultWorklistSize);
320 worklist.push_back(entry_block_);
321
322 while (!worklist.empty()) {
323 HBasicBlock* current = worklist.back();
324 uint32_t current_id = current->GetBlockId();
325 if (successors_visited[current_id] == current->GetSuccessors().size()) {
326 worklist.pop_back();
327 } else {
328 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
329 UpdateDominatorOfSuccessor(current, successor);
330
331 // Once all the forward edges have been visited, we know the immediate
332 // dominator of the block. We can then start visiting its successors.
333 if (++visits[successor->GetBlockId()] ==
334 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
335 reverse_post_order_.push_back(successor);
336 worklist.push_back(successor);
337 }
338 }
339 }
340
341 // Check if the graph has back edges not dominated by their respective headers.
342 // If so, we need to update the dominators of those headers and recursively of
343 // their successors. We do that with a fix-point iteration over all blocks.
344 // The algorithm is guaranteed to terminate because it loops only if the sum
345 // of all dominator chains has decreased in the current iteration.
346 bool must_run_fix_point = false;
347 for (HBasicBlock* block : blocks_) {
348 if (block != nullptr &&
349 block->IsLoopHeader() &&
350 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
351 must_run_fix_point = true;
352 break;
353 }
354 }
355 if (must_run_fix_point) {
356 bool update_occurred = true;
357 while (update_occurred) {
358 update_occurred = false;
359 for (HBasicBlock* block : GetReversePostOrder()) {
360 for (HBasicBlock* successor : block->GetSuccessors()) {
361 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
362 }
363 }
364 }
365 }
366
367 // Make sure that there are no remaining blocks whose dominator information
368 // needs to be updated.
369 if (kIsDebugBuild) {
370 for (HBasicBlock* block : GetReversePostOrder()) {
371 for (HBasicBlock* successor : block->GetSuccessors()) {
372 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
373 }
374 }
375 }
376
377 // Populate `dominated_blocks_` information after computing all dominators.
378 // The potential presence of irreducible loops requires to do it after.
379 for (HBasicBlock* block : GetReversePostOrder()) {
380 if (!block->IsEntryBlock()) {
381 block->GetDominator()->AddDominatedBlock(block);
382 }
383 }
384 }
385
SplitEdge(HBasicBlock * block,HBasicBlock * successor)386 HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
387 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
388 AddBlock(new_block);
389 // Use `InsertBetween` to ensure the predecessor index and successor index of
390 // `block` and `successor` are preserved.
391 new_block->InsertBetween(block, successor);
392 return new_block;
393 }
394
SplitCriticalEdge(HBasicBlock * block,HBasicBlock * successor)395 void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
396 // Insert a new node between `block` and `successor` to split the
397 // critical edge.
398 HBasicBlock* new_block = SplitEdge(block, successor);
399 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
400 if (successor->IsLoopHeader()) {
401 // If we split at a back edge boundary, make the new block the back edge.
402 HLoopInformation* info = successor->GetLoopInformation();
403 if (info->IsBackEdge(*block)) {
404 info->RemoveBackEdge(block);
405 info->AddBackEdge(new_block);
406 }
407 }
408 }
409
SplitEdgeAndUpdateRPO(HBasicBlock * block,HBasicBlock * successor)410 HBasicBlock* HGraph::SplitEdgeAndUpdateRPO(HBasicBlock* block, HBasicBlock* successor) {
411 HBasicBlock* new_block = SplitEdge(block, successor);
412 // In the RPO we have {... , block, ... , successor}. We want to insert `new_block` right after
413 // `block` to have a consistent RPO without recomputing the whole graph's RPO.
414 reverse_post_order_.insert(
415 reverse_post_order_.begin() + IndexOfElement(reverse_post_order_, block) + 1, new_block);
416 return new_block;
417 }
418
419 // Reorder phi inputs to match reordering of the block's predecessors.
FixPhisAfterPredecessorsReodering(HBasicBlock * block,size_t first,size_t second)420 static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
421 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
422 HPhi* phi = it.Current()->AsPhi();
423 HInstruction* first_instr = phi->InputAt(first);
424 HInstruction* second_instr = phi->InputAt(second);
425 phi->ReplaceInput(first_instr, second);
426 phi->ReplaceInput(second_instr, first);
427 }
428 }
429
430 // Make sure that the first predecessor of a loop header is the incoming block.
OrderLoopHeaderPredecessors(HBasicBlock * header)431 void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
432 DCHECK(header->IsLoopHeader());
433 HLoopInformation* info = header->GetLoopInformation();
434 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
435 HBasicBlock* to_swap = header->GetPredecessors()[0];
436 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
437 HBasicBlock* predecessor = header->GetPredecessors()[pred];
438 if (!info->IsBackEdge(*predecessor)) {
439 header->predecessors_[pred] = to_swap;
440 header->predecessors_[0] = predecessor;
441 FixPhisAfterPredecessorsReodering(header, 0, pred);
442 break;
443 }
444 }
445 }
446 }
447
448 // Transform control flow of the loop to a single preheader format (don't touch the data flow).
449 // New_preheader can be already among the header predecessors - this situation will be correctly
450 // processed.
FixControlForNewSinglePreheader(HBasicBlock * header,HBasicBlock * new_preheader)451 static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
452 HLoopInformation* loop_info = header->GetLoopInformation();
453 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
454 HBasicBlock* predecessor = header->GetPredecessors()[pred];
455 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
456 predecessor->ReplaceSuccessor(header, new_preheader);
457 pred--;
458 }
459 }
460 }
461
462 // == Before == == After ==
463 // _________ _________ _________ _________
464 // | B0 | | B1 | (old preheaders) | B0 | | B1 |
465 // |=========| |=========| |=========| |=========|
466 // | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
467 // |_________| |_________| |_________| |_________|
468 // \ / \ /
469 // \ / ___v____________v___
470 // \ / (new preheader) | B20 <- B0, B1 |
471 // | | |====================|
472 // | | | i20 = phi(i0, i1) |
473 // | | |____________________|
474 // | | |
475 // /\ | | /\ /\ | /\
476 // / v_______v_________v_______v \ / v___________v_____________v \
477 // | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
478 // | |===========================| | (header) | |===========================| |
479 // | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
480 // | |___________________________| | | |___________________________| |
481 // | / \ | | / \ |
482 // | ... ... | | ... ... |
483 // | _________ _________ | | _________ _________ |
484 // | | B2 | | B3 | | | | B2 | | B3 | |
485 // | |=========| |=========| | (back edges) | |=========| |=========| |
486 // | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
487 // | |_________| |_________| | | |_________| |_________| |
488 // \ / \ / \ / \ /
489 // \___/ \___/ \___/ \___/
490 //
TransformLoopToSinglePreheaderFormat(HBasicBlock * header)491 void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
492 HLoopInformation* loop_info = header->GetLoopInformation();
493
494 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
495 AddBlock(preheader);
496 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
497
498 // If the old header has no Phis then we only need to fix the control flow.
499 if (header->GetPhis().IsEmpty()) {
500 FixControlForNewSinglePreheader(header, preheader);
501 preheader->AddSuccessor(header);
502 return;
503 }
504
505 // Find the first non-back edge block in the header's predecessors list.
506 size_t first_nonbackedge_pred_pos = 0;
507 bool found = false;
508 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
509 HBasicBlock* predecessor = header->GetPredecessors()[pred];
510 if (!loop_info->IsBackEdge(*predecessor)) {
511 first_nonbackedge_pred_pos = pred;
512 found = true;
513 break;
514 }
515 }
516
517 DCHECK(found);
518
519 // Fix the data-flow.
520 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
521 HPhi* header_phi = it.Current()->AsPhi();
522
523 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
524 header_phi->GetRegNumber(),
525 0,
526 header_phi->GetType());
527 if (header_phi->GetType() == DataType::Type::kReference) {
528 preheader_phi->SetReferenceTypeInfoIfValid(header_phi->GetReferenceTypeInfo());
529 }
530 preheader->AddPhi(preheader_phi);
531
532 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
533 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
534 preheader_phi->AddInput(orig_input);
535
536 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
537 input_pos < header_phi->InputCount();
538 input_pos++) {
539 HInstruction* input = header_phi->InputAt(input_pos);
540 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
541
542 if (loop_info->Contains(*pred_block)) {
543 DCHECK(loop_info->IsBackEdge(*pred_block));
544 } else {
545 preheader_phi->AddInput(input);
546 header_phi->RemoveInputAt(input_pos);
547 input_pos--;
548 }
549 }
550 }
551
552 // Fix the control-flow.
553 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
554 preheader->InsertBetween(first_pred, header);
555
556 FixControlForNewSinglePreheader(header, preheader);
557 }
558
SimplifyLoop(HBasicBlock * header)559 void HGraph::SimplifyLoop(HBasicBlock* header) {
560 HLoopInformation* info = header->GetLoopInformation();
561
562 // Make sure the loop has only one pre header. This simplifies SSA building by having
563 // to just look at the pre header to know which locals are initialized at entry of the
564 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
565 // this graph.
566 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
567 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
568 TransformLoopToSinglePreheaderFormat(header);
569 }
570
571 OrderLoopHeaderPredecessors(header);
572
573 HInstruction* first_instruction = header->GetFirstInstruction();
574 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
575 // Called from DeadBlockElimination. Update SuspendCheck pointer.
576 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
577 }
578 }
579
ComputeTryBlockInformation()580 void HGraph::ComputeTryBlockInformation() {
581 // Iterate in reverse post order to propagate try membership information from
582 // predecessors to their successors.
583 bool graph_has_try_catch = false;
584
585 for (HBasicBlock* block : GetReversePostOrder()) {
586 if (block->IsEntryBlock() || block->IsCatchBlock()) {
587 // Catch blocks after simplification have only exceptional predecessors
588 // and hence are never in tries.
589 continue;
590 }
591
592 // Infer try membership from the first predecessor. Having simplified loops,
593 // the first predecessor can never be a back edge and therefore it must have
594 // been visited already and had its try membership set.
595 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
596 DCHECK_IMPLIES(block->IsLoopHeader(),
597 !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
598 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
599 graph_has_try_catch |= try_entry != nullptr;
600 if (try_entry != nullptr &&
601 (block->GetTryCatchInformation() == nullptr ||
602 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
603 // We are either setting try block membership for the first time or it
604 // has changed.
605 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
606 }
607 }
608
609 SetHasTryCatch(graph_has_try_catch);
610 }
611
SimplifyCFG()612 void HGraph::SimplifyCFG() {
613 // Simplify the CFG for future analysis, and code generation:
614 // (1): Split critical edges.
615 // (2): Simplify loops by having only one preheader.
616 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
617 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
618 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
619 HBasicBlock* block = blocks_[block_id];
620 if (block == nullptr) continue;
621 if (block->GetSuccessors().size() > 1) {
622 // Only split normal-flow edges. We cannot split exceptional edges as they
623 // are synthesized (approximate real control flow), and we do not need to
624 // anyway. Moves that would be inserted there are performed by the runtime.
625 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
626 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
627 HBasicBlock* successor = normal_successors[j];
628 DCHECK(!successor->IsCatchBlock());
629 if (successor == exit_block_) {
630 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
631 // do not want to split because Goto->Exit is not allowed.
632 DCHECK(block->IsSingleTryBoundary());
633 } else if (successor->GetPredecessors().size() > 1) {
634 SplitCriticalEdge(block, successor);
635 // SplitCriticalEdge could have invalidated the `normal_successors`
636 // ArrayRef. We must re-acquire it.
637 normal_successors = block->GetNormalSuccessors();
638 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
639 DCHECK_EQ(e, normal_successors.size());
640 }
641 }
642 }
643 if (block->IsLoopHeader()) {
644 SimplifyLoop(block);
645 } else if (!block->IsEntryBlock() &&
646 block->GetFirstInstruction() != nullptr &&
647 block->GetFirstInstruction()->IsSuspendCheck()) {
648 // We are being called by the dead code elimiation pass, and what used to be
649 // a loop got dismantled. Just remove the suspend check.
650 block->RemoveInstruction(block->GetFirstInstruction());
651 }
652 }
653 }
654
AnalyzeLoops() const655 GraphAnalysisResult HGraph::AnalyzeLoops() const {
656 // We iterate post order to ensure we visit inner loops before outer loops.
657 // `PopulateRecursive` needs this guarantee to know whether a natural loop
658 // contains an irreducible loop.
659 for (HBasicBlock* block : GetPostOrder()) {
660 if (block->IsLoopHeader()) {
661 if (block->IsCatchBlock()) {
662 // TODO: Dealing with exceptional back edges could be tricky because
663 // they only approximate the real control flow. Bail out for now.
664 VLOG(compiler) << "Not compiled: Exceptional back edges";
665 return kAnalysisFailThrowCatchLoop;
666 }
667 block->GetLoopInformation()->Populate();
668 }
669 }
670 return kAnalysisSuccess;
671 }
672
Dump(std::ostream & os)673 void HLoopInformation::Dump(std::ostream& os) {
674 os << "header: " << header_->GetBlockId() << std::endl;
675 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
676 for (HBasicBlock* block : back_edges_) {
677 os << "back edge: " << block->GetBlockId() << std::endl;
678 }
679 for (HBasicBlock* block : header_->GetPredecessors()) {
680 os << "predecessor: " << block->GetBlockId() << std::endl;
681 }
682 for (uint32_t idx : blocks_.Indexes()) {
683 os << " in loop: " << idx << std::endl;
684 }
685 }
686
687 template <class InstructionType, typename ValueType>
CreateConstant(ValueType value,ArenaSafeMap<ValueType,InstructionType * > * cache)688 InstructionType* HGraph::CreateConstant(ValueType value,
689 ArenaSafeMap<ValueType, InstructionType*>* cache) {
690 // Try to find an existing constant of the given value.
691 InstructionType* constant = nullptr;
692 auto cached_constant = cache->find(value);
693 if (cached_constant != cache->end()) {
694 constant = cached_constant->second;
695 }
696
697 // If not found or previously deleted, create and cache a new instruction.
698 // Don't bother reviving a previously deleted instruction, for simplicity.
699 if (constant == nullptr || constant->GetBlock() == nullptr) {
700 constant = new (allocator_) InstructionType(value);
701 cache->Overwrite(value, constant);
702 InsertConstant(constant);
703 }
704 return constant;
705 }
706
InsertConstant(HConstant * constant)707 void HGraph::InsertConstant(HConstant* constant) {
708 // New constants are inserted before the SuspendCheck at the bottom of the
709 // entry block. Note that this method can be called from the graph builder and
710 // the entry block therefore may not end with SuspendCheck->Goto yet.
711 HInstruction* insert_before = nullptr;
712
713 HInstruction* gota = entry_block_->GetLastInstruction();
714 if (gota != nullptr && gota->IsGoto()) {
715 HInstruction* suspend_check = gota->GetPrevious();
716 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
717 insert_before = suspend_check;
718 } else {
719 insert_before = gota;
720 }
721 }
722
723 if (insert_before == nullptr) {
724 entry_block_->AddInstruction(constant);
725 } else {
726 entry_block_->InsertInstructionBefore(constant, insert_before);
727 }
728 }
729
GetNullConstant()730 HNullConstant* HGraph::GetNullConstant() {
731 // For simplicity, don't bother reviving the cached null constant if it is
732 // not null and not in a block. Otherwise, we need to clear the instruction
733 // id and/or any invariants the graph is assuming when adding new instructions.
734 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
735 cached_null_constant_ = new (allocator_) HNullConstant();
736 cached_null_constant_->SetReferenceTypeInfo(GetInexactObjectRti());
737 InsertConstant(cached_null_constant_);
738 }
739 if (kIsDebugBuild) {
740 ScopedObjectAccess soa(Thread::Current());
741 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
742 }
743 return cached_null_constant_;
744 }
745
GetIntConstant(int32_t value)746 HIntConstant* HGraph::GetIntConstant(int32_t value) {
747 return CreateConstant(value, &cached_int_constants_);
748 }
749
GetLongConstant(int64_t value)750 HLongConstant* HGraph::GetLongConstant(int64_t value) {
751 return CreateConstant(value, &cached_long_constants_);
752 }
753
GetFloatConstant(float value)754 HFloatConstant* HGraph::GetFloatConstant(float value) {
755 return CreateConstant(bit_cast<int32_t, float>(value), &cached_float_constants_);
756 }
757
GetDoubleConstant(double value)758 HDoubleConstant* HGraph::GetDoubleConstant(double value) {
759 return CreateConstant(bit_cast<int64_t, double>(value), &cached_double_constants_);
760 }
761
GetCurrentMethod()762 HCurrentMethod* HGraph::GetCurrentMethod() {
763 // For simplicity, don't bother reviving the cached current method if it is
764 // not null and not in a block. Otherwise, we need to clear the instruction
765 // id and/or any invariants the graph is assuming when adding new instructions.
766 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
767 cached_current_method_ = new (allocator_) HCurrentMethod(
768 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
769 entry_block_->GetDexPc());
770 if (entry_block_->GetFirstInstruction() == nullptr) {
771 entry_block_->AddInstruction(cached_current_method_);
772 } else {
773 entry_block_->InsertInstructionBefore(
774 cached_current_method_, entry_block_->GetFirstInstruction());
775 }
776 }
777 return cached_current_method_;
778 }
779
GetMethodName() const780 const char* HGraph::GetMethodName() const {
781 const dex::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
782 return dex_file_.GetMethodName(method_id);
783 }
784
PrettyMethod(bool with_signature) const785 std::string HGraph::PrettyMethod(bool with_signature) const {
786 return dex_file_.PrettyMethod(method_idx_, with_signature);
787 }
788
GetConstant(DataType::Type type,int64_t value)789 HConstant* HGraph::GetConstant(DataType::Type type, int64_t value) {
790 switch (type) {
791 case DataType::Type::kBool:
792 DCHECK(IsUint<1>(value));
793 FALLTHROUGH_INTENDED;
794 case DataType::Type::kUint8:
795 case DataType::Type::kInt8:
796 case DataType::Type::kUint16:
797 case DataType::Type::kInt16:
798 case DataType::Type::kInt32:
799 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
800 return GetIntConstant(static_cast<int32_t>(value));
801
802 case DataType::Type::kInt64:
803 return GetLongConstant(value);
804
805 default:
806 LOG(FATAL) << "Unsupported constant type";
807 UNREACHABLE();
808 }
809 }
810
CacheFloatConstant(HFloatConstant * constant)811 void HGraph::CacheFloatConstant(HFloatConstant* constant) {
812 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
813 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
814 cached_float_constants_.Overwrite(value, constant);
815 }
816
CacheDoubleConstant(HDoubleConstant * constant)817 void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
818 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
819 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
820 cached_double_constants_.Overwrite(value, constant);
821 }
822
Add(HBasicBlock * block)823 void HLoopInformation::Add(HBasicBlock* block) {
824 blocks_.SetBit(block->GetBlockId());
825 }
826
Remove(HBasicBlock * block)827 void HLoopInformation::Remove(HBasicBlock* block) {
828 blocks_.ClearBit(block->GetBlockId());
829 }
830
PopulateRecursive(HBasicBlock * block)831 void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
832 if (blocks_.IsBitSet(block->GetBlockId())) {
833 return;
834 }
835
836 blocks_.SetBit(block->GetBlockId());
837 block->SetInLoop(this);
838 if (block->IsLoopHeader()) {
839 // We're visiting loops in post-order, so inner loops must have been
840 // populated already.
841 DCHECK(block->GetLoopInformation()->IsPopulated());
842 if (block->GetLoopInformation()->IsIrreducible()) {
843 contains_irreducible_loop_ = true;
844 }
845 }
846 for (HBasicBlock* predecessor : block->GetPredecessors()) {
847 PopulateRecursive(predecessor);
848 }
849 }
850
PopulateIrreducibleRecursive(HBasicBlock * block,ArenaBitVector * finalized)851 void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
852 size_t block_id = block->GetBlockId();
853
854 // If `block` is in `finalized`, we know its membership in the loop has been
855 // decided and it does not need to be revisited.
856 if (finalized->IsBitSet(block_id)) {
857 return;
858 }
859
860 bool is_finalized = false;
861 if (block->IsLoopHeader()) {
862 // If we hit a loop header in an irreducible loop, we first check if the
863 // pre header of that loop belongs to the currently analyzed loop. If it does,
864 // then we visit the back edges.
865 // Note that we cannot use GetPreHeader, as the loop may have not been populated
866 // yet.
867 HBasicBlock* pre_header = block->GetPredecessors()[0];
868 PopulateIrreducibleRecursive(pre_header, finalized);
869 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
870 block->SetInLoop(this);
871 blocks_.SetBit(block_id);
872 finalized->SetBit(block_id);
873 is_finalized = true;
874
875 HLoopInformation* info = block->GetLoopInformation();
876 for (HBasicBlock* back_edge : info->GetBackEdges()) {
877 PopulateIrreducibleRecursive(back_edge, finalized);
878 }
879 }
880 } else {
881 // Visit all predecessors. If one predecessor is part of the loop, this
882 // block is also part of this loop.
883 for (HBasicBlock* predecessor : block->GetPredecessors()) {
884 PopulateIrreducibleRecursive(predecessor, finalized);
885 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
886 block->SetInLoop(this);
887 blocks_.SetBit(block_id);
888 finalized->SetBit(block_id);
889 is_finalized = true;
890 }
891 }
892 }
893
894 // All predecessors have been recursively visited. Mark finalized if not marked yet.
895 if (!is_finalized) {
896 finalized->SetBit(block_id);
897 }
898 }
899
Populate()900 void HLoopInformation::Populate() {
901 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
902 // Populate this loop: starting with the back edge, recursively add predecessors
903 // that are not already part of that loop. Set the header as part of the loop
904 // to end the recursion.
905 // This is a recursive implementation of the algorithm described in
906 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
907 HGraph* graph = header_->GetGraph();
908 blocks_.SetBit(header_->GetBlockId());
909 header_->SetInLoop(this);
910
911 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
912
913 if (is_irreducible_loop) {
914 // Allocate memory from local ScopedArenaAllocator.
915 ScopedArenaAllocator allocator(graph->GetArenaStack());
916 ArenaBitVector visited(&allocator,
917 graph->GetBlocks().size(),
918 /* expandable= */ false,
919 kArenaAllocGraphBuilder);
920 // Stop marking blocks at the loop header.
921 visited.SetBit(header_->GetBlockId());
922
923 for (HBasicBlock* back_edge : GetBackEdges()) {
924 PopulateIrreducibleRecursive(back_edge, &visited);
925 }
926 } else {
927 for (HBasicBlock* back_edge : GetBackEdges()) {
928 PopulateRecursive(back_edge);
929 }
930 }
931
932 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
933 // When compiling in OSR mode, all loops in the compiled method may be entered
934 // from the interpreter. We treat this OSR entry point just like an extra entry
935 // to an irreducible loop, so we need to mark the method's loops as irreducible.
936 // This does not apply to inlined loops which do not act as OSR entry points.
937 if (suspend_check_ == nullptr) {
938 // Just building the graph in OSR mode, this loop is not inlined. We never build an
939 // inner graph in OSR mode as we can do OSR transition only from the outer method.
940 is_irreducible_loop = true;
941 } else {
942 // Look at the suspend check's environment to determine if the loop was inlined.
943 DCHECK(suspend_check_->HasEnvironment());
944 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
945 is_irreducible_loop = true;
946 }
947 }
948 }
949 if (is_irreducible_loop) {
950 irreducible_ = true;
951 contains_irreducible_loop_ = true;
952 graph->SetHasIrreducibleLoops(true);
953 }
954 graph->SetHasLoops(true);
955 }
956
PopulateInnerLoopUpwards(HLoopInformation * inner_loop)957 void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
958 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
959 blocks_.Union(&inner_loop->blocks_);
960 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
961 if (outer_loop != nullptr) {
962 outer_loop->PopulateInnerLoopUpwards(this);
963 }
964 }
965
GetPreHeader() const966 HBasicBlock* HLoopInformation::GetPreHeader() const {
967 HBasicBlock* block = header_->GetPredecessors()[0];
968 DCHECK(irreducible_ || (block == header_->GetDominator()));
969 return block;
970 }
971
Contains(const HBasicBlock & block) const972 bool HLoopInformation::Contains(const HBasicBlock& block) const {
973 return blocks_.IsBitSet(block.GetBlockId());
974 }
975
IsIn(const HLoopInformation & other) const976 bool HLoopInformation::IsIn(const HLoopInformation& other) const {
977 return other.blocks_.IsBitSet(header_->GetBlockId());
978 }
979
IsDefinedOutOfTheLoop(HInstruction * instruction) const980 bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
981 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
982 }
983
GetLifetimeEnd() const984 size_t HLoopInformation::GetLifetimeEnd() const {
985 size_t last_position = 0;
986 for (HBasicBlock* back_edge : GetBackEdges()) {
987 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
988 }
989 return last_position;
990 }
991
HasBackEdgeNotDominatedByHeader() const992 bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
993 for (HBasicBlock* back_edge : GetBackEdges()) {
994 DCHECK(back_edge->GetDominator() != nullptr);
995 if (!header_->Dominates(back_edge)) {
996 return true;
997 }
998 }
999 return false;
1000 }
1001
DominatesAllBackEdges(HBasicBlock * block)1002 bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
1003 for (HBasicBlock* back_edge : GetBackEdges()) {
1004 if (!block->Dominates(back_edge)) {
1005 return false;
1006 }
1007 }
1008 return true;
1009 }
1010
1011
HasExitEdge() const1012 bool HLoopInformation::HasExitEdge() const {
1013 // Determine if this loop has at least one exit edge.
1014 HBlocksInLoopReversePostOrderIterator it_loop(*this);
1015 for (; !it_loop.Done(); it_loop.Advance()) {
1016 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1017 if (!Contains(*successor)) {
1018 return true;
1019 }
1020 }
1021 }
1022 return false;
1023 }
1024
Dominates(const HBasicBlock * other) const1025 bool HBasicBlock::Dominates(const HBasicBlock* other) const {
1026 // Walk up the dominator tree from `other`, to find out if `this`
1027 // is an ancestor.
1028 const HBasicBlock* current = other;
1029 while (current != nullptr) {
1030 if (current == this) {
1031 return true;
1032 }
1033 current = current->GetDominator();
1034 }
1035 return false;
1036 }
1037
UpdateInputsUsers(HInstruction * instruction)1038 static void UpdateInputsUsers(HInstruction* instruction) {
1039 HInputsRef inputs = instruction->GetInputs();
1040 for (size_t i = 0; i < inputs.size(); ++i) {
1041 inputs[i]->AddUseAt(instruction, i);
1042 }
1043 // Environment should be created later.
1044 DCHECK(!instruction->HasEnvironment());
1045 }
1046
ReplaceAndRemovePhiWith(HPhi * initial,HPhi * replacement)1047 void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
1048 DCHECK(initial->GetBlock() == this);
1049 InsertPhiAfter(replacement, initial);
1050 initial->ReplaceWith(replacement);
1051 RemovePhi(initial);
1052 }
1053
ReplaceAndRemoveInstructionWith(HInstruction * initial,HInstruction * replacement)1054 void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
1055 HInstruction* replacement) {
1056 DCHECK(initial->GetBlock() == this);
1057 if (initial->IsControlFlow()) {
1058 // We can only replace a control flow instruction with another control flow instruction.
1059 DCHECK(replacement->IsControlFlow());
1060 DCHECK_EQ(replacement->GetId(), -1);
1061 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
1062 DCHECK_EQ(initial->GetBlock(), this);
1063 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
1064 DCHECK(initial->GetUses().empty());
1065 DCHECK(initial->GetEnvUses().empty());
1066 replacement->SetBlock(this);
1067 replacement->SetId(GetGraph()->GetNextInstructionId());
1068 instructions_.InsertInstructionBefore(replacement, initial);
1069 UpdateInputsUsers(replacement);
1070 } else {
1071 InsertInstructionBefore(replacement, initial);
1072 initial->ReplaceWith(replacement);
1073 }
1074 RemoveInstruction(initial);
1075 }
1076
Add(HInstructionList * instruction_list,HBasicBlock * block,HInstruction * instruction)1077 static void Add(HInstructionList* instruction_list,
1078 HBasicBlock* block,
1079 HInstruction* instruction) {
1080 DCHECK(instruction->GetBlock() == nullptr);
1081 DCHECK_EQ(instruction->GetId(), -1);
1082 instruction->SetBlock(block);
1083 instruction->SetId(block->GetGraph()->GetNextInstructionId());
1084 UpdateInputsUsers(instruction);
1085 instruction_list->AddInstruction(instruction);
1086 }
1087
AddInstruction(HInstruction * instruction)1088 void HBasicBlock::AddInstruction(HInstruction* instruction) {
1089 Add(&instructions_, this, instruction);
1090 }
1091
AddPhi(HPhi * phi)1092 void HBasicBlock::AddPhi(HPhi* phi) {
1093 Add(&phis_, this, phi);
1094 }
1095
InsertInstructionBefore(HInstruction * instruction,HInstruction * cursor)1096 void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1097 DCHECK(!cursor->IsPhi());
1098 DCHECK(!instruction->IsPhi());
1099 DCHECK_EQ(instruction->GetId(), -1);
1100 DCHECK_NE(cursor->GetId(), -1);
1101 DCHECK_EQ(cursor->GetBlock(), this);
1102 DCHECK(!instruction->IsControlFlow());
1103 instruction->SetBlock(this);
1104 instruction->SetId(GetGraph()->GetNextInstructionId());
1105 UpdateInputsUsers(instruction);
1106 instructions_.InsertInstructionBefore(instruction, cursor);
1107 }
1108
InsertInstructionAfter(HInstruction * instruction,HInstruction * cursor)1109 void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1110 DCHECK(!cursor->IsPhi());
1111 DCHECK(!instruction->IsPhi());
1112 DCHECK_EQ(instruction->GetId(), -1);
1113 DCHECK_NE(cursor->GetId(), -1);
1114 DCHECK_EQ(cursor->GetBlock(), this);
1115 DCHECK(!instruction->IsControlFlow());
1116 DCHECK(!cursor->IsControlFlow());
1117 instruction->SetBlock(this);
1118 instruction->SetId(GetGraph()->GetNextInstructionId());
1119 UpdateInputsUsers(instruction);
1120 instructions_.InsertInstructionAfter(instruction, cursor);
1121 }
1122
InsertPhiAfter(HPhi * phi,HPhi * cursor)1123 void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1124 DCHECK_EQ(phi->GetId(), -1);
1125 DCHECK_NE(cursor->GetId(), -1);
1126 DCHECK_EQ(cursor->GetBlock(), this);
1127 phi->SetBlock(this);
1128 phi->SetId(GetGraph()->GetNextInstructionId());
1129 UpdateInputsUsers(phi);
1130 phis_.InsertInstructionAfter(phi, cursor);
1131 }
1132
Remove(HInstructionList * instruction_list,HBasicBlock * block,HInstruction * instruction,bool ensure_safety)1133 static void Remove(HInstructionList* instruction_list,
1134 HBasicBlock* block,
1135 HInstruction* instruction,
1136 bool ensure_safety) {
1137 DCHECK_EQ(block, instruction->GetBlock());
1138 instruction->SetBlock(nullptr);
1139 instruction_list->RemoveInstruction(instruction);
1140 if (ensure_safety) {
1141 DCHECK(instruction->GetUses().empty());
1142 DCHECK(instruction->GetEnvUses().empty());
1143 RemoveAsUser(instruction);
1144 }
1145 }
1146
RemoveInstruction(HInstruction * instruction,bool ensure_safety)1147 void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
1148 DCHECK(!instruction->IsPhi());
1149 Remove(&instructions_, this, instruction, ensure_safety);
1150 }
1151
RemovePhi(HPhi * phi,bool ensure_safety)1152 void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1153 Remove(&phis_, this, phi, ensure_safety);
1154 }
1155
RemoveInstructionOrPhi(HInstruction * instruction,bool ensure_safety)1156 void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1157 if (instruction->IsPhi()) {
1158 RemovePhi(instruction->AsPhi(), ensure_safety);
1159 } else {
1160 RemoveInstruction(instruction, ensure_safety);
1161 }
1162 }
1163
CopyFrom(ArrayRef<HInstruction * const> locals)1164 void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
1165 for (size_t i = 0; i < locals.size(); i++) {
1166 HInstruction* instruction = locals[i];
1167 SetRawEnvAt(i, instruction);
1168 if (instruction != nullptr) {
1169 instruction->AddEnvUseAt(this, i);
1170 }
1171 }
1172 }
1173
CopyFrom(const HEnvironment * env)1174 void HEnvironment::CopyFrom(const HEnvironment* env) {
1175 for (size_t i = 0; i < env->Size(); i++) {
1176 HInstruction* instruction = env->GetInstructionAt(i);
1177 SetRawEnvAt(i, instruction);
1178 if (instruction != nullptr) {
1179 instruction->AddEnvUseAt(this, i);
1180 }
1181 }
1182 }
1183
CopyFromWithLoopPhiAdjustment(HEnvironment * env,HBasicBlock * loop_header)1184 void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1185 HBasicBlock* loop_header) {
1186 DCHECK(loop_header->IsLoopHeader());
1187 for (size_t i = 0; i < env->Size(); i++) {
1188 HInstruction* instruction = env->GetInstructionAt(i);
1189 SetRawEnvAt(i, instruction);
1190 if (instruction == nullptr) {
1191 continue;
1192 }
1193 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1194 // At the end of the loop pre-header, the corresponding value for instruction
1195 // is the first input of the phi.
1196 HInstruction* initial = instruction->AsPhi()->InputAt(0);
1197 SetRawEnvAt(i, initial);
1198 initial->AddEnvUseAt(this, i);
1199 } else {
1200 instruction->AddEnvUseAt(this, i);
1201 }
1202 }
1203 }
1204
RemoveAsUserOfInput(size_t index) const1205 void HEnvironment::RemoveAsUserOfInput(size_t index) const {
1206 const HUserRecord<HEnvironment*>& env_use = GetVRegs()[index];
1207 HInstruction* user = env_use.GetInstruction();
1208 auto before_env_use_node = env_use.GetBeforeUseNode();
1209 user->env_uses_.erase_after(before_env_use_node);
1210 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
1211 }
1212
ReplaceInput(HInstruction * replacement,size_t index)1213 void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1214 const HUserRecord<HEnvironment*>& env_use_record = GetVRegs()[index];
1215 HInstruction* orig_instr = env_use_record.GetInstruction();
1216
1217 DCHECK(orig_instr != replacement);
1218
1219 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1220 // Note: fixup_end remains valid across splice_after().
1221 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1222 : ++replacement->env_uses_.begin();
1223 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1224 env_use_record.GetInstruction()->env_uses_,
1225 before_use_node);
1226 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1227 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1228 }
1229
Dump(std::ostream & os,bool dump_args)1230 std::ostream& HInstruction::Dump(std::ostream& os, bool dump_args) {
1231 // Note: Handle the case where the instruction has been removed from
1232 // the graph to support debugging output for failed gtests.
1233 HGraph* graph = (GetBlock() != nullptr) ? GetBlock()->GetGraph() : nullptr;
1234 HGraphVisualizer::DumpInstruction(&os, graph, this);
1235 if (dump_args) {
1236 // Allocate memory from local ScopedArenaAllocator.
1237 std::optional<MallocArenaPool> local_arena_pool;
1238 std::optional<ArenaStack> local_arena_stack;
1239 if (UNLIKELY(graph == nullptr)) {
1240 local_arena_pool.emplace();
1241 local_arena_stack.emplace(&local_arena_pool.value());
1242 }
1243 ScopedArenaAllocator allocator(
1244 graph != nullptr ? graph->GetArenaStack() : &local_arena_stack.value());
1245 // Instructions that we already visited. We print each instruction only once.
1246 ArenaBitVector visited(&allocator,
1247 (graph != nullptr) ? graph->GetCurrentInstructionId() : 0u,
1248 /* expandable= */ (graph == nullptr),
1249 kArenaAllocMisc);
1250 visited.SetBit(GetId());
1251 // Keep a queue of instructions with their indentations.
1252 ScopedArenaDeque<std::pair<HInstruction*, size_t>> queue(allocator.Adapter(kArenaAllocMisc));
1253 auto add_args = [&queue](HInstruction* instruction, size_t indentation) {
1254 for (HInstruction* arg : ReverseRange(instruction->GetInputs())) {
1255 queue.emplace_front(arg, indentation);
1256 }
1257 };
1258 add_args(this, /*indentation=*/ 1u);
1259 while (!queue.empty()) {
1260 HInstruction* instruction;
1261 size_t indentation;
1262 std::tie(instruction, indentation) = queue.front();
1263 queue.pop_front();
1264 if (!visited.IsBitSet(instruction->GetId())) {
1265 visited.SetBit(instruction->GetId());
1266 os << '\n';
1267 for (size_t i = 0; i != indentation; ++i) {
1268 os << " ";
1269 }
1270 HGraphVisualizer::DumpInstruction(&os, graph, instruction);
1271 add_args(instruction, indentation + 1u);
1272 }
1273 }
1274 }
1275 return os;
1276 }
1277
GetNextDisregardingMoves() const1278 HInstruction* HInstruction::GetNextDisregardingMoves() const {
1279 HInstruction* next = GetNext();
1280 while (next != nullptr && next->IsParallelMove()) {
1281 next = next->GetNext();
1282 }
1283 return next;
1284 }
1285
GetPreviousDisregardingMoves() const1286 HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1287 HInstruction* previous = GetPrevious();
1288 while (previous != nullptr && previous->IsParallelMove()) {
1289 previous = previous->GetPrevious();
1290 }
1291 return previous;
1292 }
1293
AddInstruction(HInstruction * instruction)1294 void HInstructionList::AddInstruction(HInstruction* instruction) {
1295 if (first_instruction_ == nullptr) {
1296 DCHECK(last_instruction_ == nullptr);
1297 first_instruction_ = last_instruction_ = instruction;
1298 } else {
1299 DCHECK(last_instruction_ != nullptr);
1300 last_instruction_->next_ = instruction;
1301 instruction->previous_ = last_instruction_;
1302 last_instruction_ = instruction;
1303 }
1304 }
1305
InsertInstructionBefore(HInstruction * instruction,HInstruction * cursor)1306 void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1307 DCHECK(Contains(cursor));
1308 if (cursor == first_instruction_) {
1309 cursor->previous_ = instruction;
1310 instruction->next_ = cursor;
1311 first_instruction_ = instruction;
1312 } else {
1313 instruction->previous_ = cursor->previous_;
1314 instruction->next_ = cursor;
1315 cursor->previous_ = instruction;
1316 instruction->previous_->next_ = instruction;
1317 }
1318 }
1319
InsertInstructionAfter(HInstruction * instruction,HInstruction * cursor)1320 void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1321 DCHECK(Contains(cursor));
1322 if (cursor == last_instruction_) {
1323 cursor->next_ = instruction;
1324 instruction->previous_ = cursor;
1325 last_instruction_ = instruction;
1326 } else {
1327 instruction->next_ = cursor->next_;
1328 instruction->previous_ = cursor;
1329 cursor->next_ = instruction;
1330 instruction->next_->previous_ = instruction;
1331 }
1332 }
1333
RemoveInstruction(HInstruction * instruction)1334 void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1335 if (instruction->previous_ != nullptr) {
1336 instruction->previous_->next_ = instruction->next_;
1337 }
1338 if (instruction->next_ != nullptr) {
1339 instruction->next_->previous_ = instruction->previous_;
1340 }
1341 if (instruction == first_instruction_) {
1342 first_instruction_ = instruction->next_;
1343 }
1344 if (instruction == last_instruction_) {
1345 last_instruction_ = instruction->previous_;
1346 }
1347 }
1348
Contains(HInstruction * instruction) const1349 bool HInstructionList::Contains(HInstruction* instruction) const {
1350 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1351 if (it.Current() == instruction) {
1352 return true;
1353 }
1354 }
1355 return false;
1356 }
1357
FoundBefore(const HInstruction * instruction1,const HInstruction * instruction2) const1358 bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1359 const HInstruction* instruction2) const {
1360 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1361 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1362 if (it.Current() == instruction2) {
1363 return false;
1364 }
1365 if (it.Current() == instruction1) {
1366 return true;
1367 }
1368 }
1369 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1370 UNREACHABLE();
1371 }
1372
Dominates(HInstruction * other_instruction) const1373 bool HInstruction::Dominates(HInstruction* other_instruction) const {
1374 return other_instruction == this || StrictlyDominates(other_instruction);
1375 }
1376
StrictlyDominates(HInstruction * other_instruction) const1377 bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1378 if (other_instruction == this) {
1379 // An instruction does not strictly dominate itself.
1380 return false;
1381 }
1382 HBasicBlock* block = GetBlock();
1383 HBasicBlock* other_block = other_instruction->GetBlock();
1384 if (block != other_block) {
1385 return GetBlock()->Dominates(other_instruction->GetBlock());
1386 } else {
1387 // If both instructions are in the same block, ensure this
1388 // instruction comes before `other_instruction`.
1389 if (IsPhi()) {
1390 if (!other_instruction->IsPhi()) {
1391 // Phis appear before non phi-instructions so this instruction
1392 // dominates `other_instruction`.
1393 return true;
1394 } else {
1395 // There is no order among phis.
1396 LOG(FATAL) << "There is no dominance between phis of a same block.";
1397 UNREACHABLE();
1398 }
1399 } else {
1400 // `this` is not a phi.
1401 if (other_instruction->IsPhi()) {
1402 // Phis appear before non phi-instructions so this instruction
1403 // does not dominate `other_instruction`.
1404 return false;
1405 } else {
1406 // Check whether this instruction comes before
1407 // `other_instruction` in the instruction list.
1408 return block->GetInstructions().FoundBefore(this, other_instruction);
1409 }
1410 }
1411 }
1412 }
1413
RemoveEnvironment()1414 void HInstruction::RemoveEnvironment() {
1415 RemoveEnvironmentUses(this);
1416 environment_ = nullptr;
1417 }
1418
ReplaceWith(HInstruction * other)1419 void HInstruction::ReplaceWith(HInstruction* other) {
1420 DCHECK(other != nullptr);
1421 // Note: fixup_end remains valid across splice_after().
1422 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1423 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1424 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
1425
1426 // Note: env_fixup_end remains valid across splice_after().
1427 auto env_fixup_end =
1428 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1429 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1430 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
1431
1432 DCHECK(uses_.empty());
1433 DCHECK(env_uses_.empty());
1434 }
1435
ReplaceUsesDominatedBy(HInstruction * dominator,HInstruction * replacement,bool strictly_dominated)1436 void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator,
1437 HInstruction* replacement,
1438 bool strictly_dominated) {
1439 HBasicBlock* dominator_block = dominator->GetBlock();
1440 std::optional<ArenaBitVector> visited_blocks;
1441
1442 // Lazily compute the dominated blocks to faster calculation of domination afterwards.
1443 auto maybe_generate_visited_blocks = [&visited_blocks, this, dominator_block]() {
1444 if (visited_blocks.has_value()) {
1445 return;
1446 }
1447 HGraph* graph = GetBlock()->GetGraph();
1448 visited_blocks.emplace(graph->GetAllocator(),
1449 graph->GetBlocks().size(),
1450 /* expandable= */ false,
1451 kArenaAllocMisc);
1452 ScopedArenaAllocator allocator(graph->GetArenaStack());
1453 ScopedArenaQueue<const HBasicBlock*> worklist(allocator.Adapter(kArenaAllocMisc));
1454 worklist.push(dominator_block);
1455
1456 while (!worklist.empty()) {
1457 const HBasicBlock* current = worklist.front();
1458 worklist.pop();
1459 visited_blocks->SetBit(current->GetBlockId());
1460 for (HBasicBlock* dominated : current->GetDominatedBlocks()) {
1461 if (visited_blocks->IsBitSet(dominated->GetBlockId())) {
1462 continue;
1463 }
1464 worklist.push(dominated);
1465 }
1466 }
1467 };
1468
1469 const HUseList<HInstruction*>& uses = GetUses();
1470 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1471 HInstruction* user = it->GetUser();
1472 HBasicBlock* block = user->GetBlock();
1473 size_t index = it->GetIndex();
1474 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1475 ++it;
1476 bool dominated = false;
1477 if (dominator_block == block) {
1478 // Trickier case, call the other methods.
1479 dominated =
1480 strictly_dominated ? dominator->StrictlyDominates(user) : dominator->Dominates(user);
1481 } else {
1482 // Block domination.
1483 maybe_generate_visited_blocks();
1484 dominated = visited_blocks->IsBitSet(block->GetBlockId());
1485 }
1486
1487 if (dominated) {
1488 user->ReplaceInput(replacement, index);
1489 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1490 // If the input flows from a block dominated by `dominator`, we can replace it.
1491 // We do not perform this for catch phis as we don't have control flow support
1492 // for their inputs.
1493 HBasicBlock* predecessor = block->GetPredecessors()[index];
1494 maybe_generate_visited_blocks();
1495 if (visited_blocks->IsBitSet(predecessor->GetBlockId())) {
1496 user->ReplaceInput(replacement, index);
1497 }
1498 }
1499 }
1500 }
1501
ReplaceEnvUsesDominatedBy(HInstruction * dominator,HInstruction * replacement)1502 void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1503 const HUseList<HEnvironment*>& uses = GetEnvUses();
1504 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1505 HEnvironment* user = it->GetUser();
1506 size_t index = it->GetIndex();
1507 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1508 ++it;
1509 if (dominator->StrictlyDominates(user->GetHolder())) {
1510 user->ReplaceInput(replacement, index);
1511 }
1512 }
1513 }
1514
ReplaceInput(HInstruction * replacement,size_t index)1515 void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
1516 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
1517 if (input_use.GetInstruction() == replacement) {
1518 // Nothing to do.
1519 return;
1520 }
1521 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
1522 // Note: fixup_end remains valid across splice_after().
1523 auto fixup_end =
1524 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1525 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1526 input_use.GetInstruction()->uses_,
1527 before_use_node);
1528 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1529 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
1530 }
1531
EnvironmentSize() const1532 size_t HInstruction::EnvironmentSize() const {
1533 return HasEnvironment() ? environment_->Size() : 0;
1534 }
1535
AddInput(HInstruction * input)1536 void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
1537 DCHECK(input->GetBlock() != nullptr);
1538 inputs_.push_back(HUserRecord<HInstruction*>(input));
1539 input->AddUseAt(this, inputs_.size() - 1);
1540 }
1541
InsertInputAt(size_t index,HInstruction * input)1542 void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1543 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1544 input->AddUseAt(this, index);
1545 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1546 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1547 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1548 inputs_[i].GetUseNode()->SetIndex(i);
1549 }
1550 }
1551
RemoveInputAt(size_t index)1552 void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
1553 RemoveAsUserOfInput(index);
1554 inputs_.erase(inputs_.begin() + index);
1555 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1556 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1557 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1558 inputs_[i].GetUseNode()->SetIndex(i);
1559 }
1560 }
1561
RemoveAllInputs()1562 void HVariableInputSizeInstruction::RemoveAllInputs() {
1563 RemoveAsUserOfAllInputs();
1564 DCHECK(!HasNonEnvironmentUses());
1565
1566 inputs_.clear();
1567 DCHECK_EQ(0u, InputCount());
1568 }
1569
RemoveConstructorFences(HInstruction * instruction)1570 size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
1571 DCHECK(instruction->GetBlock() != nullptr);
1572 // Removing constructor fences only makes sense for instructions with an object return type.
1573 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
1574
1575 // Return how many instructions were removed for statistic purposes.
1576 size_t remove_count = 0;
1577
1578 // Efficient implementation that simultaneously (in one pass):
1579 // * Scans the uses list for all constructor fences.
1580 // * Deletes that constructor fence from the uses list of `instruction`.
1581 // * Deletes `instruction` from the constructor fence's inputs.
1582 // * Deletes the constructor fence if it now has 0 inputs.
1583
1584 const HUseList<HInstruction*>& uses = instruction->GetUses();
1585 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1586 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1587 const HUseListNode<HInstruction*>& use_node = *it;
1588 HInstruction* const use_instruction = use_node.GetUser();
1589
1590 // Advance the iterator immediately once we fetch the use_node.
1591 // Warning: If the input is removed, the current iterator becomes invalid.
1592 ++it;
1593
1594 if (use_instruction->IsConstructorFence()) {
1595 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1596 size_t input_index = use_node.GetIndex();
1597
1598 // Process the candidate instruction for removal
1599 // from the graph.
1600
1601 // Constructor fence instructions are never
1602 // used by other instructions.
1603 //
1604 // If we wanted to make this more generic, it
1605 // could be a runtime if statement.
1606 DCHECK(!ctor_fence->HasUses());
1607
1608 // A constructor fence's return type is "kPrimVoid"
1609 // and therefore it can't have any environment uses.
1610 DCHECK(!ctor_fence->HasEnvironmentUses());
1611
1612 // Remove the inputs first, otherwise removing the instruction
1613 // will try to remove its uses while we are already removing uses
1614 // and this operation will fail.
1615 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1616
1617 // Removing the input will also remove the `use_node`.
1618 // (Do not look at `use_node` after this, it will be a dangling reference).
1619 ctor_fence->RemoveInputAt(input_index);
1620
1621 // Once all inputs are removed, the fence is considered dead and
1622 // is removed.
1623 if (ctor_fence->InputCount() == 0u) {
1624 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
1625 ++remove_count;
1626 }
1627 }
1628 }
1629
1630 if (kIsDebugBuild) {
1631 // Post-condition checks:
1632 // * None of the uses of `instruction` are a constructor fence.
1633 // * The `instruction` itself did not get removed from a block.
1634 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1635 CHECK(!use_node.GetUser()->IsConstructorFence());
1636 }
1637 CHECK(instruction->GetBlock() != nullptr);
1638 }
1639
1640 return remove_count;
1641 }
1642
Merge(HConstructorFence * other)1643 void HConstructorFence::Merge(HConstructorFence* other) {
1644 // Do not delete yourself from the graph.
1645 DCHECK(this != other);
1646 // Don't try to merge with an instruction not associated with a block.
1647 DCHECK(other->GetBlock() != nullptr);
1648 // A constructor fence's return type is "kPrimVoid"
1649 // and therefore it cannot have any environment uses.
1650 DCHECK(!other->HasEnvironmentUses());
1651
1652 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1653 // Check if `haystack` has `needle` as any of its inputs.
1654 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1655 if (haystack->InputAt(input_count) == needle) {
1656 return true;
1657 }
1658 }
1659 return false;
1660 };
1661
1662 // Add any inputs from `other` into `this` if it wasn't already an input.
1663 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1664 HInstruction* other_input = other->InputAt(input_count);
1665 if (!has_input(this, other_input)) {
1666 AddInput(other_input);
1667 }
1668 }
1669
1670 other->GetBlock()->RemoveInstruction(other);
1671 }
1672
GetAssociatedAllocation(bool ignore_inputs)1673 HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
1674 HInstruction* new_instance_inst = GetPrevious();
1675 // Check if the immediately preceding instruction is a new-instance/new-array.
1676 // Otherwise this fence is for protecting final fields.
1677 if (new_instance_inst != nullptr &&
1678 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1679 if (ignore_inputs) {
1680 // If inputs are ignored, simply check if the predecessor is
1681 // *any* HNewInstance/HNewArray.
1682 //
1683 // Inputs are normally only ignored for prepare_for_register_allocation,
1684 // at which point *any* prior HNewInstance/Array can be considered
1685 // associated.
1686 return new_instance_inst;
1687 } else {
1688 // Normal case: There must be exactly 1 input and the previous instruction
1689 // must be that input.
1690 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1691 return new_instance_inst;
1692 }
1693 }
1694 }
1695 return nullptr;
1696 }
1697
1698 #define DEFINE_ACCEPT(name, super) \
1699 void H##name::Accept(HGraphVisitor* visitor) { \
1700 visitor->Visit##name(this); \
1701 }
1702
FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)1703 FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
1704
1705 #undef DEFINE_ACCEPT
1706
1707 void HGraphVisitor::VisitInsertionOrder() {
1708 for (HBasicBlock* block : graph_->GetActiveBlocks()) {
1709 VisitBasicBlock(block);
1710 }
1711 }
1712
VisitReversePostOrder()1713 void HGraphVisitor::VisitReversePostOrder() {
1714 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1715 VisitBasicBlock(block);
1716 }
1717 }
1718
VisitBasicBlock(HBasicBlock * block)1719 void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
1720 VisitPhis(block);
1721 VisitNonPhiInstructions(block);
1722 }
1723
VisitPhis(HBasicBlock * block)1724 void HGraphVisitor::VisitPhis(HBasicBlock* block) {
1725 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1726 DCHECK(it.Current()->IsPhi());
1727 VisitPhi(it.Current()->AsPhi());
1728 }
1729 }
1730
VisitNonPhiInstructions(HBasicBlock * block)1731 void HGraphVisitor::VisitNonPhiInstructions(HBasicBlock* block) {
1732 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1733 DCHECK(!it.Current()->IsPhi());
1734 it.Current()->Accept(this);
1735 }
1736 }
1737
TryStaticEvaluation() const1738 HConstant* HTypeConversion::TryStaticEvaluation() const { return TryStaticEvaluation(GetInput()); }
1739
TryStaticEvaluation(HInstruction * input) const1740 HConstant* HTypeConversion::TryStaticEvaluation(HInstruction* input) const {
1741 HGraph* graph = input->GetBlock()->GetGraph();
1742 if (input->IsIntConstant()) {
1743 int32_t value = input->AsIntConstant()->GetValue();
1744 switch (GetResultType()) {
1745 case DataType::Type::kInt8:
1746 return graph->GetIntConstant(static_cast<int8_t>(value));
1747 case DataType::Type::kUint8:
1748 return graph->GetIntConstant(static_cast<uint8_t>(value));
1749 case DataType::Type::kInt16:
1750 return graph->GetIntConstant(static_cast<int16_t>(value));
1751 case DataType::Type::kUint16:
1752 return graph->GetIntConstant(static_cast<uint16_t>(value));
1753 case DataType::Type::kInt64:
1754 return graph->GetLongConstant(static_cast<int64_t>(value));
1755 case DataType::Type::kFloat32:
1756 return graph->GetFloatConstant(static_cast<float>(value));
1757 case DataType::Type::kFloat64:
1758 return graph->GetDoubleConstant(static_cast<double>(value));
1759 default:
1760 return nullptr;
1761 }
1762 } else if (input->IsLongConstant()) {
1763 int64_t value = input->AsLongConstant()->GetValue();
1764 switch (GetResultType()) {
1765 case DataType::Type::kInt8:
1766 return graph->GetIntConstant(static_cast<int8_t>(value));
1767 case DataType::Type::kUint8:
1768 return graph->GetIntConstant(static_cast<uint8_t>(value));
1769 case DataType::Type::kInt16:
1770 return graph->GetIntConstant(static_cast<int16_t>(value));
1771 case DataType::Type::kUint16:
1772 return graph->GetIntConstant(static_cast<uint16_t>(value));
1773 case DataType::Type::kInt32:
1774 return graph->GetIntConstant(static_cast<int32_t>(value));
1775 case DataType::Type::kFloat32:
1776 return graph->GetFloatConstant(static_cast<float>(value));
1777 case DataType::Type::kFloat64:
1778 return graph->GetDoubleConstant(static_cast<double>(value));
1779 default:
1780 return nullptr;
1781 }
1782 } else if (input->IsFloatConstant()) {
1783 float value = input->AsFloatConstant()->GetValue();
1784 switch (GetResultType()) {
1785 case DataType::Type::kInt32:
1786 if (std::isnan(value))
1787 return graph->GetIntConstant(0);
1788 if (value >= static_cast<float>(kPrimIntMax))
1789 return graph->GetIntConstant(kPrimIntMax);
1790 if (value <= kPrimIntMin)
1791 return graph->GetIntConstant(kPrimIntMin);
1792 return graph->GetIntConstant(static_cast<int32_t>(value));
1793 case DataType::Type::kInt64:
1794 if (std::isnan(value))
1795 return graph->GetLongConstant(0);
1796 if (value >= static_cast<float>(kPrimLongMax))
1797 return graph->GetLongConstant(kPrimLongMax);
1798 if (value <= kPrimLongMin)
1799 return graph->GetLongConstant(kPrimLongMin);
1800 return graph->GetLongConstant(static_cast<int64_t>(value));
1801 case DataType::Type::kFloat64:
1802 return graph->GetDoubleConstant(static_cast<double>(value));
1803 default:
1804 return nullptr;
1805 }
1806 } else if (input->IsDoubleConstant()) {
1807 double value = input->AsDoubleConstant()->GetValue();
1808 switch (GetResultType()) {
1809 case DataType::Type::kInt32:
1810 if (std::isnan(value))
1811 return graph->GetIntConstant(0);
1812 if (value >= kPrimIntMax)
1813 return graph->GetIntConstant(kPrimIntMax);
1814 if (value <= kPrimLongMin)
1815 return graph->GetIntConstant(kPrimIntMin);
1816 return graph->GetIntConstant(static_cast<int32_t>(value));
1817 case DataType::Type::kInt64:
1818 if (std::isnan(value))
1819 return graph->GetLongConstant(0);
1820 if (value >= static_cast<double>(kPrimLongMax))
1821 return graph->GetLongConstant(kPrimLongMax);
1822 if (value <= kPrimLongMin)
1823 return graph->GetLongConstant(kPrimLongMin);
1824 return graph->GetLongConstant(static_cast<int64_t>(value));
1825 case DataType::Type::kFloat32:
1826 return graph->GetFloatConstant(static_cast<float>(value));
1827 default:
1828 return nullptr;
1829 }
1830 }
1831 return nullptr;
1832 }
1833
TryStaticEvaluation() const1834 HConstant* HUnaryOperation::TryStaticEvaluation() const { return TryStaticEvaluation(GetInput()); }
1835
TryStaticEvaluation(HInstruction * input) const1836 HConstant* HUnaryOperation::TryStaticEvaluation(HInstruction* input) const {
1837 if (input->IsIntConstant()) {
1838 return Evaluate(input->AsIntConstant());
1839 } else if (input->IsLongConstant()) {
1840 return Evaluate(input->AsLongConstant());
1841 } else if (kEnableFloatingPointStaticEvaluation) {
1842 if (input->IsFloatConstant()) {
1843 return Evaluate(input->AsFloatConstant());
1844 } else if (input->IsDoubleConstant()) {
1845 return Evaluate(input->AsDoubleConstant());
1846 }
1847 }
1848 return nullptr;
1849 }
1850
TryStaticEvaluation() const1851 HConstant* HBinaryOperation::TryStaticEvaluation() const {
1852 return TryStaticEvaluation(GetLeft(), GetRight());
1853 }
1854
TryStaticEvaluation(HInstruction * left,HInstruction * right) const1855 HConstant* HBinaryOperation::TryStaticEvaluation(HInstruction* left, HInstruction* right) const {
1856 if (left->IsIntConstant() && right->IsIntConstant()) {
1857 return Evaluate(left->AsIntConstant(), right->AsIntConstant());
1858 } else if (left->IsLongConstant()) {
1859 if (right->IsIntConstant()) {
1860 // The binop(long, int) case is only valid for shifts and rotations.
1861 DCHECK(IsShl() || IsShr() || IsUShr() || IsRol() || IsRor()) << DebugName();
1862 return Evaluate(left->AsLongConstant(), right->AsIntConstant());
1863 } else if (right->IsLongConstant()) {
1864 return Evaluate(left->AsLongConstant(), right->AsLongConstant());
1865 }
1866 } else if (left->IsNullConstant() && right->IsNullConstant()) {
1867 // The binop(null, null) case is only valid for equal and not-equal conditions.
1868 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
1869 return Evaluate(left->AsNullConstant(), right->AsNullConstant());
1870 } else if (kEnableFloatingPointStaticEvaluation) {
1871 if (left->IsFloatConstant() && right->IsFloatConstant()) {
1872 return Evaluate(left->AsFloatConstant(), right->AsFloatConstant());
1873 } else if (left->IsDoubleConstant() && right->IsDoubleConstant()) {
1874 return Evaluate(left->AsDoubleConstant(), right->AsDoubleConstant());
1875 }
1876 }
1877 return nullptr;
1878 }
1879
GetConstantRight() const1880 HConstant* HBinaryOperation::GetConstantRight() const {
1881 if (GetRight()->IsConstant()) {
1882 return GetRight()->AsConstant();
1883 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1884 return GetLeft()->AsConstant();
1885 } else {
1886 return nullptr;
1887 }
1888 }
1889
1890 // If `GetConstantRight()` returns one of the input, this returns the other
1891 // one. Otherwise it returns null.
GetLeastConstantLeft() const1892 HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1893 HInstruction* most_constant_right = GetConstantRight();
1894 if (most_constant_right == nullptr) {
1895 return nullptr;
1896 } else if (most_constant_right == GetLeft()) {
1897 return GetRight();
1898 } else {
1899 return GetLeft();
1900 }
1901 }
1902
operator <<(std::ostream & os,ComparisonBias rhs)1903 std::ostream& operator<<(std::ostream& os, ComparisonBias rhs) {
1904 // TODO: Replace with auto-generated operator<<.
1905 switch (rhs) {
1906 case ComparisonBias::kNoBias:
1907 return os << "none";
1908 case ComparisonBias::kGtBias:
1909 return os << "gt";
1910 case ComparisonBias::kLtBias:
1911 return os << "lt";
1912 }
1913 }
1914
Create(HGraph * graph,IfCondition cond,HInstruction * lhs,HInstruction * rhs,uint32_t dex_pc)1915 HCondition* HCondition::Create(HGraph* graph,
1916 IfCondition cond,
1917 HInstruction* lhs,
1918 HInstruction* rhs,
1919 uint32_t dex_pc) {
1920 ArenaAllocator* allocator = graph->GetAllocator();
1921 switch (cond) {
1922 case kCondEQ: return new (allocator) HEqual(lhs, rhs, dex_pc);
1923 case kCondNE: return new (allocator) HNotEqual(lhs, rhs, dex_pc);
1924 case kCondLT: return new (allocator) HLessThan(lhs, rhs, dex_pc);
1925 case kCondLE: return new (allocator) HLessThanOrEqual(lhs, rhs, dex_pc);
1926 case kCondGT: return new (allocator) HGreaterThan(lhs, rhs, dex_pc);
1927 case kCondGE: return new (allocator) HGreaterThanOrEqual(lhs, rhs, dex_pc);
1928 case kCondB: return new (allocator) HBelow(lhs, rhs, dex_pc);
1929 case kCondBE: return new (allocator) HBelowOrEqual(lhs, rhs, dex_pc);
1930 case kCondA: return new (allocator) HAbove(lhs, rhs, dex_pc);
1931 case kCondAE: return new (allocator) HAboveOrEqual(lhs, rhs, dex_pc);
1932 default:
1933 LOG(FATAL) << "Unexpected condition " << cond;
1934 UNREACHABLE();
1935 }
1936 }
1937
IsBeforeWhenDisregardMoves(HInstruction * instruction) const1938 bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1939 return this == instruction->GetPreviousDisregardingMoves();
1940 }
1941
Equals(const HInstruction * other) const1942 bool HInstruction::Equals(const HInstruction* other) const {
1943 if (GetKind() != other->GetKind()) return false;
1944 if (GetType() != other->GetType()) return false;
1945 if (!InstructionDataEquals(other)) return false;
1946 HConstInputsRef inputs = GetInputs();
1947 HConstInputsRef other_inputs = other->GetInputs();
1948 if (inputs.size() != other_inputs.size()) return false;
1949 for (size_t i = 0; i != inputs.size(); ++i) {
1950 if (inputs[i] != other_inputs[i]) return false;
1951 }
1952
1953 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
1954 return true;
1955 }
1956
operator <<(std::ostream & os,HInstruction::InstructionKind rhs)1957 std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs) {
1958 #define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1959 switch (rhs) {
1960 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
1961 default:
1962 os << "Unknown instruction kind " << static_cast<int>(rhs);
1963 break;
1964 }
1965 #undef DECLARE_CASE
1966 return os;
1967 }
1968
operator <<(std::ostream & os,const HInstruction::NoArgsDump rhs)1969 std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs) {
1970 // TODO Really this should be const but that would require const-ifying
1971 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
1972 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ false);
1973 }
1974
operator <<(std::ostream & os,const HInstruction::ArgsDump rhs)1975 std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs) {
1976 // TODO Really this should be const but that would require const-ifying
1977 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
1978 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ true);
1979 }
1980
operator <<(std::ostream & os,const HInstruction & rhs)1981 std::ostream& operator<<(std::ostream& os, const HInstruction& rhs) {
1982 return os << rhs.DumpWithoutArgs();
1983 }
1984
operator <<(std::ostream & os,const HUseList<HInstruction * > & lst)1985 std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst) {
1986 os << "Instructions[";
1987 bool first = true;
1988 for (const auto& hi : lst) {
1989 if (!first) {
1990 os << ", ";
1991 }
1992 first = false;
1993 os << hi.GetUser()->DebugName() << "[id: " << hi.GetUser()->GetId()
1994 << ", blk: " << hi.GetUser()->GetBlock()->GetBlockId() << "]@" << hi.GetIndex();
1995 }
1996 os << "]";
1997 return os;
1998 }
1999
operator <<(std::ostream & os,const HUseList<HEnvironment * > & lst)2000 std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst) {
2001 os << "Environments[";
2002 bool first = true;
2003 for (const auto& hi : lst) {
2004 if (!first) {
2005 os << ", ";
2006 }
2007 first = false;
2008 os << *hi.GetUser()->GetHolder() << "@" << hi.GetIndex();
2009 }
2010 os << "]";
2011 return os;
2012 }
2013
Dump(std::ostream & os,CodeGenerator * codegen,std::optional<std::reference_wrapper<const BlockNamer>> namer)2014 std::ostream& HGraph::Dump(std::ostream& os,
2015 CodeGenerator* codegen,
2016 std::optional<std::reference_wrapper<const BlockNamer>> namer) {
2017 HGraphVisualizer vis(&os, this, codegen, namer);
2018 vis.DumpGraphDebug();
2019 return os;
2020 }
2021
MoveBefore(HInstruction * cursor,bool do_checks)2022 void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
2023 if (do_checks) {
2024 DCHECK(!IsPhi());
2025 DCHECK(!IsControlFlow());
2026 DCHECK(CanBeMoved() ||
2027 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
2028 IsShouldDeoptimizeFlag());
2029 DCHECK(!cursor->IsPhi());
2030 }
2031
2032 next_->previous_ = previous_;
2033 if (previous_ != nullptr) {
2034 previous_->next_ = next_;
2035 }
2036 if (block_->instructions_.first_instruction_ == this) {
2037 block_->instructions_.first_instruction_ = next_;
2038 }
2039 DCHECK_NE(block_->instructions_.last_instruction_, this);
2040
2041 previous_ = cursor->previous_;
2042 if (previous_ != nullptr) {
2043 previous_->next_ = this;
2044 }
2045 next_ = cursor;
2046 cursor->previous_ = this;
2047 block_ = cursor->block_;
2048
2049 if (block_->instructions_.first_instruction_ == cursor) {
2050 block_->instructions_.first_instruction_ = this;
2051 }
2052 }
2053
MoveBeforeFirstUserAndOutOfLoops()2054 void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
2055 DCHECK(!CanThrow());
2056 DCHECK(!HasSideEffects());
2057 DCHECK(!HasEnvironmentUses());
2058 DCHECK(HasNonEnvironmentUses());
2059 DCHECK(!IsPhi()); // Makes no sense for Phi.
2060 DCHECK_EQ(InputCount(), 0u);
2061
2062 // Find the target block.
2063 auto uses_it = GetUses().begin();
2064 auto uses_end = GetUses().end();
2065 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
2066 ++uses_it;
2067 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
2068 ++uses_it;
2069 }
2070 if (uses_it != uses_end) {
2071 // This instruction has uses in two or more blocks. Find the common dominator.
2072 CommonDominator finder(target_block);
2073 for (; uses_it != uses_end; ++uses_it) {
2074 finder.Update(uses_it->GetUser()->GetBlock());
2075 }
2076 target_block = finder.Get();
2077 DCHECK(target_block != nullptr);
2078 }
2079 // Move to the first dominator not in a loop.
2080 while (target_block->IsInLoop()) {
2081 target_block = target_block->GetDominator();
2082 DCHECK(target_block != nullptr);
2083 }
2084
2085 // Find insertion position.
2086 HInstruction* insert_pos = nullptr;
2087 for (const HUseListNode<HInstruction*>& use : GetUses()) {
2088 if (use.GetUser()->GetBlock() == target_block &&
2089 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
2090 insert_pos = use.GetUser();
2091 }
2092 }
2093 if (insert_pos == nullptr) {
2094 // No user in `target_block`, insert before the control flow instruction.
2095 insert_pos = target_block->GetLastInstruction();
2096 DCHECK(insert_pos->IsControlFlow());
2097 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
2098 if (insert_pos->IsIf()) {
2099 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
2100 if (if_input == insert_pos->GetPrevious()) {
2101 insert_pos = if_input;
2102 }
2103 }
2104 }
2105 MoveBefore(insert_pos);
2106 }
2107
SplitBefore(HInstruction * cursor,bool require_graph_not_in_ssa_form)2108 HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor, bool require_graph_not_in_ssa_form) {
2109 DCHECK_IMPLIES(require_graph_not_in_ssa_form, !graph_->IsInSsaForm())
2110 << "Support for SSA form not implemented.";
2111 DCHECK_EQ(cursor->GetBlock(), this);
2112
2113 HBasicBlock* new_block =
2114 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
2115 new_block->instructions_.first_instruction_ = cursor;
2116 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2117 instructions_.last_instruction_ = cursor->previous_;
2118 if (cursor->previous_ == nullptr) {
2119 instructions_.first_instruction_ = nullptr;
2120 } else {
2121 cursor->previous_->next_ = nullptr;
2122 cursor->previous_ = nullptr;
2123 }
2124
2125 new_block->instructions_.SetBlockOfInstructions(new_block);
2126 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
2127
2128 for (HBasicBlock* successor : GetSuccessors()) {
2129 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2130 }
2131 new_block->successors_.swap(successors_);
2132 DCHECK(successors_.empty());
2133 AddSuccessor(new_block);
2134
2135 GetGraph()->AddBlock(new_block);
2136 return new_block;
2137 }
2138
CreateImmediateDominator()2139 HBasicBlock* HBasicBlock::CreateImmediateDominator() {
2140 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
2141 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
2142
2143 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
2144
2145 for (HBasicBlock* predecessor : GetPredecessors()) {
2146 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
2147 }
2148 new_block->predecessors_.swap(predecessors_);
2149 DCHECK(predecessors_.empty());
2150 AddPredecessor(new_block);
2151
2152 GetGraph()->AddBlock(new_block);
2153 return new_block;
2154 }
2155
SplitBeforeForInlining(HInstruction * cursor)2156 HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
2157 DCHECK_EQ(cursor->GetBlock(), this);
2158
2159 HBasicBlock* new_block =
2160 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
2161 new_block->instructions_.first_instruction_ = cursor;
2162 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2163 instructions_.last_instruction_ = cursor->previous_;
2164 if (cursor->previous_ == nullptr) {
2165 instructions_.first_instruction_ = nullptr;
2166 } else {
2167 cursor->previous_->next_ = nullptr;
2168 cursor->previous_ = nullptr;
2169 }
2170
2171 new_block->instructions_.SetBlockOfInstructions(new_block);
2172
2173 for (HBasicBlock* successor : GetSuccessors()) {
2174 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2175 }
2176 new_block->successors_.swap(successors_);
2177 DCHECK(successors_.empty());
2178
2179 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2180 dominated->dominator_ = new_block;
2181 }
2182 new_block->dominated_blocks_.swap(dominated_blocks_);
2183 DCHECK(dominated_blocks_.empty());
2184 return new_block;
2185 }
2186
SplitAfterForInlining(HInstruction * cursor)2187 HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
2188 DCHECK(!cursor->IsControlFlow());
2189 DCHECK_NE(instructions_.last_instruction_, cursor);
2190 DCHECK_EQ(cursor->GetBlock(), this);
2191
2192 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
2193 new_block->instructions_.first_instruction_ = cursor->GetNext();
2194 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2195 cursor->next_->previous_ = nullptr;
2196 cursor->next_ = nullptr;
2197 instructions_.last_instruction_ = cursor;
2198
2199 new_block->instructions_.SetBlockOfInstructions(new_block);
2200 for (HBasicBlock* successor : GetSuccessors()) {
2201 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2202 }
2203 new_block->successors_.swap(successors_);
2204 DCHECK(successors_.empty());
2205
2206 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2207 dominated->dominator_ = new_block;
2208 }
2209 new_block->dominated_blocks_.swap(dominated_blocks_);
2210 DCHECK(dominated_blocks_.empty());
2211 return new_block;
2212 }
2213
ComputeTryEntryOfSuccessors() const2214 const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
2215 if (EndsWithTryBoundary()) {
2216 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
2217 if (try_boundary->IsEntry()) {
2218 DCHECK(!IsTryBlock());
2219 return try_boundary;
2220 } else {
2221 DCHECK(IsTryBlock());
2222 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
2223 return nullptr;
2224 }
2225 } else if (IsTryBlock()) {
2226 return &try_catch_information_->GetTryEntry();
2227 } else {
2228 return nullptr;
2229 }
2230 }
2231
HasThrowingInstructions() const2232 bool HBasicBlock::HasThrowingInstructions() const {
2233 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2234 if (it.Current()->CanThrow()) {
2235 return true;
2236 }
2237 }
2238 return false;
2239 }
2240
HasOnlyOneInstruction(const HBasicBlock & block)2241 static bool HasOnlyOneInstruction(const HBasicBlock& block) {
2242 return block.GetPhis().IsEmpty()
2243 && !block.GetInstructions().IsEmpty()
2244 && block.GetFirstInstruction() == block.GetLastInstruction();
2245 }
2246
IsSingleGoto() const2247 bool HBasicBlock::IsSingleGoto() const {
2248 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
2249 }
2250
IsSingleReturn() const2251 bool HBasicBlock::IsSingleReturn() const {
2252 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
2253 }
2254
IsSingleReturnOrReturnVoidAllowingPhis() const2255 bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
2256 return (GetFirstInstruction() == GetLastInstruction()) &&
2257 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2258 }
2259
IsSingleTryBoundary() const2260 bool HBasicBlock::IsSingleTryBoundary() const {
2261 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
2262 }
2263
EndsWithControlFlowInstruction() const2264 bool HBasicBlock::EndsWithControlFlowInstruction() const {
2265 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
2266 }
2267
EndsWithReturn() const2268 bool HBasicBlock::EndsWithReturn() const {
2269 return !GetInstructions().IsEmpty() &&
2270 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2271 }
2272
EndsWithIf() const2273 bool HBasicBlock::EndsWithIf() const {
2274 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2275 }
2276
EndsWithTryBoundary() const2277 bool HBasicBlock::EndsWithTryBoundary() const {
2278 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2279 }
2280
HasSinglePhi() const2281 bool HBasicBlock::HasSinglePhi() const {
2282 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2283 }
2284
GetNormalSuccessors() const2285 ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2286 if (EndsWithTryBoundary()) {
2287 // The normal-flow successor of HTryBoundary is always stored at index zero.
2288 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2289 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2290 } else {
2291 // All successors of blocks not ending with TryBoundary are normal.
2292 return ArrayRef<HBasicBlock* const>(successors_);
2293 }
2294 }
2295
GetExceptionalSuccessors() const2296 ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2297 if (EndsWithTryBoundary()) {
2298 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2299 } else {
2300 // Blocks not ending with TryBoundary do not have exceptional successors.
2301 return ArrayRef<HBasicBlock* const>();
2302 }
2303 }
2304
HasSameExceptionHandlersAs(const HTryBoundary & other) const2305 bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
2306 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2307 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2308
2309 size_t length = handlers1.size();
2310 if (length != handlers2.size()) {
2311 return false;
2312 }
2313
2314 // Exception handlers need to be stored in the same order.
2315 for (size_t i = 0; i < length; ++i) {
2316 if (handlers1[i] != handlers2[i]) {
2317 return false;
2318 }
2319 }
2320 return true;
2321 }
2322
CountSize() const2323 size_t HInstructionList::CountSize() const {
2324 size_t size = 0;
2325 HInstruction* current = first_instruction_;
2326 for (; current != nullptr; current = current->GetNext()) {
2327 size++;
2328 }
2329 return size;
2330 }
2331
SetBlockOfInstructions(HBasicBlock * block) const2332 void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2333 for (HInstruction* current = first_instruction_;
2334 current != nullptr;
2335 current = current->GetNext()) {
2336 current->SetBlock(block);
2337 }
2338 }
2339
AddAfter(HInstruction * cursor,const HInstructionList & instruction_list)2340 void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2341 DCHECK(Contains(cursor));
2342 if (!instruction_list.IsEmpty()) {
2343 if (cursor == last_instruction_) {
2344 last_instruction_ = instruction_list.last_instruction_;
2345 } else {
2346 cursor->next_->previous_ = instruction_list.last_instruction_;
2347 }
2348 instruction_list.last_instruction_->next_ = cursor->next_;
2349 cursor->next_ = instruction_list.first_instruction_;
2350 instruction_list.first_instruction_->previous_ = cursor;
2351 }
2352 }
2353
AddBefore(HInstruction * cursor,const HInstructionList & instruction_list)2354 void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2355 DCHECK(Contains(cursor));
2356 if (!instruction_list.IsEmpty()) {
2357 if (cursor == first_instruction_) {
2358 first_instruction_ = instruction_list.first_instruction_;
2359 } else {
2360 cursor->previous_->next_ = instruction_list.first_instruction_;
2361 }
2362 instruction_list.last_instruction_->next_ = cursor;
2363 instruction_list.first_instruction_->previous_ = cursor->previous_;
2364 cursor->previous_ = instruction_list.last_instruction_;
2365 }
2366 }
2367
Add(const HInstructionList & instruction_list)2368 void HInstructionList::Add(const HInstructionList& instruction_list) {
2369 if (IsEmpty()) {
2370 first_instruction_ = instruction_list.first_instruction_;
2371 last_instruction_ = instruction_list.last_instruction_;
2372 } else {
2373 AddAfter(last_instruction_, instruction_list);
2374 }
2375 }
2376
DisconnectAndDelete()2377 void HBasicBlock::DisconnectAndDelete() {
2378 // Dominators must be removed after all the blocks they dominate. This way
2379 // a loop header is removed last, a requirement for correct loop information
2380 // iteration.
2381 DCHECK(dominated_blocks_.empty());
2382
2383 // The following steps gradually remove the block from all its dependants in
2384 // post order (b/27683071).
2385
2386 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2387 // We need to do this before step (4) which destroys the predecessor list.
2388 HBasicBlock* loop_update_start = this;
2389 if (IsLoopHeader()) {
2390 HLoopInformation* loop_info = GetLoopInformation();
2391 // All other blocks in this loop should have been removed because the header
2392 // was their dominator.
2393 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2394 DCHECK(!loop_info->IsIrreducible());
2395 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2396 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2397 loop_update_start = loop_info->GetPreHeader();
2398 }
2399
2400 // (2) Disconnect the block from its successors and update their phis.
2401 DisconnectFromSuccessors();
2402
2403 // (3) Remove instructions and phis. Instructions should have no remaining uses
2404 // except in catch phis. If an instruction is used by a catch phi at `index`,
2405 // remove `index`-th input of all phis in the catch block since they are
2406 // guaranteed dead. Note that we may miss dead inputs this way but the
2407 // graph will always remain consistent.
2408 RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ false);
2409
2410 // (4) Disconnect the block from its predecessors and update their
2411 // control-flow instructions.
2412 for (HBasicBlock* predecessor : predecessors_) {
2413 // We should not see any back edges as they would have been removed by step (3).
2414 DCHECK_IMPLIES(IsInLoop(), !GetLoopInformation()->IsBackEdge(*predecessor));
2415
2416 HInstruction* last_instruction = predecessor->GetLastInstruction();
2417 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2418 // This block is the only normal-flow successor of the TryBoundary which
2419 // makes `predecessor` dead. Since DCE removes blocks in post order,
2420 // exception handlers of this TryBoundary were already visited and any
2421 // remaining handlers therefore must be live. We remove `predecessor` from
2422 // their list of predecessors.
2423 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2424 while (predecessor->GetSuccessors().size() > 1) {
2425 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2426 DCHECK(handler->IsCatchBlock());
2427 predecessor->RemoveSuccessor(handler);
2428 handler->RemovePredecessor(predecessor);
2429 }
2430 }
2431
2432 predecessor->RemoveSuccessor(this);
2433 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2434 if (num_pred_successors == 1u) {
2435 // If we have one successor after removing one, then we must have
2436 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2437 // successor. Replace those with a HGoto.
2438 DCHECK(last_instruction->IsIf() ||
2439 last_instruction->IsPackedSwitch() ||
2440 (last_instruction->IsTryBoundary() && IsCatchBlock()));
2441 predecessor->RemoveInstruction(last_instruction);
2442 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
2443 } else if (num_pred_successors == 0u) {
2444 // The predecessor has no remaining successors and therefore must be dead.
2445 // We deliberately leave it without a control-flow instruction so that the
2446 // GraphChecker fails unless it is not removed during the pass too.
2447 predecessor->RemoveInstruction(last_instruction);
2448 } else {
2449 // There are multiple successors left. The removed block might be a successor
2450 // of a PackedSwitch which will be completely removed (perhaps replaced with
2451 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2452 // case, leave `last_instruction` as is for now.
2453 DCHECK(last_instruction->IsPackedSwitch() ||
2454 (last_instruction->IsTryBoundary() && IsCatchBlock()));
2455 }
2456 }
2457 predecessors_.clear();
2458
2459 // (5) Remove the block from all loops it is included in. Skip the inner-most
2460 // loop if this is the loop header (see definition of `loop_update_start`)
2461 // because the loop header's predecessor list has been destroyed in step (4).
2462 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2463 HLoopInformation* loop_info = it.Current();
2464 loop_info->Remove(this);
2465 if (loop_info->IsBackEdge(*this)) {
2466 // If this was the last back edge of the loop, we deliberately leave the
2467 // loop in an inconsistent state and will fail GraphChecker unless the
2468 // entire loop is removed during the pass.
2469 loop_info->RemoveBackEdge(this);
2470 }
2471 }
2472
2473 // (6) Disconnect from the dominator.
2474 dominator_->RemoveDominatedBlock(this);
2475 SetDominator(nullptr);
2476
2477 // (7) Delete from the graph, update reverse post order.
2478 graph_->DeleteDeadEmptyBlock(this);
2479 }
2480
DisconnectFromSuccessors(const ArenaBitVector * visited)2481 void HBasicBlock::DisconnectFromSuccessors(const ArenaBitVector* visited) {
2482 for (HBasicBlock* successor : successors_) {
2483 // Delete this block from the list of predecessors.
2484 size_t this_index = successor->GetPredecessorIndexOf(this);
2485 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2486
2487 if (visited != nullptr && !visited->IsBitSet(successor->GetBlockId())) {
2488 // `successor` itself is dead. Therefore, there is no need to update its phis.
2489 continue;
2490 }
2491
2492 DCHECK(!successor->predecessors_.empty());
2493
2494 // Remove this block's entries in the successor's phis. Skips exceptional
2495 // successors because catch phi inputs do not correspond to predecessor
2496 // blocks but throwing instructions. They are removed in `RemoveCatchPhiUses`.
2497 if (!successor->IsCatchBlock()) {
2498 if (successor->predecessors_.size() == 1u) {
2499 // The successor has just one predecessor left. Replace phis with the only
2500 // remaining input.
2501 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2502 HPhi* phi = phi_it.Current()->AsPhi();
2503 phi->ReplaceWith(phi->InputAt(1 - this_index));
2504 successor->RemovePhi(phi);
2505 }
2506 } else {
2507 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2508 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2509 }
2510 }
2511 }
2512 }
2513 successors_.clear();
2514 }
2515
RemoveCatchPhiUsesAndInstruction(bool building_dominator_tree)2516 void HBasicBlock::RemoveCatchPhiUsesAndInstruction(bool building_dominator_tree) {
2517 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2518 HInstruction* insn = it.Current();
2519 RemoveCatchPhiUsesOfDeadInstruction(insn);
2520
2521 // If we are building the dominator tree, we removed all input records previously.
2522 // `RemoveInstruction` will try to remove them again but that's not something we support and we
2523 // will crash. We check here since we won't be checking that in RemoveInstruction.
2524 if (building_dominator_tree) {
2525 DCHECK(insn->GetUses().empty());
2526 DCHECK(insn->GetEnvUses().empty());
2527 }
2528 RemoveInstruction(insn, /* ensure_safety= */ !building_dominator_tree);
2529 }
2530 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2531 HPhi* insn = it.Current()->AsPhi();
2532 RemoveCatchPhiUsesOfDeadInstruction(insn);
2533
2534 // If we are building the dominator tree, we removed all input records previously.
2535 // `RemovePhi` will try to remove them again but that's not something we support and we
2536 // will crash. We check here since we won't be checking that in RemovePhi.
2537 if (building_dominator_tree) {
2538 DCHECK(insn->GetUses().empty());
2539 DCHECK(insn->GetEnvUses().empty());
2540 }
2541 RemovePhi(insn, /* ensure_safety= */ !building_dominator_tree);
2542 }
2543 }
2544
MergeInstructionsWith(HBasicBlock * other)2545 void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2546 DCHECK(EndsWithControlFlowInstruction());
2547 RemoveInstruction(GetLastInstruction());
2548 instructions_.Add(other->GetInstructions());
2549 other->instructions_.SetBlockOfInstructions(this);
2550 other->instructions_.Clear();
2551 }
2552
MergeWith(HBasicBlock * other)2553 void HBasicBlock::MergeWith(HBasicBlock* other) {
2554 DCHECK_EQ(GetGraph(), other->GetGraph());
2555 DCHECK(ContainsElement(dominated_blocks_, other));
2556 DCHECK_EQ(GetSingleSuccessor(), other);
2557 DCHECK_EQ(other->GetSinglePredecessor(), this);
2558 DCHECK(other->GetPhis().IsEmpty());
2559
2560 // Move instructions from `other` to `this`.
2561 MergeInstructionsWith(other);
2562
2563 // Remove `other` from the loops it is included in.
2564 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2565 HLoopInformation* loop_info = it.Current();
2566 loop_info->Remove(other);
2567 if (loop_info->IsBackEdge(*other)) {
2568 loop_info->ReplaceBackEdge(other, this);
2569 }
2570 }
2571
2572 // Update links to the successors of `other`.
2573 successors_.clear();
2574 for (HBasicBlock* successor : other->GetSuccessors()) {
2575 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
2576 }
2577 successors_.swap(other->successors_);
2578 DCHECK(other->successors_.empty());
2579
2580 // Update the dominator tree.
2581 RemoveDominatedBlock(other);
2582 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
2583 dominated->SetDominator(this);
2584 }
2585 dominated_blocks_.insert(
2586 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
2587 other->dominated_blocks_.clear();
2588 other->dominator_ = nullptr;
2589
2590 // Clear the list of predecessors of `other` in preparation of deleting it.
2591 other->predecessors_.clear();
2592
2593 // Delete `other` from the graph. The function updates reverse post order.
2594 graph_->DeleteDeadEmptyBlock(other);
2595 }
2596
MergeWithInlined(HBasicBlock * other)2597 void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2598 DCHECK_NE(GetGraph(), other->GetGraph());
2599 DCHECK(GetDominatedBlocks().empty());
2600 DCHECK(GetSuccessors().empty());
2601 DCHECK(!EndsWithControlFlowInstruction());
2602 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
2603 DCHECK(other->GetPhis().IsEmpty());
2604 DCHECK(!other->IsInLoop());
2605
2606 // Move instructions from `other` to `this`.
2607 instructions_.Add(other->GetInstructions());
2608 other->instructions_.SetBlockOfInstructions(this);
2609
2610 // Update links to the successors of `other`.
2611 successors_.clear();
2612 for (HBasicBlock* successor : other->GetSuccessors()) {
2613 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
2614 }
2615 successors_.swap(other->successors_);
2616 DCHECK(other->successors_.empty());
2617
2618 // Update the dominator tree.
2619 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
2620 dominated->SetDominator(this);
2621 }
2622 dominated_blocks_.insert(
2623 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
2624 other->dominated_blocks_.clear();
2625 other->dominator_ = nullptr;
2626 other->graph_ = nullptr;
2627 }
2628
ReplaceWith(HBasicBlock * other)2629 void HBasicBlock::ReplaceWith(HBasicBlock* other) {
2630 while (!GetPredecessors().empty()) {
2631 HBasicBlock* predecessor = GetPredecessors()[0];
2632 predecessor->ReplaceSuccessor(this, other);
2633 }
2634 while (!GetSuccessors().empty()) {
2635 HBasicBlock* successor = GetSuccessors()[0];
2636 successor->ReplacePredecessor(this, other);
2637 }
2638 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2639 other->AddDominatedBlock(dominated);
2640 }
2641 GetDominator()->ReplaceDominatedBlock(this, other);
2642 other->SetDominator(GetDominator());
2643 dominator_ = nullptr;
2644 graph_ = nullptr;
2645 }
2646
DeleteDeadEmptyBlock(HBasicBlock * block)2647 void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
2648 DCHECK_EQ(block->GetGraph(), this);
2649 DCHECK(block->GetSuccessors().empty());
2650 DCHECK(block->GetPredecessors().empty());
2651 DCHECK(block->GetDominatedBlocks().empty());
2652 DCHECK(block->GetDominator() == nullptr);
2653 DCHECK(block->GetInstructions().IsEmpty());
2654 DCHECK(block->GetPhis().IsEmpty());
2655
2656 if (block->IsExitBlock()) {
2657 SetExitBlock(nullptr);
2658 }
2659
2660 RemoveElement(reverse_post_order_, block);
2661 blocks_[block->GetBlockId()] = nullptr;
2662 block->SetGraph(nullptr);
2663 }
2664
UpdateLoopAndTryInformationOfNewBlock(HBasicBlock * block,HBasicBlock * reference,bool replace_if_back_edge,bool has_more_specific_try_catch_info)2665 void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2666 HBasicBlock* reference,
2667 bool replace_if_back_edge,
2668 bool has_more_specific_try_catch_info) {
2669 if (block->IsLoopHeader()) {
2670 // Clear the information of which blocks are contained in that loop. Since the
2671 // information is stored as a bit vector based on block ids, we have to update
2672 // it, as those block ids were specific to the callee graph and we are now adding
2673 // these blocks to the caller graph.
2674 block->GetLoopInformation()->ClearAllBlocks();
2675 }
2676
2677 // If not already in a loop, update the loop information.
2678 if (!block->IsInLoop()) {
2679 block->SetLoopInformation(reference->GetLoopInformation());
2680 }
2681
2682 // If the block is in a loop, update all its outward loops.
2683 HLoopInformation* loop_info = block->GetLoopInformation();
2684 if (loop_info != nullptr) {
2685 for (HLoopInformationOutwardIterator loop_it(*block);
2686 !loop_it.Done();
2687 loop_it.Advance()) {
2688 loop_it.Current()->Add(block);
2689 }
2690 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2691 loop_info->ReplaceBackEdge(reference, block);
2692 }
2693 }
2694
2695 DCHECK_IMPLIES(has_more_specific_try_catch_info, !reference->IsTryBlock())
2696 << "We don't allow to inline try catches inside of other try blocks.";
2697
2698 // Update the TryCatchInformation, if we are not inlining a try catch.
2699 if (!has_more_specific_try_catch_info) {
2700 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2701 TryCatchInformation* try_catch_info =
2702 reference->IsTryBlock() ? reference->GetTryCatchInformation() : nullptr;
2703 block->SetTryCatchInformation(try_catch_info);
2704 }
2705 }
2706
InlineInto(HGraph * outer_graph,HInvoke * invoke)2707 HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
2708 DCHECK(HasExitBlock()) << "Unimplemented scenario";
2709 // Update the environments in this graph to have the invoke's environment
2710 // as parent.
2711 {
2712 // Skip the entry block, we do not need to update the entry's suspend check.
2713 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
2714 for (HInstructionIterator instr_it(block->GetInstructions());
2715 !instr_it.Done();
2716 instr_it.Advance()) {
2717 HInstruction* current = instr_it.Current();
2718 if (current->NeedsEnvironment()) {
2719 DCHECK(current->HasEnvironment());
2720 current->GetEnvironment()->SetAndCopyParentChain(
2721 outer_graph->GetAllocator(), invoke->GetEnvironment());
2722 }
2723 }
2724 }
2725 }
2726
2727 if (HasBoundsChecks()) {
2728 outer_graph->SetHasBoundsChecks(true);
2729 }
2730 if (HasLoops()) {
2731 outer_graph->SetHasLoops(true);
2732 }
2733 if (HasIrreducibleLoops()) {
2734 outer_graph->SetHasIrreducibleLoops(true);
2735 }
2736 if (HasDirectCriticalNativeCall()) {
2737 outer_graph->SetHasDirectCriticalNativeCall(true);
2738 }
2739 if (HasTryCatch()) {
2740 outer_graph->SetHasTryCatch(true);
2741 }
2742 if (HasMonitorOperations()) {
2743 outer_graph->SetHasMonitorOperations(true);
2744 }
2745 if (HasTraditionalSIMD()) {
2746 outer_graph->SetHasTraditionalSIMD(true);
2747 }
2748 if (HasPredicatedSIMD()) {
2749 outer_graph->SetHasPredicatedSIMD(true);
2750 }
2751 if (HasAlwaysThrowingInvokes()) {
2752 outer_graph->SetHasAlwaysThrowingInvokes(true);
2753 }
2754
2755 HInstruction* return_value = nullptr;
2756 if (GetBlocks().size() == 3) {
2757 // Inliner already made sure we don't inline methods that always throw.
2758 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
2759 // Simple case of an entry block, a body block, and an exit block.
2760 // Put the body block's instruction into `invoke`'s block.
2761 HBasicBlock* body = GetBlocks()[1];
2762 DCHECK(GetBlocks()[0]->IsEntryBlock());
2763 DCHECK(GetBlocks()[2]->IsExitBlock());
2764 DCHECK(!body->IsExitBlock());
2765 DCHECK(!body->IsInLoop());
2766 HInstruction* last = body->GetLastInstruction();
2767
2768 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2769 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
2770 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
2771
2772 // Replace the invoke with the return value of the inlined graph.
2773 if (last->IsReturn()) {
2774 return_value = last->InputAt(0);
2775 } else {
2776 DCHECK(last->IsReturnVoid());
2777 }
2778
2779 invoke->GetBlock()->RemoveInstruction(last);
2780 } else {
2781 // Need to inline multiple blocks. We split `invoke`'s block
2782 // into two blocks, merge the first block of the inlined graph into
2783 // the first half, and replace the exit block of the inlined graph
2784 // with the second half.
2785 ArenaAllocator* allocator = outer_graph->GetAllocator();
2786 HBasicBlock* at = invoke->GetBlock();
2787 // Note that we split before the invoke only to simplify polymorphic inlining.
2788 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
2789
2790 HBasicBlock* first = entry_block_->GetSuccessors()[0];
2791 DCHECK(!first->IsInLoop());
2792 DCHECK(first->GetTryCatchInformation() == nullptr);
2793 at->MergeWithInlined(first);
2794 exit_block_->ReplaceWith(to);
2795
2796 // Update the meta information surrounding blocks:
2797 // (1) the graph they are now in,
2798 // (2) the reverse post order of that graph,
2799 // (3) their potential loop information, inner and outer,
2800 // (4) try block membership.
2801 // Note that we do not need to update catch phi inputs because they
2802 // correspond to the register file of the outer method which the inlinee
2803 // cannot modify.
2804
2805 // We don't add the entry block, the exit block, and the first block, which
2806 // has been merged with `at`.
2807 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2808
2809 // We add the `to` block.
2810 static constexpr int kNumberOfNewBlocksInCaller = 1;
2811 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
2812 + kNumberOfNewBlocksInCaller;
2813
2814 // Find the location of `at` in the outer graph's reverse post order. The new
2815 // blocks will be added after it.
2816 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
2817 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2818
2819 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2820 // and (4) to the blocks that apply.
2821 for (HBasicBlock* current : GetReversePostOrder()) {
2822 if (current != exit_block_ && current != entry_block_ && current != first) {
2823 DCHECK(current->GetGraph() == this);
2824 current->SetGraph(outer_graph);
2825 outer_graph->AddBlock(current);
2826 outer_graph->reverse_post_order_[++index_of_at] = current;
2827 UpdateLoopAndTryInformationOfNewBlock(current,
2828 at,
2829 /* replace_if_back_edge= */ false,
2830 current->GetTryCatchInformation() != nullptr);
2831 }
2832 }
2833
2834 // Do (1), (2), (3) and (4) to `to`.
2835 to->SetGraph(outer_graph);
2836 outer_graph->AddBlock(to);
2837 outer_graph->reverse_post_order_[++index_of_at] = to;
2838 // Only `to` can become a back edge, as the inlined blocks
2839 // are predecessors of `to`.
2840 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
2841
2842 // Update all predecessors of the exit block (now the `to` block)
2843 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2844 // to now get the outer graph exit block as successor.
2845 HPhi* return_value_phi = nullptr;
2846 bool rerun_dominance = false;
2847 bool rerun_loop_analysis = false;
2848 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2849 HBasicBlock* predecessor = to->GetPredecessors()[pred];
2850 HInstruction* last = predecessor->GetLastInstruction();
2851
2852 // At this point we might either have:
2853 // A) Return/ReturnVoid/Throw as the last instruction, or
2854 // B) `Return/ReturnVoid/Throw->TryBoundary` as the last instruction chain
2855
2856 const bool saw_try_boundary = last->IsTryBoundary();
2857 if (saw_try_boundary) {
2858 DCHECK(predecessor->IsSingleTryBoundary());
2859 DCHECK(!last->AsTryBoundary()->IsEntry());
2860 predecessor = predecessor->GetSinglePredecessor();
2861 last = predecessor->GetLastInstruction();
2862 }
2863
2864 if (last->IsThrow()) {
2865 if (at->IsTryBlock()) {
2866 DCHECK(!saw_try_boundary) << "We don't support inlining of try blocks into try blocks.";
2867 // Create a TryBoundary of kind:exit and point it to the Exit block.
2868 HBasicBlock* new_block = outer_graph->SplitEdge(predecessor, to);
2869 new_block->AddInstruction(
2870 new (allocator) HTryBoundary(HTryBoundary::BoundaryKind::kExit, last->GetDexPc()));
2871 new_block->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2872
2873 // Copy information from the predecessor.
2874 new_block->SetLoopInformation(predecessor->GetLoopInformation());
2875 TryCatchInformation* try_catch_info = predecessor->GetTryCatchInformation();
2876 new_block->SetTryCatchInformation(try_catch_info);
2877 for (HBasicBlock* xhandler :
2878 try_catch_info->GetTryEntry().GetBlock()->GetExceptionalSuccessors()) {
2879 new_block->AddSuccessor(xhandler);
2880 }
2881 DCHECK(try_catch_info->GetTryEntry().HasSameExceptionHandlersAs(
2882 *new_block->GetLastInstruction()->AsTryBoundary()));
2883 } else {
2884 // We either have `Throw->TryBoundary` or `Throw`. We want to point the whole chain to the
2885 // exit, so we recompute `predecessor`
2886 predecessor = to->GetPredecessors()[pred];
2887 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2888 }
2889
2890 --pred;
2891 // We need to re-run dominance information, as the exit block now has
2892 // a new predecessor and potential new dominator.
2893 // TODO(solanes): See if it's worth it to hand-modify the domination chain instead of
2894 // rerunning the dominance for the whole graph.
2895 rerun_dominance = true;
2896 if (predecessor->GetLoopInformation() != nullptr) {
2897 // The loop information might have changed e.g. `predecessor` might not be in a loop
2898 // anymore. We only do this if `predecessor` has loop information as it is impossible for
2899 // predecessor to end up in a loop if it wasn't in one before.
2900 rerun_loop_analysis = true;
2901 }
2902 } else {
2903 if (last->IsReturnVoid()) {
2904 DCHECK(return_value == nullptr);
2905 DCHECK(return_value_phi == nullptr);
2906 } else {
2907 DCHECK(last->IsReturn());
2908 if (return_value_phi != nullptr) {
2909 return_value_phi->AddInput(last->InputAt(0));
2910 } else if (return_value == nullptr) {
2911 return_value = last->InputAt(0);
2912 } else {
2913 // There will be multiple returns.
2914 return_value_phi = new (allocator) HPhi(
2915 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2916 to->AddPhi(return_value_phi);
2917 return_value_phi->AddInput(return_value);
2918 return_value_phi->AddInput(last->InputAt(0));
2919 return_value = return_value_phi;
2920 }
2921 }
2922 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2923 predecessor->RemoveInstruction(last);
2924
2925 if (saw_try_boundary) {
2926 predecessor = to->GetPredecessors()[pred];
2927 DCHECK(predecessor->EndsWithTryBoundary());
2928 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
2929 if (predecessor->GetSuccessors()[0]->GetPredecessors().size() > 1) {
2930 outer_graph->SplitCriticalEdge(predecessor, to);
2931 rerun_dominance = true;
2932 if (predecessor->GetLoopInformation() != nullptr) {
2933 rerun_loop_analysis = true;
2934 }
2935 }
2936 }
2937 }
2938 }
2939 if (rerun_loop_analysis) {
2940 outer_graph->RecomputeDominatorTree();
2941 } else if (rerun_dominance) {
2942 outer_graph->ClearDominanceInformation();
2943 outer_graph->ComputeDominanceInformation();
2944 }
2945 }
2946
2947 // Walk over the entry block and:
2948 // - Move constants from the entry block to the outer_graph's entry block,
2949 // - Replace HParameterValue instructions with their real value.
2950 // - Remove suspend checks, that hold an environment.
2951 // We must do this after the other blocks have been inlined, otherwise ids of
2952 // constants could overlap with the inner graph.
2953 size_t parameter_index = 0;
2954 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2955 HInstruction* current = it.Current();
2956 HInstruction* replacement = nullptr;
2957 if (current->IsNullConstant()) {
2958 replacement = outer_graph->GetNullConstant();
2959 } else if (current->IsIntConstant()) {
2960 replacement = outer_graph->GetIntConstant(current->AsIntConstant()->GetValue());
2961 } else if (current->IsLongConstant()) {
2962 replacement = outer_graph->GetLongConstant(current->AsLongConstant()->GetValue());
2963 } else if (current->IsFloatConstant()) {
2964 replacement = outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue());
2965 } else if (current->IsDoubleConstant()) {
2966 replacement = outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue());
2967 } else if (current->IsParameterValue()) {
2968 if (kIsDebugBuild &&
2969 invoke->IsInvokeStaticOrDirect() &&
2970 invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2971 // Ensure we do not use the last input of `invoke`, as it
2972 // contains a clinit check which is not an actual argument.
2973 size_t last_input_index = invoke->InputCount() - 1;
2974 DCHECK(parameter_index != last_input_index);
2975 }
2976 replacement = invoke->InputAt(parameter_index++);
2977 } else if (current->IsCurrentMethod()) {
2978 replacement = outer_graph->GetCurrentMethod();
2979 } else {
2980 // It is OK to ignore MethodEntryHook for inlined functions.
2981 // In debug mode we don't inline and in release mode method
2982 // tracing is best effort so OK to ignore them.
2983 DCHECK(current->IsGoto() || current->IsSuspendCheck() || current->IsMethodEntryHook());
2984 entry_block_->RemoveInstruction(current);
2985 }
2986 if (replacement != nullptr) {
2987 current->ReplaceWith(replacement);
2988 // If the current is the return value then we need to update the latter.
2989 if (current == return_value) {
2990 DCHECK_EQ(entry_block_, return_value->GetBlock());
2991 return_value = replacement;
2992 }
2993 }
2994 }
2995
2996 return return_value;
2997 }
2998
2999 /*
3000 * Loop will be transformed to:
3001 * old_pre_header
3002 * |
3003 * if_block
3004 * / \
3005 * true_block false_block
3006 * \ /
3007 * new_pre_header
3008 * |
3009 * header
3010 */
TransformLoopHeaderForBCE(HBasicBlock * header)3011 void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
3012 DCHECK(header->IsLoopHeader());
3013 HBasicBlock* old_pre_header = header->GetDominator();
3014
3015 // Need extra block to avoid critical edge.
3016 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3017 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3018 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3019 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3020 AddBlock(if_block);
3021 AddBlock(true_block);
3022 AddBlock(false_block);
3023 AddBlock(new_pre_header);
3024
3025 header->ReplacePredecessor(old_pre_header, new_pre_header);
3026 old_pre_header->successors_.clear();
3027 old_pre_header->dominated_blocks_.clear();
3028
3029 old_pre_header->AddSuccessor(if_block);
3030 if_block->AddSuccessor(true_block); // True successor
3031 if_block->AddSuccessor(false_block); // False successor
3032 true_block->AddSuccessor(new_pre_header);
3033 false_block->AddSuccessor(new_pre_header);
3034
3035 old_pre_header->dominated_blocks_.push_back(if_block);
3036 if_block->SetDominator(old_pre_header);
3037 if_block->dominated_blocks_.push_back(true_block);
3038 true_block->SetDominator(if_block);
3039 if_block->dominated_blocks_.push_back(false_block);
3040 false_block->SetDominator(if_block);
3041 if_block->dominated_blocks_.push_back(new_pre_header);
3042 new_pre_header->SetDominator(if_block);
3043 new_pre_header->dominated_blocks_.push_back(header);
3044 header->SetDominator(new_pre_header);
3045
3046 // Fix reverse post order.
3047 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
3048 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
3049 reverse_post_order_[index_of_header++] = if_block;
3050 reverse_post_order_[index_of_header++] = true_block;
3051 reverse_post_order_[index_of_header++] = false_block;
3052 reverse_post_order_[index_of_header++] = new_pre_header;
3053
3054 // The pre_header can never be a back edge of a loop.
3055 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
3056 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
3057 UpdateLoopAndTryInformationOfNewBlock(
3058 if_block, old_pre_header, /* replace_if_back_edge= */ false);
3059 UpdateLoopAndTryInformationOfNewBlock(
3060 true_block, old_pre_header, /* replace_if_back_edge= */ false);
3061 UpdateLoopAndTryInformationOfNewBlock(
3062 false_block, old_pre_header, /* replace_if_back_edge= */ false);
3063 UpdateLoopAndTryInformationOfNewBlock(
3064 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
3065 }
3066
3067 // Creates a new two-basic-block loop and inserts it between original loop header and
3068 // original loop exit; also adjusts dominators, post order and new LoopInformation.
TransformLoopForVectorization(HBasicBlock * header,HBasicBlock * body,HBasicBlock * exit)3069 HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
3070 HBasicBlock* body,
3071 HBasicBlock* exit) {
3072 DCHECK(header->IsLoopHeader());
3073 HLoopInformation* loop = header->GetLoopInformation();
3074
3075 // Add new loop blocks.
3076 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3077 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3078 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
3079 AddBlock(new_pre_header);
3080 AddBlock(new_header);
3081 AddBlock(new_body);
3082
3083 // Set up control flow.
3084 header->ReplaceSuccessor(exit, new_pre_header);
3085 new_pre_header->AddSuccessor(new_header);
3086 new_header->AddSuccessor(exit);
3087 new_header->AddSuccessor(new_body);
3088 new_body->AddSuccessor(new_header);
3089
3090 // Set up dominators.
3091 header->ReplaceDominatedBlock(exit, new_pre_header);
3092 new_pre_header->SetDominator(header);
3093 new_pre_header->dominated_blocks_.push_back(new_header);
3094 new_header->SetDominator(new_pre_header);
3095 new_header->dominated_blocks_.push_back(new_body);
3096 new_body->SetDominator(new_header);
3097 new_header->dominated_blocks_.push_back(exit);
3098 exit->SetDominator(new_header);
3099
3100 // Fix reverse post order.
3101 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
3102 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
3103 reverse_post_order_[++index_of_header] = new_pre_header;
3104 reverse_post_order_[++index_of_header] = new_header;
3105 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
3106 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
3107 reverse_post_order_[index_of_body] = new_body;
3108
3109 // Add gotos and suspend check (client must add conditional in header).
3110 new_pre_header->AddInstruction(new (allocator_) HGoto());
3111 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
3112 new_header->AddInstruction(suspend_check);
3113 new_body->AddInstruction(new (allocator_) HGoto());
3114 DCHECK(loop->GetSuspendCheck() != nullptr);
3115 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
3116 loop->GetSuspendCheck()->GetEnvironment(), header);
3117
3118 // Update loop information.
3119 new_header->AddBackEdge(new_body);
3120 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
3121 new_header->GetLoopInformation()->Populate();
3122 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
3123 HLoopInformationOutwardIterator it(*new_header);
3124 for (it.Advance(); !it.Done(); it.Advance()) {
3125 it.Current()->Add(new_pre_header);
3126 it.Current()->Add(new_header);
3127 it.Current()->Add(new_body);
3128 }
3129 return new_pre_header;
3130 }
3131
CheckAgainstUpperBound(ReferenceTypeInfo rti,ReferenceTypeInfo upper_bound_rti)3132 static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti) {
3133 if (rti.IsValid()) {
3134 ScopedObjectAccess soa(Thread::Current());
3135 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
3136 << " upper_bound_rti: " << upper_bound_rti
3137 << " rti: " << rti;
3138 DCHECK_IMPLIES(upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes(), rti.IsExact())
3139 << " upper_bound_rti: " << upper_bound_rti
3140 << " rti: " << rti;
3141 }
3142 }
3143
SetReferenceTypeInfo(ReferenceTypeInfo rti)3144 void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
3145 if (kIsDebugBuild) {
3146 DCHECK_EQ(GetType(), DataType::Type::kReference);
3147 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
3148 if (IsBoundType()) {
3149 // Having the test here spares us from making the method virtual just for
3150 // the sake of a DCHECK.
3151 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
3152 }
3153 }
3154 reference_type_handle_ = rti.GetTypeHandle();
3155 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
3156 }
3157
SetReferenceTypeInfoIfValid(ReferenceTypeInfo rti)3158 void HInstruction::SetReferenceTypeInfoIfValid(ReferenceTypeInfo rti) {
3159 if (rti.IsValid()) {
3160 SetReferenceTypeInfo(rti);
3161 }
3162 }
3163
InstructionDataEquals(const HInstruction * other) const3164 bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
3165 const HBoundType* other_bt = other->AsBoundType();
3166 ScopedObjectAccess soa(Thread::Current());
3167 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
3168 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
3169 CanBeNull() == other_bt->CanBeNull();
3170 }
3171
SetUpperBound(const ReferenceTypeInfo & upper_bound,bool can_be_null)3172 void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
3173 if (kIsDebugBuild) {
3174 DCHECK(upper_bound.IsValid());
3175 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
3176 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
3177 }
3178 upper_bound_ = upper_bound;
3179 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
3180 }
3181
HasAnyEnvironmentUseBefore(HInstruction * other)3182 bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
3183 // For now, assume that instructions in different blocks may use the
3184 // environment.
3185 // TODO: Use the control flow to decide if this is true.
3186 if (GetBlock() != other->GetBlock()) {
3187 return true;
3188 }
3189
3190 // We know that we are in the same block. Walk from 'this' to 'other',
3191 // checking to see if there is any instruction with an environment.
3192 HInstruction* current = this;
3193 for (; current != other && current != nullptr; current = current->GetNext()) {
3194 // This is a conservative check, as the instruction result may not be in
3195 // the referenced environment.
3196 if (current->HasEnvironment()) {
3197 return true;
3198 }
3199 }
3200
3201 // We should have been called with 'this' before 'other' in the block.
3202 // Just confirm this.
3203 DCHECK(current != nullptr);
3204 return false;
3205 }
3206
SetIntrinsic(Intrinsics intrinsic,IntrinsicNeedsEnvironment needs_env,IntrinsicSideEffects side_effects,IntrinsicExceptions exceptions)3207 void HInvoke::SetIntrinsic(Intrinsics intrinsic,
3208 IntrinsicNeedsEnvironment needs_env,
3209 IntrinsicSideEffects side_effects,
3210 IntrinsicExceptions exceptions) {
3211 intrinsic_ = intrinsic;
3212 IntrinsicOptimizations opt(this);
3213
3214 // Adjust method's side effects from intrinsic table.
3215 switch (side_effects) {
3216 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
3217 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
3218 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
3219 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
3220 }
3221
3222 if (needs_env == kNoEnvironment) {
3223 opt.SetDoesNotNeedEnvironment();
3224 } else {
3225 // If we need an environment, that means there will be a call, which can trigger GC.
3226 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
3227 }
3228 // Adjust method's exception status from intrinsic table.
3229 SetCanThrow(exceptions == kCanThrow);
3230 }
3231
IsStringAlloc() const3232 bool HNewInstance::IsStringAlloc() const {
3233 return GetEntrypoint() == kQuickAllocStringObject;
3234 }
3235
NeedsEnvironment() const3236 bool HInvoke::NeedsEnvironment() const {
3237 if (!IsIntrinsic()) {
3238 return true;
3239 }
3240 IntrinsicOptimizations opt(*this);
3241 return !opt.GetDoesNotNeedEnvironment();
3242 }
3243
GetDexFileForPcRelativeDexCache() const3244 const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
3245 ArtMethod* caller = GetEnvironment()->GetMethod();
3246 ScopedObjectAccess soa(Thread::Current());
3247 // `caller` is null for a top-level graph representing a method whose declaring
3248 // class was not resolved.
3249 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
3250 }
3251
operator <<(std::ostream & os,HInvokeStaticOrDirect::ClinitCheckRequirement rhs)3252 std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
3253 switch (rhs) {
3254 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
3255 return os << "explicit";
3256 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
3257 return os << "implicit";
3258 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
3259 return os << "none";
3260 }
3261 }
3262
CanBeNull() const3263 bool HInvokeStaticOrDirect::CanBeNull() const {
3264 if (IsStringInit()) {
3265 return false;
3266 }
3267 return HInvoke::CanBeNull();
3268 }
3269
CanBeNull() const3270 bool HInvoke::CanBeNull() const {
3271 switch (GetIntrinsic()) {
3272 case Intrinsics::kThreadCurrentThread:
3273 case Intrinsics::kStringBufferAppend:
3274 case Intrinsics::kStringBufferToString:
3275 case Intrinsics::kStringBuilderAppendObject:
3276 case Intrinsics::kStringBuilderAppendString:
3277 case Intrinsics::kStringBuilderAppendCharSequence:
3278 case Intrinsics::kStringBuilderAppendCharArray:
3279 case Intrinsics::kStringBuilderAppendBoolean:
3280 case Intrinsics::kStringBuilderAppendChar:
3281 case Intrinsics::kStringBuilderAppendInt:
3282 case Intrinsics::kStringBuilderAppendLong:
3283 case Intrinsics::kStringBuilderAppendFloat:
3284 case Intrinsics::kStringBuilderAppendDouble:
3285 case Intrinsics::kStringBuilderToString:
3286 #define DEFINE_BOXED_CASE(name, unused1, unused2, unused3, unused4) \
3287 case Intrinsics::k##name##ValueOf:
3288 BOXED_TYPES(DEFINE_BOXED_CASE)
3289 #undef DEFINE_BOXED_CASE
3290 return false;
3291 default:
3292 return GetType() == DataType::Type::kReference;
3293 }
3294 }
3295
CanDoImplicitNullCheckOn(HInstruction * obj) const3296 bool HInvokeVirtual::CanDoImplicitNullCheckOn(HInstruction* obj) const {
3297 if (obj != InputAt(0)) {
3298 return false;
3299 }
3300 switch (GetIntrinsic()) {
3301 case Intrinsics::kNone:
3302 return true;
3303 case Intrinsics::kReferenceRefersTo:
3304 return true;
3305 default:
3306 // TODO: Add implicit null checks in more intrinsics.
3307 return false;
3308 }
3309 }
3310
InstructionDataEquals(const HInstruction * other) const3311 bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
3312 const HLoadClass* other_load_class = other->AsLoadClass();
3313 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
3314 // names rather than type indexes. However, we shall also have to re-think the hash code.
3315 if (type_index_ != other_load_class->type_index_ ||
3316 GetPackedFields() != other_load_class->GetPackedFields()) {
3317 return false;
3318 }
3319 switch (GetLoadKind()) {
3320 case LoadKind::kBootImageRelRo:
3321 case LoadKind::kJitBootImageAddress:
3322 case LoadKind::kJitTableAddress: {
3323 ScopedObjectAccess soa(Thread::Current());
3324 return GetClass().Get() == other_load_class->GetClass().Get();
3325 }
3326 default:
3327 DCHECK(HasTypeReference(GetLoadKind()));
3328 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
3329 }
3330 }
3331
InstructionDataEquals(const HInstruction * other) const3332 bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3333 const HLoadString* other_load_string = other->AsLoadString();
3334 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3335 // rather than their indexes. However, we shall also have to re-think the hash code.
3336 if (string_index_ != other_load_string->string_index_ ||
3337 GetPackedFields() != other_load_string->GetPackedFields()) {
3338 return false;
3339 }
3340 switch (GetLoadKind()) {
3341 case LoadKind::kBootImageRelRo:
3342 case LoadKind::kJitBootImageAddress:
3343 case LoadKind::kJitTableAddress: {
3344 ScopedObjectAccess soa(Thread::Current());
3345 return GetString().Get() == other_load_string->GetString().Get();
3346 }
3347 default:
3348 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
3349 }
3350 }
3351
RemoveEnvironmentUsers()3352 void HInstruction::RemoveEnvironmentUsers() {
3353 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3354 HEnvironment* user = use.GetUser();
3355 user->SetRawEnvAt(use.GetIndex(), nullptr);
3356 }
3357 env_uses_.clear();
3358 }
3359
ReplaceInstrOrPhiByClone(HInstruction * instr)3360 HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3361 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3362 HBasicBlock* block = instr->GetBlock();
3363
3364 if (instr->IsPhi()) {
3365 HPhi* phi = instr->AsPhi();
3366 DCHECK(!phi->HasEnvironment());
3367 HPhi* phi_clone = clone->AsPhi();
3368 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3369 } else {
3370 block->ReplaceAndRemoveInstructionWith(instr, clone);
3371 if (instr->HasEnvironment()) {
3372 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3373 HLoopInformation* loop_info = block->GetLoopInformation();
3374 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3375 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3376 }
3377 }
3378 }
3379 return clone;
3380 }
3381
operator <<(std::ostream & os,const MoveOperands & rhs)3382 std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3383 os << "["
3384 << " source=" << rhs.GetSource()
3385 << " destination=" << rhs.GetDestination()
3386 << " type=" << rhs.GetType()
3387 << " instruction=";
3388 if (rhs.GetInstruction() != nullptr) {
3389 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3390 } else {
3391 os << "null";
3392 }
3393 os << " ]";
3394 return os;
3395 }
3396
operator <<(std::ostream & os,TypeCheckKind rhs)3397 std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3398 switch (rhs) {
3399 case TypeCheckKind::kUnresolvedCheck:
3400 return os << "unresolved_check";
3401 case TypeCheckKind::kExactCheck:
3402 return os << "exact_check";
3403 case TypeCheckKind::kClassHierarchyCheck:
3404 return os << "class_hierarchy_check";
3405 case TypeCheckKind::kAbstractClassCheck:
3406 return os << "abstract_class_check";
3407 case TypeCheckKind::kInterfaceCheck:
3408 return os << "interface_check";
3409 case TypeCheckKind::kArrayObjectCheck:
3410 return os << "array_object_check";
3411 case TypeCheckKind::kArrayCheck:
3412 return os << "array_check";
3413 case TypeCheckKind::kBitstringCheck:
3414 return os << "bitstring_check";
3415 }
3416 }
3417
3418 // Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3419 #define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3420 static_assert( \
3421 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3422 "Intrinsics enumeration space overflow.");
ART_INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)3423 ART_INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3424 #undef CHECK_INTRINSICS_ENUM_VALUES
3425
3426 // Function that returns whether an intrinsic needs an environment or not.
3427 static inline IntrinsicNeedsEnvironment NeedsEnvironmentIntrinsic(Intrinsics i) {
3428 switch (i) {
3429 case Intrinsics::kNone:
3430 return kNeedsEnvironment; // Non-sensical for intrinsic.
3431 #define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
3432 case Intrinsics::k ## Name: \
3433 return NeedsEnv;
3434 ART_INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3435 #undef OPTIMIZING_INTRINSICS
3436 }
3437 return kNeedsEnvironment;
3438 }
3439
3440 // Function that returns whether an intrinsic has side effects.
GetSideEffectsIntrinsic(Intrinsics i)3441 static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3442 switch (i) {
3443 case Intrinsics::kNone:
3444 return kAllSideEffects;
3445 #define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
3446 case Intrinsics::k ## Name: \
3447 return SideEffects;
3448 ART_INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3449 #undef OPTIMIZING_INTRINSICS
3450 }
3451 return kAllSideEffects;
3452 }
3453
3454 // Function that returns whether an intrinsic can throw exceptions.
GetExceptionsIntrinsic(Intrinsics i)3455 static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3456 switch (i) {
3457 case Intrinsics::kNone:
3458 return kCanThrow;
3459 #define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
3460 case Intrinsics::k ## Name: \
3461 return Exceptions;
3462 ART_INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3463 #undef OPTIMIZING_INTRINSICS
3464 }
3465 return kCanThrow;
3466 }
3467
SetResolvedMethod(ArtMethod * method,bool enable_intrinsic_opt)3468 void HInvoke::SetResolvedMethod(ArtMethod* method, bool enable_intrinsic_opt) {
3469 if (method != nullptr && method->IsIntrinsic() && enable_intrinsic_opt) {
3470 Intrinsics intrinsic = method->GetIntrinsic();
3471 SetIntrinsic(intrinsic,
3472 NeedsEnvironmentIntrinsic(intrinsic),
3473 GetSideEffectsIntrinsic(intrinsic),
3474 GetExceptionsIntrinsic(intrinsic));
3475 }
3476 resolved_method_ = method;
3477 }
3478
IsGEZero(HInstruction * instruction)3479 bool IsGEZero(HInstruction* instruction) {
3480 DCHECK(instruction != nullptr);
3481 if (instruction->IsArrayLength()) {
3482 return true;
3483 } else if (instruction->IsMin()) {
3484 // Instruction MIN(>=0, >=0) is >= 0.
3485 return IsGEZero(instruction->InputAt(0)) &&
3486 IsGEZero(instruction->InputAt(1));
3487 } else if (instruction->IsAbs()) {
3488 // Instruction ABS(>=0) is >= 0.
3489 // NOTE: ABS(minint) = minint prevents assuming
3490 // >= 0 without looking at the argument.
3491 return IsGEZero(instruction->InputAt(0));
3492 }
3493 int64_t value = -1;
3494 return IsInt64AndGet(instruction, &value) && value >= 0;
3495 }
3496
3497 } // namespace art
3498