• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 "control_flow_simplifier.h"
18 
19 #include "optimizing/nodes.h"
20 #include "reference_type_propagation.h"
21 
22 namespace art HIDDEN {
23 
24 static constexpr size_t kMaxInstructionsInBranch = 1u;
25 
HControlFlowSimplifier(HGraph * graph,OptimizingCompilerStats * stats,const char * name)26 HControlFlowSimplifier::HControlFlowSimplifier(HGraph* graph,
27                                                OptimizingCompilerStats* stats,
28                                                const char* name)
29     : HOptimization(graph, name, stats) {
30 }
31 
32 // Returns true if `block` has only one predecessor, ends with a Goto
33 // or a Return and contains at most `kMaxInstructionsInBranch` other
34 // movable instruction with no side-effects.
IsSimpleBlock(HBasicBlock * block)35 static bool IsSimpleBlock(HBasicBlock* block) {
36   if (block->GetPredecessors().size() != 1u) {
37     return false;
38   }
39   DCHECK(block->GetPhis().IsEmpty());
40 
41   size_t num_instructions = 0u;
42   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
43     HInstruction* instruction = it.Current();
44     if (instruction->IsControlFlow()) {
45       return instruction->IsGoto() || instruction->IsReturn();
46     } else if (instruction->CanBeMoved() &&
47                !instruction->HasSideEffects() &&
48                !instruction->CanThrow()) {
49       if (instruction->IsSelect() && instruction->AsSelect()->GetCondition()->GetBlock() == block) {
50         // Count one HCondition and HSelect in the same block as a single instruction.
51         // This enables finding nested selects.
52         continue;
53       } else if (++num_instructions > kMaxInstructionsInBranch) {
54         return false;  // bail as soon as we exceed number of allowed instructions
55       }
56     } else {
57       return false;
58     }
59   }
60 
61   LOG(FATAL) << "Unreachable";
62   UNREACHABLE();
63 }
64 
65 // Returns true if 'block1' and 'block2' are empty and merge into the
66 // same single successor.
BlocksMergeTogether(HBasicBlock * block1,HBasicBlock * block2)67 static bool BlocksMergeTogether(HBasicBlock* block1, HBasicBlock* block2) {
68   return block1->GetSingleSuccessor() == block2->GetSingleSuccessor();
69 }
70 
71 // Search `block` for phis that have different inputs at `index1` and `index2`.
72 // If none is found, returns `{true, nullptr}`.
73 // If exactly one such `phi` is found, returns `{true, phi}`.
74 // Otherwise (if more than one such phi is found), returns `{false, nullptr}`.
HasAtMostOnePhiWithDifferentInputs(HBasicBlock * block,size_t index1,size_t index2)75 static std::pair<bool, HPhi*> HasAtMostOnePhiWithDifferentInputs(HBasicBlock* block,
76                                                                  size_t index1,
77                                                                  size_t index2) {
78   DCHECK_NE(index1, index2);
79 
80   HPhi* select_phi = nullptr;
81   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
82     HPhi* phi = it.Current()->AsPhi();
83     auto&& inputs = phi->GetInputs();
84     if (inputs[index1] == inputs[index2]) {
85       continue;
86     }
87     if (select_phi == nullptr) {
88       // First phi found.
89       select_phi = phi;
90     } else {
91       // More than one phi found, return null.
92       return {false, nullptr};
93     }
94   }
95   return {true, select_phi};
96 }
97 
TryGenerateSelectSimpleDiamondPattern(HBasicBlock * block,ScopedArenaSafeMap<HInstruction *,HSelect * > * cache)98 bool HControlFlowSimplifier::TryGenerateSelectSimpleDiamondPattern(
99     HBasicBlock* block, ScopedArenaSafeMap<HInstruction*, HSelect*>* cache) {
100   DCHECK(block->GetLastInstruction()->IsIf());
101   HIf* if_instruction = block->GetLastInstruction()->AsIf();
102   HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
103   HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
104   DCHECK_NE(true_block, false_block);
105 
106   if (!IsSimpleBlock(true_block) ||
107       !IsSimpleBlock(false_block) ||
108       !BlocksMergeTogether(true_block, false_block)) {
109     return false;
110   }
111   HBasicBlock* merge_block = true_block->GetSingleSuccessor();
112 
113   // If the branches are not empty, move instructions in front of the If.
114   // TODO(dbrazdil): This puts an instruction between If and its condition.
115   //                 Implement moving of conditions to first users if possible.
116   while (!true_block->IsSingleGoto() && !true_block->IsSingleReturn()) {
117     HInstruction* instr = true_block->GetFirstInstruction();
118     DCHECK(!instr->CanThrow());
119     instr->MoveBefore(if_instruction);
120   }
121   while (!false_block->IsSingleGoto() && !false_block->IsSingleReturn()) {
122     HInstruction* instr = false_block->GetFirstInstruction();
123     DCHECK(!instr->CanThrow());
124     instr->MoveBefore(if_instruction);
125   }
126   DCHECK(true_block->IsSingleGoto() || true_block->IsSingleReturn());
127   DCHECK(false_block->IsSingleGoto() || false_block->IsSingleReturn());
128 
129   // Find the resulting true/false values.
130   size_t predecessor_index_true = merge_block->GetPredecessorIndexOf(true_block);
131   size_t predecessor_index_false = merge_block->GetPredecessorIndexOf(false_block);
132   DCHECK_NE(predecessor_index_true, predecessor_index_false);
133 
134   bool both_successors_return = true_block->IsSingleReturn() && false_block->IsSingleReturn();
135   // TODO(solanes): Extend to support multiple phis? e.g.
136   //   int a, b;
137   //   if (bool) {
138   //     a = 0; b = 1;
139   //   } else {
140   //     a = 1; b = 2;
141   //   }
142   //   // use a and b
143   bool at_most_one_phi_with_different_inputs = false;
144   HPhi* phi = nullptr;
145   HInstruction* true_value = nullptr;
146   HInstruction* false_value = nullptr;
147   if (both_successors_return) {
148     // Note: This can create a select with the same then-value and else-value.
149     true_value = true_block->GetFirstInstruction()->InputAt(0);
150     false_value = false_block->GetFirstInstruction()->InputAt(0);
151   } else {
152     std::tie(at_most_one_phi_with_different_inputs, phi) = HasAtMostOnePhiWithDifferentInputs(
153         merge_block, predecessor_index_true, predecessor_index_false);
154     if (!at_most_one_phi_with_different_inputs) {
155       return false;
156     }
157     if (phi != nullptr) {
158       true_value = phi->InputAt(predecessor_index_true);
159       false_value = phi->InputAt(predecessor_index_false);
160     }  // else we don't need to create a `HSelect` at all.
161   }
162   DCHECK(both_successors_return || at_most_one_phi_with_different_inputs);
163 
164   // Create the Select instruction and insert it in front of the If.
165   HInstruction* condition = if_instruction->InputAt(0);
166   HSelect* select = nullptr;
167   if (both_successors_return || phi != nullptr) {
168     select = new (graph_->GetAllocator()) HSelect(condition,
169                                                   true_value,
170                                                   false_value,
171                                                   if_instruction->GetDexPc());
172     block->InsertInstructionBefore(select, if_instruction);
173     if (both_successors_return) {
174       if (true_value->GetType() == DataType::Type::kReference) {
175         DCHECK(false_value->GetType() == DataType::Type::kReference);
176         ReferenceTypePropagation::FixUpSelectType(select, graph_->GetHandleCache());
177       }
178       false_block->GetFirstInstruction()->ReplaceInput(select, 0);
179     } else {
180       if (phi->GetType() == DataType::Type::kReference) {
181         select->SetReferenceTypeInfoIfValid(phi->GetReferenceTypeInfo());
182       }
183       phi->ReplaceInput(select, predecessor_index_false);  // We'll remove the true branch below.
184     }
185   }
186 
187   // Remove the true branch which removes the corresponding Phi input if needed.
188   // If left only with the false branch, the Phi is automatically removed.
189   true_block->DisconnectAndDelete();
190 
191   // Merge remaining blocks which are now connected with Goto.
192   DCHECK_EQ(block->GetSingleSuccessor(), false_block);
193   block->MergeWith(false_block);
194   if (!both_successors_return && merge_block->GetPredecessors().size() == 1u) {
195     DCHECK_IMPLIES(phi != nullptr, phi->GetBlock() == nullptr);
196     DCHECK(merge_block->GetPhis().IsEmpty());
197     DCHECK_EQ(block->GetSingleSuccessor(), merge_block);
198     block->MergeWith(merge_block);
199   }
200 
201   MaybeRecordStat(stats_, select != nullptr ? MethodCompilationStat::kControlFlowSelectGenerated
202                                             : MethodCompilationStat::kControlFlowDiamondRemoved);
203 
204   // Very simple way of finding common subexpressions in the generated HSelect statements
205   // (since this runs after GVN). Lookup by condition, and reuse latest one if possible
206   // (due to post order, latest select is most likely replacement). If needed, we could
207   // improve this by e.g. using the operands in the map as well.
208   if (select != nullptr) {
209     auto it = cache->find(condition);
210     if (it == cache->end()) {
211       cache->Put(condition, select);
212     } else {
213       // Found cached value. See if latest can replace cached in the HIR.
214       HSelect* cached_select = it->second;
215       DCHECK_EQ(cached_select->GetCondition(), select->GetCondition());
216       if (cached_select->GetTrueValue() == select->GetTrueValue() &&
217           cached_select->GetFalseValue() == select->GetFalseValue() &&
218           select->StrictlyDominates(cached_select)) {
219         cached_select->ReplaceWith(select);
220         cached_select->GetBlock()->RemoveInstruction(cached_select);
221       }
222       it->second = select;  // always cache latest
223     }
224   }
225 
226   // No need to update dominance information, as we are simplifying
227   // a simple diamond shape, where the join block is merged with the
228   // entry block. Any following blocks would have had the join block
229   // as a dominator, and `MergeWith` handles changing that to the
230   // entry block
231   return true;
232 }
233 
TryFixupDoubleDiamondPattern(HBasicBlock * block)234 HBasicBlock* HControlFlowSimplifier::TryFixupDoubleDiamondPattern(HBasicBlock* block) {
235   DCHECK(block->GetLastInstruction()->IsIf());
236   HIf* if_instruction = block->GetLastInstruction()->AsIf();
237   HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
238   HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
239   DCHECK_NE(true_block, false_block);
240 
241   // One branch must be a single goto, and the other one the inner if.
242   if (true_block->IsSingleGoto() == false_block->IsSingleGoto()) {
243     return nullptr;
244   }
245 
246   HBasicBlock* single_goto = true_block->IsSingleGoto() ? true_block : false_block;
247   HBasicBlock* inner_if_block = true_block->IsSingleGoto() ? false_block : true_block;
248 
249   // The innner if branch has to be a block with just a comparison and an if.
250   if (!inner_if_block->EndsWithIf() ||
251       inner_if_block->GetLastInstruction()->AsIf()->InputAt(0) !=
252           inner_if_block->GetFirstInstruction() ||
253       inner_if_block->GetLastInstruction()->GetPrevious() !=
254           inner_if_block->GetFirstInstruction() ||
255       !inner_if_block->GetFirstInstruction()->IsCondition()) {
256     return nullptr;
257   }
258 
259   HIf* inner_if_instruction = inner_if_block->GetLastInstruction()->AsIf();
260   HBasicBlock* inner_if_true_block = inner_if_instruction->IfTrueSuccessor();
261   HBasicBlock* inner_if_false_block = inner_if_instruction->IfFalseSuccessor();
262   if (!inner_if_true_block->IsSingleGoto() || !inner_if_false_block->IsSingleGoto()) {
263     return nullptr;
264   }
265 
266   // One must merge into the outer condition and the other must not.
267   if (BlocksMergeTogether(single_goto, inner_if_true_block) ==
268       BlocksMergeTogether(single_goto, inner_if_false_block)) {
269     return nullptr;
270   }
271 
272   // First merge merges the outer if with one of the inner if branches. The block must be a Phi and
273   // a Goto.
274   HBasicBlock* first_merge = single_goto->GetSingleSuccessor();
275   if (first_merge->GetNumberOfPredecessors() != 2 ||
276       first_merge->GetPhis().CountSize() != 1 ||
277       !first_merge->GetLastInstruction()->IsGoto() ||
278       first_merge->GetFirstInstruction() != first_merge->GetLastInstruction()) {
279     return nullptr;
280   }
281 
282   HPhi* first_phi = first_merge->GetFirstPhi()->AsPhi();
283 
284   // Second merge is first_merge and the remainder branch merging. It must be phi + goto, or phi +
285   // return. Depending on the first merge, we define the second merge.
286   HBasicBlock* merges_into_second_merge =
287     BlocksMergeTogether(single_goto, inner_if_true_block)
288       ? inner_if_false_block
289       : inner_if_true_block;
290   if (!BlocksMergeTogether(first_merge, merges_into_second_merge)) {
291     return nullptr;
292   }
293 
294   HBasicBlock* second_merge = merges_into_second_merge->GetSingleSuccessor();
295   if (second_merge->GetNumberOfPredecessors() != 2 ||
296       second_merge->GetPhis().CountSize() != 1 ||
297       !(second_merge->GetLastInstruction()->IsGoto() ||
298         second_merge->GetLastInstruction()->IsReturn()) ||
299       second_merge->GetFirstInstruction() != second_merge->GetLastInstruction()) {
300     return nullptr;
301   }
302 
303   size_t index = second_merge->GetPredecessorIndexOf(merges_into_second_merge);
304   HPhi* second_phi = second_merge->GetFirstPhi()->AsPhi();
305 
306   // Merge the phis.
307   first_phi->AddInput(second_phi->InputAt(index));
308   merges_into_second_merge->ReplaceSuccessor(second_merge, first_merge);
309   second_phi->ReplaceWith(first_phi);
310   second_merge->RemovePhi(second_phi);
311 
312   // Sort out the new domination before merging the blocks
313   DCHECK_EQ(second_merge->GetSinglePredecessor(), first_merge);
314   second_merge->GetDominator()->RemoveDominatedBlock(second_merge);
315   second_merge->SetDominator(first_merge);
316   first_merge->AddDominatedBlock(second_merge);
317   first_merge->MergeWith(second_merge);
318 
319   // No need to update dominance information. There's a chance that `merges_into_second_merge`
320   // doesn't come before `first_merge` but we don't need to fix it since `merges_into_second_merge`
321   // will disappear from the graph altogether when doing the follow-up
322   // TryGenerateSelectSimpleDiamondPattern.
323 
324   return inner_if_block;
325 }
326 
Run()327 bool HControlFlowSimplifier::Run() {
328   bool did_select = false;
329   // Select cache with local allocator.
330   ScopedArenaAllocator allocator(graph_->GetArenaStack());
331   ScopedArenaSafeMap<HInstruction*, HSelect*> cache(
332       std::less<HInstruction*>(), allocator.Adapter(kArenaAllocControlFlowSimplifier));
333 
334   // Iterate in post order in the unlikely case that removing one occurrence of
335   // the selection pattern empties a branch block of another occurrence.
336   for (HBasicBlock* block : graph_->GetPostOrder()) {
337     if (!block->EndsWithIf()) {
338       continue;
339     }
340 
341     if (TryGenerateSelectSimpleDiamondPattern(block, &cache)) {
342       did_select = true;
343     } else {
344       // Try to fix up the odd version of the double diamond pattern. If we could do it, it means
345       // that we can generate two selects.
346       HBasicBlock* inner_if_block = TryFixupDoubleDiamondPattern(block);
347       if (inner_if_block != nullptr) {
348         // Generate the selects now since `inner_if_block` should be after `block` in PostOrder.
349         bool result = TryGenerateSelectSimpleDiamondPattern(inner_if_block, &cache);
350         DCHECK(result);
351         result = TryGenerateSelectSimpleDiamondPattern(block, &cache);
352         DCHECK(result);
353         did_select = true;
354       }
355     }
356   }
357 
358   return did_select;
359 }
360 
361 }  // namespace art
362