blob: 3cc7b0e78d7b2328c275e63369069b07a053349f [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
David Brazdild9c90372016-09-14 16:53:55 +010019#include "base/array_ref.h"
Roland Levillain72bceff2014-09-15 18:29:00 +010020#include "base/bit_vector-inl.h"
Vladimir Marko009d1662017-10-10 13:21:15 +010021#include "base/scoped_arena_allocator.h"
22#include "base/scoped_arena_containers.h"
Vladimir Marko2c45bc92016-10-25 16:54:12 +010023#include "base/stl_util.h"
David Brazdil84daae52015-05-18 12:06:52 +010024#include "ssa_phi_elimination.h"
Roland Levillain72bceff2014-09-15 18:29:00 +010025
26namespace art {
27
Vladimir Marko211c2112015-09-24 16:52:33 +010028static void MarkReachableBlocks(HGraph* graph, ArenaBitVector* visited) {
Vladimir Marko009d1662017-10-10 13:21:15 +010029 // Use local allocator for allocating memory.
30 ScopedArenaAllocator allocator(graph->GetArenaStack());
31
32 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocDCE));
Vladimir Marko211c2112015-09-24 16:52:33 +010033 constexpr size_t kDefaultWorlistSize = 8;
34 worklist.reserve(kDefaultWorlistSize);
35 visited->SetBit(graph->GetEntryBlock()->GetBlockId());
36 worklist.push_back(graph->GetEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +010037
Vladimir Marko211c2112015-09-24 16:52:33 +010038 while (!worklist.empty()) {
39 HBasicBlock* block = worklist.back();
40 worklist.pop_back();
41 int block_id = block->GetBlockId();
42 DCHECK(visited->IsBitSet(block_id));
43
44 ArrayRef<HBasicBlock* const> live_successors(block->GetSuccessors());
45 HInstruction* last_instruction = block->GetLastInstruction();
46 if (last_instruction->IsIf()) {
47 HIf* if_instruction = last_instruction->AsIf();
48 HInstruction* condition = if_instruction->InputAt(0);
49 if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +000050 if (condition->AsIntConstant()->IsTrue()) {
Vladimir Marko211c2112015-09-24 16:52:33 +010051 live_successors = live_successors.SubArray(0u, 1u);
52 DCHECK_EQ(live_successors[0], if_instruction->IfTrueSuccessor());
53 } else {
Roland Levillain1a653882016-03-18 18:05:57 +000054 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
Vladimir Marko211c2112015-09-24 16:52:33 +010055 live_successors = live_successors.SubArray(1u, 1u);
56 DCHECK_EQ(live_successors[0], if_instruction->IfFalseSuccessor());
57 }
Mark Mendellfe57faa2015-09-18 09:26:15 -040058 }
Vladimir Marko211c2112015-09-24 16:52:33 +010059 } else if (last_instruction->IsPackedSwitch()) {
60 HPackedSwitch* switch_instruction = last_instruction->AsPackedSwitch();
61 HInstruction* switch_input = switch_instruction->InputAt(0);
62 if (switch_input->IsIntConstant()) {
63 int32_t switch_value = switch_input->AsIntConstant()->GetValue();
64 int32_t start_value = switch_instruction->GetStartValue();
Vladimir Marko430c4f52015-09-25 17:10:15 +010065 // Note: Though the spec forbids packed-switch values to wrap around, we leave
66 // that task to the verifier and use unsigned arithmetic with it's "modulo 2^32"
67 // semantics to check if the value is in range, wrapped or not.
68 uint32_t switch_index =
69 static_cast<uint32_t>(switch_value) - static_cast<uint32_t>(start_value);
Vladimir Marko211c2112015-09-24 16:52:33 +010070 if (switch_index < switch_instruction->GetNumEntries()) {
71 live_successors = live_successors.SubArray(switch_index, 1u);
Vladimir Markoec7802a2015-10-01 20:57:57 +010072 DCHECK_EQ(live_successors[0], block->GetSuccessors()[switch_index]);
Vladimir Marko211c2112015-09-24 16:52:33 +010073 } else {
74 live_successors = live_successors.SubArray(switch_instruction->GetNumEntries(), 1u);
75 DCHECK_EQ(live_successors[0], switch_instruction->GetDefaultBlock());
76 }
Mark Mendellfe57faa2015-09-18 09:26:15 -040077 }
78 }
Vladimir Marko211c2112015-09-24 16:52:33 +010079
80 for (HBasicBlock* successor : live_successors) {
81 // Add only those successors that have not been visited yet.
82 if (!visited->IsBitSet(successor->GetBlockId())) {
83 visited->SetBit(successor->GetBlockId());
84 worklist.push_back(successor);
85 }
David Brazdil2d7352b2015-04-20 14:52:42 +010086 }
87 }
88}
89
90void HDeadCodeElimination::MaybeRecordDeadBlock(HBasicBlock* block) {
91 if (stats_ != nullptr) {
92 stats_->RecordStat(MethodCompilationStat::kRemovedDeadInstruction,
93 block->GetPhis().CountSize() + block->GetInstructions().CountSize());
94 }
95}
96
Nicolas Geoffraydac9b192016-07-15 10:46:17 +010097void HDeadCodeElimination::MaybeRecordSimplifyIf() {
98 if (stats_ != nullptr) {
99 stats_->RecordStat(MethodCompilationStat::kSimplifyIf);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000100 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100101}
102
103static bool HasInput(HCondition* instruction, HInstruction* input) {
104 return (instruction->InputAt(0) == input) ||
105 (instruction->InputAt(1) == input);
106}
107
108static bool HasEquality(IfCondition condition) {
109 switch (condition) {
110 case kCondEQ:
111 case kCondLE:
112 case kCondGE:
113 case kCondBE:
114 case kCondAE:
115 return true;
116 case kCondNE:
117 case kCondLT:
118 case kCondGT:
119 case kCondB:
120 case kCondA:
121 return false;
122 }
123}
124
125static HConstant* Evaluate(HCondition* condition, HInstruction* left, HInstruction* right) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 if (left == right && !DataType::IsFloatingPointType(left->GetType())) {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100127 return condition->GetBlock()->GetGraph()->GetIntConstant(
128 HasEquality(condition->GetCondition()) ? 1 : 0);
129 }
130
131 if (!left->IsConstant() || !right->IsConstant()) {
132 return nullptr;
133 }
134
135 if (left->IsIntConstant()) {
136 return condition->Evaluate(left->AsIntConstant(), right->AsIntConstant());
137 } else if (left->IsNullConstant()) {
138 return condition->Evaluate(left->AsNullConstant(), right->AsNullConstant());
139 } else if (left->IsLongConstant()) {
140 return condition->Evaluate(left->AsLongConstant(), right->AsLongConstant());
141 } else if (left->IsFloatConstant()) {
142 return condition->Evaluate(left->AsFloatConstant(), right->AsFloatConstant());
143 } else {
144 DCHECK(left->IsDoubleConstant());
145 return condition->Evaluate(left->AsDoubleConstant(), right->AsDoubleConstant());
146 }
147}
148
149// Simplify the pattern:
150//
151// B1 B2 ...
152// goto goto goto
153// \ | /
154// \ | /
155// B3
156// i1 = phi(input, input)
157// (i2 = condition on i1)
158// if i1 (or i2)
159// / \
160// / \
161// B4 B5
162//
163// Into:
164//
165// B1 B2 ...
166// | | |
167// B4 B5 B?
168//
Vladimir Marko606c8f02016-11-03 13:01:28 +0000169// Note that individual edges can be redirected (for example B2->B3
170// can be redirected as B2->B5) without applying this optimization
171// to other incoming edges.
172//
173// This simplification cannot be applied to catch blocks, because
174// exception handler edges do not represent normal control flow.
175// Though in theory this could still apply to normal control flow
176// going directly to a catch block, we cannot support it at the
177// moment because the catch Phi's inputs do not correspond to the
178// catch block's predecessors, so we cannot identify which
179// predecessor corresponds to a given statically evaluated input.
180//
181// We do not apply this optimization to loop headers as this could
182// create irreducible loops. We rely on the suspend check in the
183// loop header to prevent the pattern match.
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100184//
185// Note that we rely on the dead code elimination to get rid of B3.
186bool HDeadCodeElimination::SimplifyIfs() {
187 bool simplified_one_or_more_ifs = false;
188 bool rerun_dominance_and_loop_analysis = false;
189
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100190 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100191 HInstruction* last = block->GetLastInstruction();
192 HInstruction* first = block->GetFirstInstruction();
Vladimir Marko606c8f02016-11-03 13:01:28 +0000193 if (!block->IsCatchBlock() &&
194 last->IsIf() &&
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100195 block->HasSinglePhi() &&
196 block->GetFirstPhi()->HasOnlyOneNonEnvironmentUse()) {
197 bool has_only_phi_and_if = (last == first) && (last->InputAt(0) == block->GetFirstPhi());
198 bool has_only_phi_condition_and_if =
199 !has_only_phi_and_if &&
200 first->IsCondition() &&
201 HasInput(first->AsCondition(), block->GetFirstPhi()) &&
202 (first->GetNext() == last) &&
203 (last->InputAt(0) == first) &&
204 first->HasOnlyOneNonEnvironmentUse();
205
206 if (has_only_phi_and_if || has_only_phi_condition_and_if) {
207 DCHECK(!block->IsLoopHeader());
208 HPhi* phi = block->GetFirstPhi()->AsPhi();
209 bool phi_input_is_left = (first->InputAt(0) == phi);
210
211 // Walk over all inputs of the phis and update the control flow of
212 // predecessors feeding constants to the phi.
213 // Note that phi->InputCount() may change inside the loop.
214 for (size_t i = 0; i < phi->InputCount();) {
215 HInstruction* input = phi->InputAt(i);
216 HInstruction* value_to_check = nullptr;
217 if (has_only_phi_and_if) {
218 if (input->IsIntConstant()) {
219 value_to_check = input;
220 }
221 } else {
222 DCHECK(has_only_phi_condition_and_if);
223 if (phi_input_is_left) {
224 value_to_check = Evaluate(first->AsCondition(), input, first->InputAt(1));
225 } else {
226 value_to_check = Evaluate(first->AsCondition(), first->InputAt(0), input);
227 }
228 }
229 if (value_to_check == nullptr) {
230 // Could not evaluate to a constant, continue iterating over the inputs.
231 ++i;
232 } else {
233 HBasicBlock* predecessor_to_update = block->GetPredecessors()[i];
234 HBasicBlock* successor_to_update = nullptr;
235 if (value_to_check->AsIntConstant()->IsTrue()) {
236 successor_to_update = last->AsIf()->IfTrueSuccessor();
237 } else {
238 DCHECK(value_to_check->AsIntConstant()->IsFalse())
239 << value_to_check->AsIntConstant()->GetValue();
240 successor_to_update = last->AsIf()->IfFalseSuccessor();
241 }
242 predecessor_to_update->ReplaceSuccessor(block, successor_to_update);
243 phi->RemoveInputAt(i);
244 simplified_one_or_more_ifs = true;
245 if (block->IsInLoop()) {
246 rerun_dominance_and_loop_analysis = true;
247 }
248 // For simplicity, don't create a dead block, let the dead code elimination
249 // pass deal with it.
250 if (phi->InputCount() == 1) {
251 break;
252 }
253 }
254 }
255 if (block->GetPredecessors().size() == 1) {
256 phi->ReplaceWith(phi->InputAt(0));
257 block->RemovePhi(phi);
258 if (has_only_phi_condition_and_if) {
259 // Evaluate here (and not wait for a constant folding pass) to open
260 // more opportunities for DCE.
261 HInstruction* result = first->AsCondition()->TryStaticEvaluation();
262 if (result != nullptr) {
263 first->ReplaceWith(result);
264 block->RemoveInstruction(first);
265 }
266 }
267 }
268 if (simplified_one_or_more_ifs) {
269 MaybeRecordSimplifyIf();
270 }
271 }
272 }
273 }
274 // We need to re-analyze the graph in order to run DCE afterwards.
275 if (simplified_one_or_more_ifs) {
276 if (rerun_dominance_and_loop_analysis) {
277 graph_->ClearLoopInformation();
278 graph_->ClearDominanceInformation();
279 graph_->BuildDominatorTree();
280 } else {
281 graph_->ClearDominanceInformation();
282 // We have introduced critical edges, remove them.
283 graph_->SimplifyCFG();
284 graph_->ComputeDominanceInformation();
285 graph_->ComputeTryBlockInformation();
286 }
287 }
288
289 return simplified_one_or_more_ifs;
290}
291
292void HDeadCodeElimination::ConnectSuccessiveBlocks() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100293 // Order does not matter. Skip the entry block by starting at index 1 in reverse post order.
294 for (size_t i = 1u, size = graph_->GetReversePostOrder().size(); i != size; ++i) {
295 HBasicBlock* block = graph_->GetReversePostOrder()[i];
296 DCHECK(!block->IsEntryBlock());
297 while (block->GetLastInstruction()->IsGoto()) {
298 HBasicBlock* successor = block->GetSingleSuccessor();
299 if (successor->IsExitBlock() || successor->GetPredecessors().size() != 1u) {
300 break;
301 }
302 DCHECK_LT(i, IndexOfElement(graph_->GetReversePostOrder(), successor));
303 block->MergeWith(successor);
304 --size;
305 DCHECK_EQ(size, graph_->GetReversePostOrder().size());
306 DCHECK_EQ(block, graph_->GetReversePostOrder()[i]);
307 // Reiterate on this block in case it can be merged with its new successor.
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100308 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100309 }
310}
311
312bool HDeadCodeElimination::RemoveDeadBlocks() {
Vladimir Marko009d1662017-10-10 13:21:15 +0100313 // Use local allocator for allocating memory.
314 ScopedArenaAllocator allocator(graph_->GetArenaStack());
315
David Brazdil2d7352b2015-04-20 14:52:42 +0100316 // Classify blocks as reachable/unreachable.
Vladimir Marko009d1662017-10-10 13:21:15 +0100317 ArenaBitVector live_blocks(&allocator, graph_->GetBlocks().size(), false, kArenaAllocDCE);
318 live_blocks.ClearAllBits();
David Brazdila4b8c212015-05-07 09:59:30 +0100319
Vladimir Marko211c2112015-09-24 16:52:33 +0100320 MarkReachableBlocks(graph_, &live_blocks);
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100321 bool removed_one_or_more_blocks = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000322 bool rerun_dominance_and_loop_analysis = false;
David Brazdil2d7352b2015-04-20 14:52:42 +0100323
David Brazdila4b8c212015-05-07 09:59:30 +0100324 // Remove all dead blocks. Iterate in post order because removal needs the
325 // block's chain of dominators and nested loops need to be updated from the
326 // inside out.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100327 for (HBasicBlock* block : graph_->GetPostOrder()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100328 int id = block->GetBlockId();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000329 if (!live_blocks.IsBitSet(id)) {
David Brazdil69a28042015-04-29 17:16:07 +0100330 MaybeRecordDeadBlock(block);
331 block->DisconnectAndDelete();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100332 removed_one_or_more_blocks = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000333 if (block->IsInLoop()) {
334 rerun_dominance_and_loop_analysis = true;
335 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100336 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100337 }
338
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100339 // If we removed at least one block, we need to recompute the full
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000340 // dominator tree and try block membership.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100341 if (removed_one_or_more_blocks) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000342 if (rerun_dominance_and_loop_analysis) {
343 graph_->ClearLoopInformation();
344 graph_->ClearDominanceInformation();
345 graph_->BuildDominatorTree();
346 } else {
347 graph_->ClearDominanceInformation();
348 graph_->ComputeDominanceInformation();
349 graph_->ComputeTryBlockInformation();
350 }
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100351 }
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100352 return removed_one_or_more_blocks;
David Brazdil2d7352b2015-04-20 14:52:42 +0100353}
354
355void HDeadCodeElimination::RemoveDeadInstructions() {
Roland Levillain72bceff2014-09-15 18:29:00 +0100356 // Process basic blocks in post-order in the dominator tree, so that
David Brazdil2d7352b2015-04-20 14:52:42 +0100357 // a dead instruction depending on another dead instruction is removed.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100358 for (HBasicBlock* block : graph_->GetPostOrder()) {
Roland Levillain72bceff2014-09-15 18:29:00 +0100359 // Traverse this block's instructions in backward order and remove
360 // the unused ones.
361 HBackwardInstructionIterator i(block->GetInstructions());
362 // Skip the first iteration, as the last instruction of a block is
363 // a branching instruction.
364 DCHECK(i.Current()->IsControlFlow());
365 for (i.Advance(); !i.Done(); i.Advance()) {
366 HInstruction* inst = i.Current();
367 DCHECK(!inst->IsControlFlow());
Aart Bik482095d2016-10-10 15:39:10 -0700368 if (inst->IsDeadAndRemovable()) {
Roland Levillain72bceff2014-09-15 18:29:00 +0100369 block->RemoveInstruction(inst);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700370 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedDeadInstruction);
Roland Levillain72bceff2014-09-15 18:29:00 +0100371 }
372 }
373 }
374}
375
David Brazdil2d7352b2015-04-20 14:52:42 +0100376void HDeadCodeElimination::Run() {
Nicolas Geoffraydac9b192016-07-15 10:46:17 +0100377 // Do not eliminate dead blocks if the graph has irreducible loops. We could
378 // support it, but that would require changes in our loop representation to handle
379 // multiple entry points. We decided it was not worth the complexity.
380 if (!graph_->HasIrreducibleLoops()) {
381 // Simplify graph to generate more dead block patterns.
382 ConnectSuccessiveBlocks();
383 bool did_any_simplification = false;
384 did_any_simplification |= SimplifyIfs();
385 did_any_simplification |= RemoveDeadBlocks();
386 if (did_any_simplification) {
387 // Connect successive blocks created by dead branches.
388 ConnectSuccessiveBlocks();
389 }
390 }
David Brazdil84daae52015-05-18 12:06:52 +0100391 SsaRedundantPhiElimination(graph_).Run();
David Brazdil2d7352b2015-04-20 14:52:42 +0100392 RemoveDeadInstructions();
393}
394
Roland Levillain72bceff2014-09-15 18:29:00 +0100395} // namespace art