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