blob: 5437d9bd93c5d224756a43ea4617181fb1ad37dd [file] [log] [blame]
Roland Levillain72bceff2014-09-15 18:29:00 +01001/*
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
17#include "dead_code_elimination.h"
18
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +010019#include "android-base/logging.h"
David Brazdild9c90372016-09-14 16:53:55 +010020#include "base/array_ref.h"
Roland Levillain72bceff2014-09-15 18:29:00 +010021#include "base/bit_vector-inl.h"
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +000022#include "base/logging.h"
Vladimir Marko009d1662017-10-10 13:21:15 +010023#include "base/scoped_arena_allocator.h"
24#include "base/scoped_arena_containers.h"
Vladimir Marko2c45bc92016-10-25 16:54:12 +010025#include "base/stl_util.h"
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +010026#include "optimizing/nodes.h"
David Brazdil84daae52015-05-18 12:06:52 +010027#include "ssa_phi_elimination.h"
Roland Levillain72bceff2014-09-15 18:29:00 +010028
VladimĂ­r Marko434d9682022-11-04 14:04:17 +000029namespace art HIDDEN {
Roland Levillain72bceff2014-09-15 18:29:00 +010030
Vladimir Marko211c2112015-09-24 16:52:33 +010031static void MarkReachableBlocks(HGraph* graph, ArenaBitVector* visited) {
Vladimir Marko009d1662017-10-10 13:21:15 +010032 // Use local allocator for allocating memory.
33 ScopedArenaAllocator allocator(graph->GetArenaStack());
34
35 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocDCE));
Vladimir Marko211c2112015-09-24 16:52:33 +010036 constexpr size_t kDefaultWorlistSize = 8;
37 worklist.reserve(kDefaultWorlistSize);
38 visited->SetBit(graph->GetEntryBlock()->GetBlockId());
39 worklist.push_back(graph->GetEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +010040
Vladimir Marko211c2112015-09-24 16:52:33 +010041 while (!worklist.empty()) {
42 HBasicBlock* block = worklist.back();
43 worklist.pop_back();
44 int block_id = block->GetBlockId();
45 DCHECK(visited->IsBitSet(block_id));
46
47 ArrayRef<HBasicBlock* const> live_successors(block->GetSuccessors());
48 HInstruction* last_instruction = block->GetLastInstruction();
49 if (last_instruction->IsIf()) {
50 HIf* if_instruction = last_instruction->AsIf();
51 HInstruction* condition = if_instruction->InputAt(0);
52 if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +000053 if (condition->AsIntConstant()->IsTrue()) {
Vladimir Marko211c2112015-09-24 16:52:33 +010054 live_successors = live_successors.SubArray(0u, 1u);
55 DCHECK_EQ(live_successors[0], if_instruction->IfTrueSuccessor());
56 } else {
Roland Levillain1a653882016-03-18 18:05:57 +000057 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
Vladimir Marko211c2112015-09-24 16:52:33 +010058 live_successors = live_successors.SubArray(1u, 1u);
59 DCHECK_EQ(live_successors[0], if_instruction->IfFalseSuccessor());
60 }
Mark Mendellfe57faa2015-09-18 09:26:15 -040061 }
Vladimir Marko211c2112015-09-24 16:52:33 +010062 } else if (last_instruction->IsPackedSwitch()) {
63 HPackedSwitch* switch_instruction = last_instruction->AsPackedSwitch();
64 HInstruction* switch_input = switch_instruction->InputAt(0);
65 if (switch_input->IsIntConstant()) {
66 int32_t switch_value = switch_input->AsIntConstant()->GetValue();
67 int32_t start_value = switch_instruction->GetStartValue();
Vladimir Marko430c4f52015-09-25 17:10:15 +010068 // Note: Though the spec forbids packed-switch values to wrap around, we leave
69 // that task to the verifier and use unsigned arithmetic with it's "modulo 2^32"
70 // semantics to check if the value is in range, wrapped or not.
71 uint32_t switch_index =
72 static_cast<uint32_t>(switch_value) - static_cast<uint32_t>(start_value);
Vladimir Marko211c2112015-09-24 16:52:33 +010073 if (switch_index < switch_instruction->GetNumEntries()) {
74 live_successors = live_successors.SubArray(switch_index, 1u);
Vladimir Markoec7802a2015-10-01 20:57:57 +010075 DCHECK_EQ(live_successors[0], block->GetSuccessors()[switch_index]);
Vladimir Marko211c2112015-09-24 16:52:33 +010076 } else {
77 live_successors = live_successors.SubArray(switch_instruction->GetNumEntries(), 1u);
78 DCHECK_EQ(live_successors[0], switch_instruction->GetDefaultBlock());
79 }
Mark Mendellfe57faa2015-09-18 09:26:15 -040080 }
81 }
Vladimir Marko211c2112015-09-24 16:52:33 +010082
83 for (HBasicBlock* successor : live_successors) {
84 // Add only those successors that have not been visited yet.
85 if (!visited->IsBitSet(successor->GetBlockId())) {
86 visited->SetBit(successor->GetBlockId());
87 worklist.push_back(successor);
88 }
David Brazdil2d7352b2015-04-20 14:52:42 +010089 }
90 }
91}
92
93void HDeadCodeElimination::MaybeRecordDeadBlock(HBasicBlock* block) {
94 if (stats_ != nullptr) {
95 stats_->RecordStat(MethodCompilationStat::kRemovedDeadInstruction,
96 block->GetPhis().CountSize() + block->GetInstructions().CountSize());
97 }
98}
99
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100100void HDeadCodeElimination::MaybeRecordSimplifyIf() {
101 if (stats_ != nullptr) {
102 stats_->RecordStat(MethodCompilationStat::kSimplifyIf);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000103 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100104}
105
106static bool HasInput(HCondition* instruction, HInstruction* input) {
107 return (instruction->InputAt(0) == input) ||
108 (instruction->InputAt(1) == input);
109}
110
111static bool HasEquality(IfCondition condition) {
112 switch (condition) {
113 case kCondEQ:
114 case kCondLE:
115 case kCondGE:
116 case kCondBE:
117 case kCondAE:
118 return true;
119 case kCondNE:
120 case kCondLT:
121 case kCondGT:
122 case kCondB:
123 case kCondA:
124 return false;
125 }
126}
127
128static HConstant* Evaluate(HCondition* condition, HInstruction* left, HInstruction* right) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100129 if (left == right && !DataType::IsFloatingPointType(left->GetType())) {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100130 return condition->GetBlock()->GetGraph()->GetIntConstant(
131 HasEquality(condition->GetCondition()) ? 1 : 0);
132 }
133
134 if (!left->IsConstant() || !right->IsConstant()) {
135 return nullptr;
136 }
137
138 if (left->IsIntConstant()) {
139 return condition->Evaluate(left->AsIntConstant(), right->AsIntConstant());
140 } else if (left->IsNullConstant()) {
141 return condition->Evaluate(left->AsNullConstant(), right->AsNullConstant());
142 } else if (left->IsLongConstant()) {
143 return condition->Evaluate(left->AsLongConstant(), right->AsLongConstant());
144 } else if (left->IsFloatConstant()) {
145 return condition->Evaluate(left->AsFloatConstant(), right->AsFloatConstant());
146 } else {
147 DCHECK(left->IsDoubleConstant());
148 return condition->Evaluate(left->AsDoubleConstant(), right->AsDoubleConstant());
149 }
150}
151
Aart Bik4c563ca2018-01-24 16:34:25 -0800152static bool RemoveNonNullControlDependences(HBasicBlock* block, HBasicBlock* throws) {
153 // Test for an if as last statement.
154 if (!block->EndsWithIf()) {
155 return false;
156 }
157 HIf* ifs = block->GetLastInstruction()->AsIf();
158 // Find either:
159 // if obj == null
160 // throws
161 // else
162 // not_throws
163 // or:
164 // if obj != null
165 // not_throws
166 // else
167 // throws
168 HInstruction* cond = ifs->InputAt(0);
169 HBasicBlock* not_throws = nullptr;
170 if (throws == ifs->IfTrueSuccessor() && cond->IsEqual()) {
171 not_throws = ifs->IfFalseSuccessor();
172 } else if (throws == ifs->IfFalseSuccessor() && cond->IsNotEqual()) {
173 not_throws = ifs->IfTrueSuccessor();
174 } else {
175 return false;
176 }
177 DCHECK(cond->IsEqual() || cond->IsNotEqual());
178 HInstruction* obj = cond->InputAt(1);
179 if (obj->IsNullConstant()) {
180 obj = cond->InputAt(0);
181 } else if (!cond->InputAt(0)->IsNullConstant()) {
182 return false;
183 }
184 // Scan all uses of obj and find null check under control dependence.
185 HBoundType* bound = nullptr;
186 const HUseList<HInstruction*>& uses = obj->GetUses();
187 for (auto it = uses.begin(), end = uses.end(); it != end;) {
188 HInstruction* user = it->GetUser();
189 ++it; // increment before possibly replacing
190 if (user->IsNullCheck()) {
191 HBasicBlock* user_block = user->GetBlock();
192 if (user_block != block &&
193 user_block != throws &&
194 block->Dominates(user_block)) {
195 if (bound == nullptr) {
196 ReferenceTypeInfo ti = obj->GetReferenceTypeInfo();
197 bound = new (obj->GetBlock()->GetGraph()->GetAllocator()) HBoundType(obj);
198 bound->SetUpperBound(ti, /*can_be_null*/ false);
199 bound->SetReferenceTypeInfo(ti);
200 bound->SetCanBeNull(false);
201 not_throws->InsertInstructionBefore(bound, not_throws->GetFirstInstruction());
202 }
203 user->ReplaceWith(bound);
204 user_block->RemoveInstruction(user);
205 }
206 }
207 }
208 return bound != nullptr;
209}
210
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100211// Simplify the pattern:
212//
Aart Bika8b8e9b2018-01-09 11:01:02 -0800213// B1
214// / \
Santiago Aboy Solanescef72a62022-04-06 14:13:18 +0000215// | instr_1
216// | ...
217// | instr_n
Aart Bika8b8e9b2018-01-09 11:01:02 -0800218// | foo() // always throws
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +0100219// | instr_n+2
220// | ...
221// | instr_n+m
Aart Bika8b8e9b2018-01-09 11:01:02 -0800222// \ goto B2
223// \ /
224// B2
225//
226// Into:
227//
228// B1
229// / \
Santiago Aboy Solanescef72a62022-04-06 14:13:18 +0000230// | instr_1
231// | ...
232// | instr_n
Aart Bika8b8e9b2018-01-09 11:01:02 -0800233// | foo()
234// | goto Exit
235// | |
236// B2 Exit
237//
238// Rationale:
Santiago Aboy Solanesa3bd09c2022-07-29 14:09:28 +0100239// Removal of the never taken edge to B2 may expose other optimization opportunities, such as code
240// sinking.
241//
242// Note: The example above is a simple one that uses a `goto` but we could end the block with an If,
243// for example.
Aart Bika8b8e9b2018-01-09 11:01:02 -0800244bool HDeadCodeElimination::SimplifyAlwaysThrows() {
Aart Bika8b8e9b2018-01-09 11:01:02 -0800245 HBasicBlock* exit = graph_->GetExitBlock();
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +0100246 if (!graph_->HasAlwaysThrowingInvokes() || exit == nullptr) {
Aart Bika8b8e9b2018-01-09 11:01:02 -0800247 return false;
248 }
249
250 bool rerun_dominance_and_loop_analysis = false;
251
252 // Order does not matter, just pick one.
253 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
Santiago Aboy Solanesa3bd09c2022-07-29 14:09:28 +0100254 if (block->IsTryBlock()) {
Santiago Aboy Solanescef72a62022-04-06 14:13:18 +0000255 // We don't want to perform the simplify always throws optimizations for throws inside of
Santiago Aboy Solanesa3bd09c2022-07-29 14:09:28 +0100256 // tries since those throws might not go to the exit block.
Santiago Aboy Solanescef72a62022-04-06 14:13:18 +0000257 continue;
258 }
259
Santiago Aboy Solanesa3bd09c2022-07-29 14:09:28 +0100260 // We iterate to find the first instruction that always throws. If two instructions always
261 // throw, the first one will throw and the second one will never be reached.
262 HInstruction* throwing_invoke = nullptr;
263 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
264 if (it.Current()->IsInvoke() && it.Current()->AsInvoke()->AlwaysThrows()) {
265 throwing_invoke = it.Current();
266 break;
Aart Bika8b8e9b2018-01-09 11:01:02 -0800267 }
268 }
Santiago Aboy Solanesa3bd09c2022-07-29 14:09:28 +0100269
270 if (throwing_invoke == nullptr) {
271 // No always-throwing instruction found. Continue with the rest of the blocks.
272 continue;
273 }
274
275 // If we are already pointing at the exit block we could still remove the instructions
276 // between the always throwing instruction, and the exit block. If we have no other
277 // instructions, just continue since there's nothing to do.
278 if (block->GetSuccessors().size() == 1 &&
279 block->GetSingleSuccessor() == exit &&
280 block->GetLastInstruction()->GetPrevious() == throwing_invoke) {
281 continue;
282 }
283
284 // We split the block at the throwing instruction, and the instructions after the throwing
285 // instructions will be disconnected from the graph after `block` points to the exit.
286 // `RemoveDeadBlocks` will take care of removing this new block and its instructions.
287 // Even though `SplitBefore` doesn't guarantee the graph to remain in SSA form, it is fine
288 // since we do not break it.
289 HBasicBlock* new_block = block->SplitBefore(throwing_invoke->GetNext(),
290 /* require_graph_not_in_ssa_form= */ false);
291 DCHECK_EQ(block->GetSingleSuccessor(), new_block);
292 block->ReplaceSuccessor(new_block, exit);
293
294 rerun_dominance_and_loop_analysis = true;
295 MaybeRecordStat(stats_, MethodCompilationStat::kSimplifyThrowingInvoke);
296 // Perform a quick follow up optimization on object != null control dependences
297 // that is much cheaper to perform now than in a later phase.
298 // If there are multiple predecessors, none may end with a HIf as required in
299 // RemoveNonNullControlDependences because we split critical edges.
300 if (block->GetPredecessors().size() == 1u &&
301 RemoveNonNullControlDependences(block->GetSinglePredecessor(), block)) {
302 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedNullCheck);
303 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800304 }
305
306 // We need to re-analyze the graph in order to run DCE afterwards.
307 if (rerun_dominance_and_loop_analysis) {
308 graph_->ClearLoopInformation();
309 graph_->ClearDominanceInformation();
310 graph_->BuildDominatorTree();
311 return true;
312 }
313 return false;
314}
315
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100316bool HDeadCodeElimination::SimplifyIfs() {
317 bool simplified_one_or_more_ifs = false;
318 bool rerun_dominance_and_loop_analysis = false;
319
Santiago Aboy Solanes10d68702023-01-24 18:05:10 +0000320 // Iterating in PostOrder it's better for MaybeAddPhi as it can add a Phi for multiple If
321 // instructions in a chain without updating the dominator chain. The branch redirection itself can
322 // work in PostOrder or ReversePostOrder without issues.
323 for (HBasicBlock* block : graph_->GetPostOrder()) {
324 if (block->IsCatchBlock()) {
325 // This simplification cannot be applied to catch blocks, because exception handler edges do
326 // not represent normal control flow. Though in theory this could still apply to normal
327 // control flow going directly to a catch block, we cannot support it at the moment because
328 // the catch Phi's inputs do not correspond to the catch block's predecessors, so we cannot
329 // identify which predecessor corresponds to a given statically evaluated input.
330 continue;
331 }
332
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100333 HInstruction* last = block->GetLastInstruction();
Santiago Aboy Solanes10d68702023-01-24 18:05:10 +0000334 if (!last->IsIf()) {
335 continue;
336 }
337
338 if (block->IsLoopHeader()) {
339 // We do not apply this optimization to loop headers as this could create irreducible loops.
340 continue;
341 }
342
343 // We will add a Phi which allows the simplification to take place in cases where it wouldn't.
344 MaybeAddPhi(block);
345
346 // TODO(solanes): Investigate support for multiple phis in `block`. We can potentially "push
347 // downwards" existing Phis into the true/false branches. For example, let's say we have another
348 // Phi: Phi(x1,x2,x3,x4,x5,x6). This could turn into Phi(x1,x2) in the true branch, Phi(x3,x4)
349 // in the false branch, and remain as Phi(x5,x6) in `block` (for edges that we couldn't
350 // redirect). We might even be able to remove some phis altogether as they will have only one
351 // value.
352 if (block->HasSinglePhi() &&
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100353 block->GetFirstPhi()->HasOnlyOneNonEnvironmentUse()) {
Santiago Aboy Solanes10d68702023-01-24 18:05:10 +0000354 HInstruction* first = block->GetFirstInstruction();
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100355 bool has_only_phi_and_if = (last == first) && (last->InputAt(0) == block->GetFirstPhi());
356 bool has_only_phi_condition_and_if =
357 !has_only_phi_and_if &&
358 first->IsCondition() &&
359 HasInput(first->AsCondition(), block->GetFirstPhi()) &&
360 (first->GetNext() == last) &&
361 (last->InputAt(0) == first) &&
362 first->HasOnlyOneNonEnvironmentUse();
363
364 if (has_only_phi_and_if || has_only_phi_condition_and_if) {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100365 HPhi* phi = block->GetFirstPhi()->AsPhi();
366 bool phi_input_is_left = (first->InputAt(0) == phi);
367
368 // Walk over all inputs of the phis and update the control flow of
369 // predecessors feeding constants to the phi.
370 // Note that phi->InputCount() may change inside the loop.
371 for (size_t i = 0; i < phi->InputCount();) {
372 HInstruction* input = phi->InputAt(i);
373 HInstruction* value_to_check = nullptr;
374 if (has_only_phi_and_if) {
375 if (input->IsIntConstant()) {
376 value_to_check = input;
377 }
378 } else {
379 DCHECK(has_only_phi_condition_and_if);
380 if (phi_input_is_left) {
381 value_to_check = Evaluate(first->AsCondition(), input, first->InputAt(1));
382 } else {
383 value_to_check = Evaluate(first->AsCondition(), first->InputAt(0), input);
384 }
385 }
386 if (value_to_check == nullptr) {
387 // Could not evaluate to a constant, continue iterating over the inputs.
388 ++i;
389 } else {
390 HBasicBlock* predecessor_to_update = block->GetPredecessors()[i];
391 HBasicBlock* successor_to_update = nullptr;
392 if (value_to_check->AsIntConstant()->IsTrue()) {
393 successor_to_update = last->AsIf()->IfTrueSuccessor();
394 } else {
395 DCHECK(value_to_check->AsIntConstant()->IsFalse())
396 << value_to_check->AsIntConstant()->GetValue();
397 successor_to_update = last->AsIf()->IfFalseSuccessor();
398 }
399 predecessor_to_update->ReplaceSuccessor(block, successor_to_update);
400 phi->RemoveInputAt(i);
401 simplified_one_or_more_ifs = true;
402 if (block->IsInLoop()) {
403 rerun_dominance_and_loop_analysis = true;
404 }
405 // For simplicity, don't create a dead block, let the dead code elimination
406 // pass deal with it.
407 if (phi->InputCount() == 1) {
408 break;
409 }
410 }
411 }
412 if (block->GetPredecessors().size() == 1) {
413 phi->ReplaceWith(phi->InputAt(0));
414 block->RemovePhi(phi);
415 if (has_only_phi_condition_and_if) {
416 // Evaluate here (and not wait for a constant folding pass) to open
417 // more opportunities for DCE.
418 HInstruction* result = first->AsCondition()->TryStaticEvaluation();
419 if (result != nullptr) {
420 first->ReplaceWith(result);
421 block->RemoveInstruction(first);
422 }
423 }
424 }
425 if (simplified_one_or_more_ifs) {
426 MaybeRecordSimplifyIf();
427 }
428 }
429 }
430 }
431 // We need to re-analyze the graph in order to run DCE afterwards.
432 if (simplified_one_or_more_ifs) {
433 if (rerun_dominance_and_loop_analysis) {
434 graph_->ClearLoopInformation();
435 graph_->ClearDominanceInformation();
436 graph_->BuildDominatorTree();
437 } else {
438 graph_->ClearDominanceInformation();
439 // We have introduced critical edges, remove them.
440 graph_->SimplifyCFG();
441 graph_->ComputeDominanceInformation();
442 graph_->ComputeTryBlockInformation();
443 }
444 }
445
446 return simplified_one_or_more_ifs;
447}
448
Santiago Aboy Solanes10d68702023-01-24 18:05:10 +0000449void HDeadCodeElimination::MaybeAddPhi(HBasicBlock* block) {
450 DCHECK(block->GetLastInstruction()->IsIf());
451 HIf* if_instruction = block->GetLastInstruction()->AsIf();
452 if (if_instruction->InputAt(0)->IsConstant()) {
453 // Constant values are handled in RemoveDeadBlocks.
454 return;
455 }
456
457 if (block->GetNumberOfPredecessors() < 2u) {
458 // Nothing to redirect.
459 return;
460 }
461
462 if (!block->GetPhis().IsEmpty()) {
463 // SimplifyIf doesn't currently work with multiple phis. Adding a phi here won't help that
464 // optimization.
465 return;
466 }
467
468 HBasicBlock* dominator = block->GetDominator();
469 if (!dominator->EndsWithIf()) {
470 return;
471 }
472
473 HInstruction* input = if_instruction->InputAt(0);
474 HInstruction* dominator_input = dominator->GetLastInstruction()->AsIf()->InputAt(0);
475 const bool same_input = dominator_input == input;
476 if (!same_input) {
477 // Try to see if the dominator has the opposite input (e.g. if(cond) and if(!cond)). If that's
478 // the case, we can perform the optimization with the false and true branches reversed.
479 if (!dominator_input->IsCondition() || !input->IsCondition()) {
480 return;
481 }
482
483 HCondition* block_cond = input->AsCondition();
484 HCondition* dominator_cond = dominator_input->AsCondition();
485
486 if (block_cond->GetLeft() != dominator_cond->GetLeft() ||
487 block_cond->GetRight() != dominator_cond->GetRight() ||
488 block_cond->GetOppositeCondition() != dominator_cond->GetCondition()) {
489 return;
490 }
491 }
492
493 if (kIsDebugBuild) {
494 // `block`'s successors should have only one predecessor. Otherwise, we have a critical edge in
495 // the graph.
496 for (HBasicBlock* succ : block->GetSuccessors()) {
497 DCHECK_EQ(succ->GetNumberOfPredecessors(), 1u);
498 }
499 }
500
501 const size_t pred_size = block->GetNumberOfPredecessors();
502 HPhi* new_phi = new (graph_->GetAllocator())
503 HPhi(graph_->GetAllocator(), kNoRegNumber, pred_size, DataType::Type::kInt32);
504
505 for (size_t index = 0; index < pred_size; index++) {
506 HBasicBlock* pred = block->GetPredecessors()[index];
507 const bool dominated_by_true =
508 dominator->GetLastInstruction()->AsIf()->IfTrueSuccessor()->Dominates(pred);
509 const bool dominated_by_false =
510 dominator->GetLastInstruction()->AsIf()->IfFalseSuccessor()->Dominates(pred);
511 if (dominated_by_true == dominated_by_false) {
512 // In this case, we can't know if we are coming from the true branch, or the false branch. It
513 // happens in cases like:
514 // 1 (outer if)
515 // / \
516 // 2 3 (inner if)
517 // | / \
518 // | 4 5
519 // \/ |
520 // 6 |
521 // \ |
522 // 7 (has the same if(cond) as 1)
523 // |
524 // 8
525 // `7` (which would be `block` in this example), and `6` will come from both the true path and
526 // the false path of `1`. We bumped into something similar in SelectGenerator. See
527 // HSelectGenerator::TryFixupDoubleDiamondPattern.
528 // TODO(solanes): Figure out if we can fix up the graph into a double diamond in a generic way
529 // so that DeadCodeElimination and SelectGenerator can take advantage of it.
530
531 if (!same_input) {
532 // `1` and `7` having the opposite condition is a case we are missing. We could potentially
533 // add a BooleanNot instruction to be able to add the Phi, but it seems like overkill since
534 // this case is not that common.
535 return;
536 }
537
538 // The Phi will have `0`, `1`, and `cond` as inputs. If SimplifyIf redirects 0s and 1s, we
539 // will end up with Phi(cond,...,cond) which will be replaced by `cond`. Effectively, we will
540 // redirect edges that we are able to redirect and the rest will remain as before (i.e. we
541 // won't have an extra Phi).
542 new_phi->SetRawInputAt(index, input);
543 } else {
544 // Redirect to either the true branch (1), or the false branch (0).
545 // Given that `dominated_by_true` is the exact opposite of `dominated_by_false`,
546 // `(same_input && dominated_by_true) || (!same_input && dominated_by_false)` is equivalent to
547 // `same_input == dominated_by_true`.
548 new_phi->SetRawInputAt(
549 index,
550 same_input == dominated_by_true ? graph_->GetIntConstant(1) : graph_->GetIntConstant(0));
551 }
552 }
553
554 block->AddPhi(new_phi);
555 if_instruction->ReplaceInput(new_phi, 0);
556
557 // Remove the old input now, if possible. This allows the branch redirection in SimplifyIf to
558 // work without waiting for another pass of DCE.
559 if (input->IsDeadAndRemovable()) {
560 DCHECK(!same_input)
561 << " if both blocks have the same condition, it shouldn't be dead and removable since the "
562 << "dominator block's If instruction would be using that condition.";
563 input->GetBlock()->RemoveInstruction(input);
564 }
565 MaybeRecordStat(stats_, MethodCompilationStat::kSimplifyIfAddedPhi);
566}
567
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100568void HDeadCodeElimination::ConnectSuccessiveBlocks() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100569 // Order does not matter. Skip the entry block by starting at index 1 in reverse post order.
570 for (size_t i = 1u, size = graph_->GetReversePostOrder().size(); i != size; ++i) {
571 HBasicBlock* block = graph_->GetReversePostOrder()[i];
572 DCHECK(!block->IsEntryBlock());
573 while (block->GetLastInstruction()->IsGoto()) {
574 HBasicBlock* successor = block->GetSingleSuccessor();
575 if (successor->IsExitBlock() || successor->GetPredecessors().size() != 1u) {
576 break;
577 }
578 DCHECK_LT(i, IndexOfElement(graph_->GetReversePostOrder(), successor));
579 block->MergeWith(successor);
580 --size;
581 DCHECK_EQ(size, graph_->GetReversePostOrder().size());
582 DCHECK_EQ(block, graph_->GetReversePostOrder()[i]);
583 // Reiterate on this block in case it can be merged with its new successor.
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100584 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100585 }
586}
587
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000588struct HDeadCodeElimination::TryBelongingInformation {
Santiago Aboy Solanes44ba4232022-11-23 12:27:57 +0000589 explicit TryBelongingInformation(ScopedArenaAllocator* allocator)
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000590 : blocks_in_try(allocator->Adapter(kArenaAllocDCE)),
591 coalesced_try_entries(allocator->Adapter(kArenaAllocDCE)) {}
592
593 // Which blocks belong in the try.
594 ScopedArenaSet<HBasicBlock*> blocks_in_try;
595 // Which other try entries are referencing this same try.
596 ScopedArenaSet<HBasicBlock*> coalesced_try_entries;
597};
598
599bool HDeadCodeElimination::CanPerformTryRemoval(const TryBelongingInformation& try_belonging_info) {
600 for (HBasicBlock* block : try_belonging_info.blocks_in_try) {
601 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
602 if (it.Current()->CanThrow()) {
603 return false;
604 }
605 }
606 }
607 return true;
608}
609
610void HDeadCodeElimination::DisconnectHandlersAndUpdateTryBoundary(
611 HBasicBlock* block,
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000612 /* out */ bool* any_block_in_loop) {
613 if (block->IsInLoop()) {
614 *any_block_in_loop = true;
615 }
616
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000617 // Disconnect the handlers.
618 while (block->GetSuccessors().size() > 1) {
619 HBasicBlock* handler = block->GetSuccessors()[1];
620 DCHECK(handler->IsCatchBlock());
621 block->RemoveSuccessor(handler);
622 handler->RemovePredecessor(block);
623 if (handler->IsInLoop()) {
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000624 *any_block_in_loop = true;
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000625 }
626 }
627
628 // Change TryBoundary to Goto.
629 DCHECK(block->EndsWithTryBoundary());
630 HInstruction* last = block->GetLastInstruction();
631 block->RemoveInstruction(last);
632 block->AddInstruction(new (graph_->GetAllocator()) HGoto(last->GetDexPc()));
633 DCHECK_EQ(block->GetSuccessors().size(), 1u);
634}
635
636void HDeadCodeElimination::RemoveTry(HBasicBlock* try_entry,
637 const TryBelongingInformation& try_belonging_info,
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000638 /* out */ bool* any_block_in_loop) {
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000639 // Update all try entries.
640 DCHECK(try_entry->EndsWithTryBoundary());
641 DCHECK(try_entry->GetLastInstruction()->AsTryBoundary()->IsEntry());
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000642 DisconnectHandlersAndUpdateTryBoundary(try_entry, any_block_in_loop);
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000643
644 for (HBasicBlock* other_try_entry : try_belonging_info.coalesced_try_entries) {
645 DCHECK(other_try_entry->EndsWithTryBoundary());
646 DCHECK(other_try_entry->GetLastInstruction()->AsTryBoundary()->IsEntry());
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000647 DisconnectHandlersAndUpdateTryBoundary(other_try_entry, any_block_in_loop);
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000648 }
649
650 // Update the blocks in the try.
651 for (HBasicBlock* block : try_belonging_info.blocks_in_try) {
652 // Update the try catch information since now the try doesn't exist.
653 block->SetTryCatchInformation(nullptr);
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000654 if (block->IsInLoop()) {
655 *any_block_in_loop = true;
656 }
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000657
658 if (block->EndsWithTryBoundary()) {
659 // Try exits.
660 DCHECK(!block->GetLastInstruction()->AsTryBoundary()->IsEntry());
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000661 DisconnectHandlersAndUpdateTryBoundary(block, any_block_in_loop);
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000662
663 if (block->GetSingleSuccessor()->IsExitBlock()) {
Santiago Aboy Solanese22e84b2022-11-28 11:49:16 +0000664 // `block` used to be a single exit TryBoundary that got turned into a Goto. It
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000665 // is now pointing to the exit which we don't allow. To fix it, we disconnect
Santiago Aboy Solanese22e84b2022-11-28 11:49:16 +0000666 // `block` from its predecessor and RemoveDeadBlocks will remove it from the
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000667 // graph.
668 DCHECK(block->IsSingleGoto());
669 HBasicBlock* predecessor = block->GetSinglePredecessor();
670 predecessor->ReplaceSuccessor(block, graph_->GetExitBlock());
Santiago Aboy Solanese22e84b2022-11-28 11:49:16 +0000671
672 if (!block->GetDominatedBlocks().empty()) {
673 // Update domination tree if `block` dominates a block to keep the graph consistent.
674 DCHECK_EQ(block->GetDominatedBlocks().size(), 1u);
675 DCHECK_EQ(graph_->GetExitBlock()->GetDominator(), block);
676 predecessor->AddDominatedBlock(graph_->GetExitBlock());
677 graph_->GetExitBlock()->SetDominator(predecessor);
678 block->RemoveDominatedBlock(graph_->GetExitBlock());
679 }
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000680 }
681 }
682 }
683}
684
685bool HDeadCodeElimination::RemoveUnneededTries() {
686 if (!graph_->HasTryCatch()) {
687 return false;
688 }
689
690 // Use local allocator for allocating memory.
691 ScopedArenaAllocator allocator(graph_->GetArenaStack());
692
693 // Collect which blocks are part of which try.
694 std::unordered_map<HBasicBlock*, TryBelongingInformation> tries;
695 for (HBasicBlock* block : graph_->GetReversePostOrderSkipEntryBlock()) {
696 if (block->IsTryBlock()) {
697 HBasicBlock* key = block->GetTryCatchInformation()->GetTryEntry().GetBlock();
698 auto it = tries.find(key);
699 if (it == tries.end()) {
700 it = tries.insert({key, TryBelongingInformation(&allocator)}).first;
701 }
702 it->second.blocks_in_try.insert(block);
703 }
704 }
705
706 // Deduplicate the tries which have different try entries but they are really the same try.
707 for (auto it = tries.begin(); it != tries.end(); it++) {
708 DCHECK(it->first->EndsWithTryBoundary());
709 HTryBoundary* try_boundary = it->first->GetLastInstruction()->AsTryBoundary();
710 for (auto other_it = next(it); other_it != tries.end(); /*other_it++ in the loop*/) {
711 DCHECK(other_it->first->EndsWithTryBoundary());
712 HTryBoundary* other_try_boundary = other_it->first->GetLastInstruction()->AsTryBoundary();
713 if (try_boundary->HasSameExceptionHandlersAs(*other_try_boundary)) {
714 // Merge the entries as they are really the same one.
715 // Block merging.
716 it->second.blocks_in_try.insert(other_it->second.blocks_in_try.begin(),
717 other_it->second.blocks_in_try.end());
718
719 // Add the coalesced try entry to update it too.
720 it->second.coalesced_try_entries.insert(other_it->first);
721
722 // Erase the other entry.
723 other_it = tries.erase(other_it);
724 } else {
725 other_it++;
726 }
727 }
728 }
729
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000730 size_t removed_tries = 0;
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000731 bool any_block_in_loop = false;
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000732
733 // Check which tries contain throwing instructions.
734 for (const auto& entry : tries) {
735 if (CanPerformTryRemoval(entry.second)) {
736 ++removed_tries;
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000737 RemoveTry(entry.first, entry.second, &any_block_in_loop);
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000738 }
739 }
740
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000741 if (removed_tries != 0) {
742 // We want to:
743 // 1) Update the dominance information
744 // 2) Remove catch block subtrees, if they are now unreachable.
745 // If we run the dominance recomputation without removing the code, those catch blocks will
746 // not be part of the post order and won't be removed. If we don't run the dominance
747 // recomputation, we risk RemoveDeadBlocks not running it and leaving the graph in an
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000748 // inconsistent state. So, what we can do is run RemoveDeadBlocks and force a recomputation.
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000749 // Note that we are not guaranteed to remove a catch block if we have nested try blocks:
750 //
751 // try {
752 // ... nothing can throw. TryBoundary A ...
753 // try {
754 // ... can throw. TryBoundary B...
755 // } catch (Error e) {}
756 // } catch (Exception e) {}
757 //
758 // In the example above, we can remove the TryBoundary A but the Exception catch cannot be
759 // removed as the TryBoundary B might still throw into that catch. TryBoundary A and B don't get
760 // coalesced since they have different catch handlers.
761
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000762 RemoveDeadBlocks(/* force_recomputation= */ true, any_block_in_loop);
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000763 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedTry, removed_tries);
764 return true;
765 } else {
766 return false;
767 }
768}
769
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000770bool HDeadCodeElimination::RemoveDeadBlocks(bool force_recomputation,
771 bool force_loop_recomputation) {
772 DCHECK_IMPLIES(force_loop_recomputation, force_recomputation);
773
Vladimir Marko009d1662017-10-10 13:21:15 +0100774 // Use local allocator for allocating memory.
775 ScopedArenaAllocator allocator(graph_->GetArenaStack());
776
David Brazdil2d7352b2015-04-20 14:52:42 +0100777 // Classify blocks as reachable/unreachable.
Vladimir Marko009d1662017-10-10 13:21:15 +0100778 ArenaBitVector live_blocks(&allocator, graph_->GetBlocks().size(), false, kArenaAllocDCE);
779 live_blocks.ClearAllBits();
David Brazdila4b8c212015-05-07 09:59:30 +0100780
Vladimir Marko211c2112015-09-24 16:52:33 +0100781 MarkReachableBlocks(graph_, &live_blocks);
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100782 bool removed_one_or_more_blocks = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000783 bool rerun_dominance_and_loop_analysis = false;
David Brazdil2d7352b2015-04-20 14:52:42 +0100784
David Brazdila4b8c212015-05-07 09:59:30 +0100785 // Remove all dead blocks. Iterate in post order because removal needs the
786 // block's chain of dominators and nested loops need to be updated from the
787 // inside out.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100788 for (HBasicBlock* block : graph_->GetPostOrder()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100789 int id = block->GetBlockId();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000790 if (!live_blocks.IsBitSet(id)) {
David Brazdil69a28042015-04-29 17:16:07 +0100791 MaybeRecordDeadBlock(block);
792 block->DisconnectAndDelete();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100793 removed_one_or_more_blocks = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000794 if (block->IsInLoop()) {
795 rerun_dominance_and_loop_analysis = true;
796 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100797 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100798 }
799
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100800 // If we removed at least one block, we need to recompute the full
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000801 // dominator tree and try block membership.
Santiago Aboy Solanesfa55aa02022-11-29 11:42:20 +0000802 if (removed_one_or_more_blocks || force_recomputation) {
803 if (rerun_dominance_and_loop_analysis || force_loop_recomputation) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000804 graph_->ClearLoopInformation();
805 graph_->ClearDominanceInformation();
806 graph_->BuildDominatorTree();
807 } else {
808 graph_->ClearDominanceInformation();
809 graph_->ComputeDominanceInformation();
810 graph_->ComputeTryBlockInformation();
811 }
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100812 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100813 return removed_one_or_more_blocks;
David Brazdil2d7352b2015-04-20 14:52:42 +0100814}
815
816void HDeadCodeElimination::RemoveDeadInstructions() {
Roland Levillain72bceff2014-09-15 18:29:00 +0100817 // Process basic blocks in post-order in the dominator tree, so that
David Brazdil2d7352b2015-04-20 14:52:42 +0100818 // a dead instruction depending on another dead instruction is removed.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100819 for (HBasicBlock* block : graph_->GetPostOrder()) {
Roland Levillain72bceff2014-09-15 18:29:00 +0100820 // Traverse this block's instructions in backward order and remove
821 // the unused ones.
822 HBackwardInstructionIterator i(block->GetInstructions());
823 // Skip the first iteration, as the last instruction of a block is
824 // a branching instruction.
825 DCHECK(i.Current()->IsControlFlow());
826 for (i.Advance(); !i.Done(); i.Advance()) {
827 HInstruction* inst = i.Current();
828 DCHECK(!inst->IsControlFlow());
Aart Bik482095d2016-10-10 15:39:10 -0700829 if (inst->IsDeadAndRemovable()) {
Roland Levillain72bceff2014-09-15 18:29:00 +0100830 block->RemoveInstruction(inst);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700831 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedDeadInstruction);
Roland Levillain72bceff2014-09-15 18:29:00 +0100832 }
833 }
834 }
835}
836
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000837void HDeadCodeElimination::UpdateGraphFlags() {
838 bool has_monitor_operations = false;
839 bool has_simd = false;
840 bool has_bounds_checks = false;
841 bool has_always_throwing_invokes = false;
842
843 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
844 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
845 HInstruction* instruction = it.Current();
846 if (instruction->IsMonitorOperation()) {
847 has_monitor_operations = true;
848 } else if (instruction->IsVecOperation()) {
849 has_simd = true;
850 } else if (instruction->IsBoundsCheck()) {
851 has_bounds_checks = true;
852 } else if (instruction->IsInvoke() && instruction->AsInvoke()->AlwaysThrows()) {
853 has_always_throwing_invokes = true;
854 }
855 }
856 }
857
858 graph_->SetHasMonitorOperations(has_monitor_operations);
859 graph_->SetHasSIMD(has_simd);
860 graph_->SetHasBoundsChecks(has_bounds_checks);
861 graph_->SetHasAlwaysThrowingInvokes(has_always_throwing_invokes);
862}
863
Aart Bik24773202018-04-26 10:28:51 -0700864bool HDeadCodeElimination::Run() {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100865 // Do not eliminate dead blocks if the graph has irreducible loops. We could
866 // support it, but that would require changes in our loop representation to handle
867 // multiple entry points. We decided it was not worth the complexity.
868 if (!graph_->HasIrreducibleLoops()) {
869 // Simplify graph to generate more dead block patterns.
870 ConnectSuccessiveBlocks();
871 bool did_any_simplification = false;
Aart Bika8b8e9b2018-01-09 11:01:02 -0800872 did_any_simplification |= SimplifyAlwaysThrows();
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100873 did_any_simplification |= SimplifyIfs();
874 did_any_simplification |= RemoveDeadBlocks();
Santiago Aboy Solanesb2d364d2022-11-10 10:26:31 +0000875 // We call RemoveDeadBlocks before RemoveUnneededTries to remove the dead blocks from the
876 // previous optimizations. Otherwise, we might detect that a try has throwing instructions but
877 // they are actually dead code. RemoveUnneededTryBoundary will call RemoveDeadBlocks again if
878 // needed.
879 did_any_simplification |= RemoveUnneededTries();
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100880 if (did_any_simplification) {
881 // Connect successive blocks created by dead branches.
882 ConnectSuccessiveBlocks();
883 }
884 }
David Brazdil84daae52015-05-18 12:06:52 +0100885 SsaRedundantPhiElimination(graph_).Run();
David Brazdil2d7352b2015-04-20 14:52:42 +0100886 RemoveDeadInstructions();
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000887 UpdateGraphFlags();
Aart Bik24773202018-04-26 10:28:51 -0700888 return true;
David Brazdil2d7352b2015-04-20 14:52:42 +0100889}
890
Roland Levillain72bceff2014-09-15 18:29:00 +0100891} // namespace art