1 // Copyright (c) 2017 The Khronos Group Inc.
2 // Copyright (c) 2017 Valve Corporation
3 // Copyright (c) 2017 LunarG Inc.
4 // Copyright (c) 2019 Google LLC
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17
18 #include "block_merge_util.h"
19
20 namespace spvtools {
21 namespace opt {
22 namespace blockmergeutil {
23
24 namespace {
25
26 // Returns true if |block| contains a merge instruction.
IsHeader(BasicBlock * block)27 bool IsHeader(BasicBlock* block) { return block->GetMergeInst() != nullptr; }
28
29 // Returns true if |id| contains a merge instruction.
IsHeader(IRContext * context,uint32_t id)30 bool IsHeader(IRContext* context, uint32_t id) {
31 return IsHeader(
32 context->get_instr_block(context->get_def_use_mgr()->GetDef(id)));
33 }
34
35 // Returns true if |id| is the merge target of a merge instruction.
IsMerge(IRContext * context,uint32_t id)36 bool IsMerge(IRContext* context, uint32_t id) {
37 return !context->get_def_use_mgr()->WhileEachUse(id, [](Instruction* user,
38 uint32_t index) {
39 SpvOp op = user->opcode();
40 if ((op == SpvOpLoopMerge || op == SpvOpSelectionMerge) && index == 0u) {
41 return false;
42 }
43 return true;
44 });
45 }
46
47 // Returns true if |block| is the merge target of a merge instruction.
IsMerge(IRContext * context,BasicBlock * block)48 bool IsMerge(IRContext* context, BasicBlock* block) {
49 return IsMerge(context, block->id());
50 }
51
52 // Returns true if |id| is the continue target of a merge instruction.
IsContinue(IRContext * context,uint32_t id)53 bool IsContinue(IRContext* context, uint32_t id) {
54 return !context->get_def_use_mgr()->WhileEachUse(
55 id, [](Instruction* user, uint32_t index) {
56 SpvOp op = user->opcode();
57 if (op == SpvOpLoopMerge && index == 1u) {
58 return false;
59 }
60 return true;
61 });
62 }
63
64 // Removes any OpPhi instructions in |block|, which should have exactly one
65 // predecessor, replacing uses of OpPhi ids with the ids associated with the
66 // predecessor.
EliminateOpPhiInstructions(IRContext * context,BasicBlock * block)67 void EliminateOpPhiInstructions(IRContext* context, BasicBlock* block) {
68 block->ForEachPhiInst([context](Instruction* phi) {
69 assert(2 == phi->NumInOperands() &&
70 "A block can only have one predecessor for block merging to make "
71 "sense.");
72 context->ReplaceAllUsesWith(phi->result_id(),
73 phi->GetSingleWordInOperand(0));
74 context->KillInst(phi);
75 });
76 }
77
78 } // Anonymous namespace
79
CanMergeWithSuccessor(IRContext * context,BasicBlock * block)80 bool CanMergeWithSuccessor(IRContext* context, BasicBlock* block) {
81 // Find block with single successor which has no other predecessors.
82 auto ii = block->end();
83 --ii;
84 Instruction* br = &*ii;
85 if (br->opcode() != SpvOpBranch) {
86 return false;
87 }
88
89 const uint32_t lab_id = br->GetSingleWordInOperand(0);
90 if (context->cfg()->preds(lab_id).size() != 1) {
91 return false;
92 }
93
94 bool pred_is_merge = IsMerge(context, block);
95 bool succ_is_merge = IsMerge(context, lab_id);
96 if (pred_is_merge && succ_is_merge) {
97 // Cannot merge two merges together.
98 return false;
99 }
100
101 if (pred_is_merge && IsContinue(context, lab_id)) {
102 // Cannot merge a continue target with a merge block.
103 return false;
104 }
105
106 Instruction* merge_inst = block->GetMergeInst();
107 const bool pred_is_header = IsHeader(block);
108 if (pred_is_header && lab_id != merge_inst->GetSingleWordInOperand(0u)) {
109 bool succ_is_header = IsHeader(context, lab_id);
110 if (pred_is_header && succ_is_header) {
111 // Cannot merge two headers together when the successor is not the merge
112 // block of the predecessor.
113 return false;
114 }
115
116 // If this is a header block and the successor is not its merge, we must
117 // be careful about which blocks we are willing to merge together.
118 // OpLoopMerge must be followed by a conditional or unconditional branch.
119 // The merge must be a loop merge because a selection merge cannot be
120 // followed by an unconditional branch.
121 BasicBlock* succ_block = context->get_instr_block(lab_id);
122 SpvOp succ_term_op = succ_block->terminator()->opcode();
123 assert(merge_inst->opcode() == SpvOpLoopMerge);
124 if (succ_term_op != SpvOpBranch && succ_term_op != SpvOpBranchConditional) {
125 return false;
126 }
127 }
128 return true;
129 }
130
MergeWithSuccessor(IRContext * context,Function * func,Function::iterator bi)131 void MergeWithSuccessor(IRContext* context, Function* func,
132 Function::iterator bi) {
133 assert(CanMergeWithSuccessor(context, &*bi) &&
134 "Precondition failure for MergeWithSuccessor: it must be legal to "
135 "merge the block and its successor.");
136
137 auto ii = bi->end();
138 --ii;
139 Instruction* br = &*ii;
140 const uint32_t lab_id = br->GetSingleWordInOperand(0);
141 Instruction* merge_inst = bi->GetMergeInst();
142 bool pred_is_header = IsHeader(&*bi);
143
144 // Merge blocks.
145 context->KillInst(br);
146 auto sbi = bi;
147 for (; sbi != func->end(); ++sbi)
148 if (sbi->id() == lab_id) break;
149 // If bi is sbi's only predecessor, it dominates sbi and thus
150 // sbi must follow bi in func's ordering.
151 assert(sbi != func->end());
152
153 // Update the inst-to-block mapping for the instructions in sbi.
154 for (auto& inst : *sbi) {
155 context->set_instr_block(&inst, &*bi);
156 }
157
158 EliminateOpPhiInstructions(context, &*sbi);
159
160 // Now actually move the instructions.
161 bi->AddInstructions(&*sbi);
162
163 if (merge_inst) {
164 if (pred_is_header && lab_id == merge_inst->GetSingleWordInOperand(0u)) {
165 // Merging the header and merge blocks, so remove the structured control
166 // flow declaration.
167 context->KillInst(merge_inst);
168 } else {
169 // Move OpLine/OpNoLine information to merge_inst. This solves
170 // the validation error that OpLine is placed between OpLoopMerge
171 // and OpBranchConditional.
172 auto terminator = bi->terminator();
173 auto& vec = terminator->dbg_line_insts();
174 if (vec.size() > 0) {
175 merge_inst->ClearDbgLineInsts();
176 auto& new_vec = merge_inst->dbg_line_insts();
177 new_vec.insert(new_vec.end(), vec.begin(), vec.end());
178 terminator->ClearDbgLineInsts();
179 for (auto& l_inst : new_vec)
180 context->get_def_use_mgr()->AnalyzeInstDefUse(&l_inst);
181 }
182 // Clear debug scope of terminator to avoid DebugScope
183 // emitted between terminator and merge.
184 terminator->SetDebugScope(DebugScope(kNoDebugScope, kNoInlinedAt));
185 // Move the merge instruction to just before the terminator.
186 merge_inst->InsertBefore(terminator);
187 }
188 }
189 context->ReplaceAllUsesWith(lab_id, bi->id());
190 context->KillInst(sbi->GetLabelInst());
191 (void)sbi.Erase();
192 }
193
194 } // namespace blockmergeutil
195 } // namespace opt
196 } // namespace spvtools
197