blob: f9acf5aa9a90153fc013b924cd550784e512d21d [file] [log] [blame]
David Brazdil74eb1b22015-12-14 11:44:01 +00001/*
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
Aart Bik6d057002018-04-09 15:39:58 -070019#include "base/scoped_arena_containers.h"
Vladimir Marko009d1662017-10-10 13:21:15 +010020#include "reference_type_propagation.h"
21
David Brazdil74eb1b22015-12-14 11:44:01 +000022namespace art {
23
24static constexpr size_t kMaxInstructionsInBranch = 1u;
25
Mads Ager16e52892017-07-14 13:11:37 +020026HSelectGenerator::HSelectGenerator(HGraph* graph,
27 VariableSizedHandleScope* handles,
Aart Bik2ca10eb2017-11-15 15:17:53 -080028 OptimizingCompilerStats* stats,
29 const char* name)
30 : HOptimization(graph, name, stats),
Mads Ager16e52892017-07-14 13:11:37 +020031 handle_scope_(handles) {
32}
33
34// Returns true if `block` has only one predecessor, ends with a Goto
35// or a Return and contains at most `kMaxInstructionsInBranch` other
36// movable instruction with no side-effects.
David Brazdil74eb1b22015-12-14 11:44:01 +000037static bool IsSimpleBlock(HBasicBlock* block) {
38 if (block->GetPredecessors().size() != 1u) {
39 return false;
40 }
41 DCHECK(block->GetPhis().IsEmpty());
42
43 size_t num_instructions = 0u;
44 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
45 HInstruction* instruction = it.Current();
46 if (instruction->IsControlFlow()) {
Mads Ager16e52892017-07-14 13:11:37 +020047 return instruction->IsGoto() || instruction->IsReturn();
David Brazdil74eb1b22015-12-14 11:44:01 +000048 } else if (instruction->CanBeMoved() && !instruction->HasSideEffects()) {
Aart Bik1d746de2018-03-28 16:30:02 -070049 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 }
David Brazdil74eb1b22015-12-14 11:44:01 +000057 } else {
58 return false;
59 }
60 }
61
62 LOG(FATAL) << "Unreachable";
63 UNREACHABLE();
64}
65
Mads Ager16e52892017-07-14 13:11:37 +020066// Returns true if 'block1' and 'block2' are empty and merge into the
67// same single successor.
David Brazdil74eb1b22015-12-14 11:44:01 +000068static 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
73// with different inputs at `index1` and `index2`. Otherwise returns that phi.
74static HPhi* GetSingleChangedPhi(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 (phi->InputAt(index1) != phi->InputAt(index2)) {
81 if (select_phi == nullptr) {
82 // First phi with different inputs for the two indices found.
83 select_phi = phi;
84 } else {
85 // More than one phis has different inputs for the two indices.
86 return nullptr;
87 }
88 }
89 }
90 return select_phi;
91}
92
93void HSelectGenerator::Run() {
Aart Bik6d057002018-04-09 15:39:58 -070094 // Select cache with local allocator.
95 ScopedArenaAllocator allocator(graph_->GetArenaStack());
96 ScopedArenaSafeMap<HInstruction*, HSelect*> cache(
97 std::less<HInstruction*>(), allocator.Adapter(kArenaAllocSelectGenerator));
98
David Brazdil74eb1b22015-12-14 11:44:01 +000099 // Iterate in post order in the unlikely case that removing one occurrence of
100 // the selection pattern empties a branch block of another occurrence.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100101 for (HBasicBlock* block : graph_->GetPostOrder()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000102 if (!block->EndsWithIf()) continue;
103
104 // Find elements of the diamond pattern.
105 HIf* if_instruction = block->GetLastInstruction()->AsIf();
106 HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
107 HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
108 DCHECK_NE(true_block, false_block);
Aart Bik1d746de2018-03-28 16:30:02 -0700109
David Brazdil74eb1b22015-12-14 11:44:01 +0000110 if (!IsSimpleBlock(true_block) ||
111 !IsSimpleBlock(false_block) ||
112 !BlocksMergeTogether(true_block, false_block)) {
113 continue;
114 }
115 HBasicBlock* merge_block = true_block->GetSingleSuccessor();
116
117 // If the branches are not empty, move instructions in front of the If.
118 // TODO(dbrazdil): This puts an instruction between If and its condition.
119 // Implement moving of conditions to first users if possible.
Aart Bik1d746de2018-03-28 16:30:02 -0700120 while (!true_block->IsSingleGoto() && !true_block->IsSingleReturn()) {
David Brazdild6c205e2016-06-07 14:20:52 +0100121 true_block->GetFirstInstruction()->MoveBefore(if_instruction);
David Brazdil74eb1b22015-12-14 11:44:01 +0000122 }
Aart Bik1d746de2018-03-28 16:30:02 -0700123 while (!false_block->IsSingleGoto() && !false_block->IsSingleReturn()) {
David Brazdild6c205e2016-06-07 14:20:52 +0100124 false_block->GetFirstInstruction()->MoveBefore(if_instruction);
David Brazdil74eb1b22015-12-14 11:44:01 +0000125 }
Mads Ager16e52892017-07-14 13:11:37 +0200126 DCHECK(true_block->IsSingleGoto() || true_block->IsSingleReturn());
127 DCHECK(false_block->IsSingleGoto() || false_block->IsSingleReturn());
David Brazdil74eb1b22015-12-14 11:44:01 +0000128
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
Mads Ager16e52892017-07-14 13:11:37 +0200134 bool both_successors_return = true_block->IsSingleReturn() && false_block->IsSingleReturn();
David Brazdil74eb1b22015-12-14 11:44:01 +0000135 HPhi* phi = GetSingleChangedPhi(merge_block, predecessor_index_true, predecessor_index_false);
Mads Ager16e52892017-07-14 13:11:37 +0200136
137 HInstruction* true_value = nullptr;
138 HInstruction* false_value = nullptr;
139 if (both_successors_return) {
140 true_value = true_block->GetFirstInstruction()->InputAt(0);
141 false_value = false_block->GetFirstInstruction()->InputAt(0);
142 } else if (phi != nullptr) {
143 true_value = phi->InputAt(predecessor_index_true);
144 false_value = phi->InputAt(predecessor_index_false);
145 } else {
David Brazdil74eb1b22015-12-14 11:44:01 +0000146 continue;
147 }
Mads Ager16e52892017-07-14 13:11:37 +0200148 DCHECK(both_successors_return || phi != nullptr);
David Brazdil74eb1b22015-12-14 11:44:01 +0000149
150 // Create the Select instruction and insert it in front of the If.
Aart Bik6d057002018-04-09 15:39:58 -0700151 HInstruction* condition = if_instruction->InputAt(0);
152 HSelect* select = new (graph_->GetAllocator()) HSelect(condition,
Vladimir Markoca6fff82017-10-03 14:49:14 +0100153 true_value,
154 false_value,
155 if_instruction->GetDexPc());
Mads Ager16e52892017-07-14 13:11:37 +0200156 if (both_successors_return) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100157 if (true_value->GetType() == DataType::Type::kReference) {
158 DCHECK(false_value->GetType() == DataType::Type::kReference);
Mads Ager16e52892017-07-14 13:11:37 +0200159 ReferenceTypePropagation::FixUpInstructionType(select, handle_scope_);
160 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100161 } else if (phi->GetType() == DataType::Type::kReference) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000162 select->SetReferenceTypeInfo(phi->GetReferenceTypeInfo());
163 }
164 block->InsertInstructionBefore(select, if_instruction);
165
Mads Ager16e52892017-07-14 13:11:37 +0200166 // Remove the true branch which removes the corresponding Phi
167 // input if needed. If left only with the false branch, the Phi is
168 // automatically removed.
169 if (both_successors_return) {
170 false_block->GetFirstInstruction()->ReplaceInput(select, 0);
171 } else {
172 phi->ReplaceInput(select, predecessor_index_false);
173 }
174
David Brazdil74eb1b22015-12-14 11:44:01 +0000175 bool only_two_predecessors = (merge_block->GetPredecessors().size() == 2u);
176 true_block->DisconnectAndDelete();
David Brazdil74eb1b22015-12-14 11:44:01 +0000177
178 // Merge remaining blocks which are now connected with Goto.
179 DCHECK_EQ(block->GetSingleSuccessor(), false_block);
180 block->MergeWith(false_block);
Mads Ager16e52892017-07-14 13:11:37 +0200181 if (!both_successors_return && only_two_predecessors) {
182 DCHECK_EQ(only_two_predecessors, phi->GetBlock() == nullptr);
David Brazdil74eb1b22015-12-14 11:44:01 +0000183 DCHECK_EQ(block->GetSingleSuccessor(), merge_block);
184 block->MergeWith(merge_block);
185 }
186
Igor Murashkin1e065a52017-08-09 13:20:34 -0700187 MaybeRecordStat(stats_, MethodCompilationStat::kSelectGenerated);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100188
Aart Bik6d057002018-04-09 15:39:58 -0700189 // Very simple way of finding common subexpressions in the generated HSelect statements
190 // (since this runs after GVN). Lookup by condition, and reuse latest one if possible
191 // (due to post order, latest select is most likely replacement). If needed, we could
192 // improve this by e.g. using the operands in the map as well.
193 auto it = cache.find(condition);
194 if (it == cache.end()) {
195 cache.Put(condition, select);
196 } else {
197 // Found cached value. See if latest can replace cached in the HIR.
198 HSelect* cached = it->second;
199 DCHECK_EQ(cached->GetCondition(), select->GetCondition());
200 if (cached->GetTrueValue() == select->GetTrueValue() &&
201 cached->GetFalseValue() == select->GetFalseValue() &&
202 select->StrictlyDominates(cached)) {
203 cached->ReplaceWith(select);
204 cached->GetBlock()->RemoveInstruction(cached);
205 }
206 it->second = select; // always cache latest
207 }
208
David Brazdil74eb1b22015-12-14 11:44:01 +0000209 // No need to update dominance information, as we are simplifying
210 // a simple diamond shape, where the join block is merged with the
211 // entry block. Any following blocks would have had the join block
212 // as a dominator, and `MergeWith` handles changing that to the
213 // entry block.
214 }
215}
216
217} // namespace art