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 namespace art {
20 
21 static constexpr size_t kMaxInstructionsInBranch = 1u;
22 
23 // Returns true if `block` has only one predecessor, ends with a Goto and
24 // contains at most `kMaxInstructionsInBranch` other movable instruction with
25 // no side-effects.
IsSimpleBlock(HBasicBlock * block)26 static bool IsSimpleBlock(HBasicBlock* block) {
27   if (block->GetPredecessors().size() != 1u) {
28     return false;
29   }
30   DCHECK(block->GetPhis().IsEmpty());
31 
32   size_t num_instructions = 0u;
33   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
34     HInstruction* instruction = it.Current();
35     if (instruction->IsControlFlow()) {
36       return instruction->IsGoto() && num_instructions <= kMaxInstructionsInBranch;
37     } else if (instruction->CanBeMoved() && !instruction->HasSideEffects()) {
38       num_instructions++;
39     } else {
40       return false;
41     }
42   }
43 
44   LOG(FATAL) << "Unreachable";
45   UNREACHABLE();
46 }
47 
48 // Returns true if 'block1' and 'block2' are empty, merge into the same single
49 // successor and the successor can only be reached from them.
BlocksMergeTogether(HBasicBlock * block1,HBasicBlock * block2)50 static bool BlocksMergeTogether(HBasicBlock* block1, HBasicBlock* block2) {
51   return block1->GetSingleSuccessor() == block2->GetSingleSuccessor();
52 }
53 
54 // Returns nullptr if `block` has either no phis or there is more than one phi
55 // with different inputs at `index1` and `index2`. Otherwise returns that phi.
GetSingleChangedPhi(HBasicBlock * block,size_t index1,size_t index2)56 static HPhi* GetSingleChangedPhi(HBasicBlock* block, size_t index1, size_t index2) {
57   DCHECK_NE(index1, index2);
58 
59   HPhi* select_phi = nullptr;
60   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
61     HPhi* phi = it.Current()->AsPhi();
62     if (phi->InputAt(index1) != phi->InputAt(index2)) {
63       if (select_phi == nullptr) {
64         // First phi with different inputs for the two indices found.
65         select_phi = phi;
66       } else {
67         // More than one phis has different inputs for the two indices.
68         return nullptr;
69       }
70     }
71   }
72   return select_phi;
73 }
74 
Run()75 void HSelectGenerator::Run() {
76   // Iterate in post order in the unlikely case that removing one occurrence of
77   // the selection pattern empties a branch block of another occurrence.
78   // Otherwise the order does not matter.
79   for (HBasicBlock* block : graph_->GetPostOrder()) {
80     if (!block->EndsWithIf()) continue;
81 
82     // Find elements of the diamond pattern.
83     HIf* if_instruction = block->GetLastInstruction()->AsIf();
84     HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
85     HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
86     DCHECK_NE(true_block, false_block);
87     if (!IsSimpleBlock(true_block) ||
88         !IsSimpleBlock(false_block) ||
89         !BlocksMergeTogether(true_block, false_block)) {
90       continue;
91     }
92     HBasicBlock* merge_block = true_block->GetSingleSuccessor();
93 
94     // If the branches are not empty, move instructions in front of the If.
95     // TODO(dbrazdil): This puts an instruction between If and its condition.
96     //                 Implement moving of conditions to first users if possible.
97     if (!true_block->IsSingleGoto()) {
98       true_block->GetFirstInstruction()->MoveBefore(if_instruction);
99     }
100     if (!false_block->IsSingleGoto()) {
101       false_block->GetFirstInstruction()->MoveBefore(if_instruction);
102     }
103     DCHECK(true_block->IsSingleGoto());
104     DCHECK(false_block->IsSingleGoto());
105 
106     // Find the resulting true/false values.
107     size_t predecessor_index_true = merge_block->GetPredecessorIndexOf(true_block);
108     size_t predecessor_index_false = merge_block->GetPredecessorIndexOf(false_block);
109     DCHECK_NE(predecessor_index_true, predecessor_index_false);
110 
111     HPhi* phi = GetSingleChangedPhi(merge_block, predecessor_index_true, predecessor_index_false);
112     if (phi == nullptr) {
113       continue;
114     }
115     HInstruction* true_value = phi->InputAt(predecessor_index_true);
116     HInstruction* false_value = phi->InputAt(predecessor_index_false);
117 
118     // Create the Select instruction and insert it in front of the If.
119     HSelect* select = new (graph_->GetArena()) HSelect(if_instruction->InputAt(0),
120                                                        true_value,
121                                                        false_value,
122                                                        if_instruction->GetDexPc());
123     if (phi->GetType() == Primitive::kPrimNot) {
124       select->SetReferenceTypeInfo(phi->GetReferenceTypeInfo());
125     }
126     block->InsertInstructionBefore(select, if_instruction);
127 
128     // Remove the true branch which removes the corresponding Phi input.
129     // If left only with the false branch, the Phi is automatically removed.
130     phi->ReplaceInput(select, predecessor_index_false);
131     bool only_two_predecessors = (merge_block->GetPredecessors().size() == 2u);
132     true_block->DisconnectAndDelete();
133     DCHECK_EQ(only_two_predecessors, phi->GetBlock() == nullptr);
134 
135     // Merge remaining blocks which are now connected with Goto.
136     DCHECK_EQ(block->GetSingleSuccessor(), false_block);
137     block->MergeWith(false_block);
138     if (only_two_predecessors) {
139       DCHECK_EQ(block->GetSingleSuccessor(), merge_block);
140       block->MergeWith(merge_block);
141     }
142 
143     MaybeRecordStat(MethodCompilationStat::kSelectGenerated);
144 
145     // No need to update dominance information, as we are simplifying
146     // a simple diamond shape, where the join block is merged with the
147     // entry block. Any following blocks would have had the join block
148     // as a dominator, and `MergeWith` handles changing that to the
149     // entry block.
150   }
151 }
152 
153 }  // namespace art
154