1 /*
2 * Copyright © 2019 Valve Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 */
24
25 #include "aco_builder.h"
26 #include "aco_ir.h"
27
28 #include "util/enum_operators.h"
29
30 #include <algorithm>
31 #include <map>
32 #include <vector>
33
34 namespace aco {
35
36 enum class pred_defined : uint8_t {
37 undef = 0,
38 const_1 = 1,
39 const_0 = 2,
40 temp = 3,
41 zero = 4, /* all disabled lanes are zero'd out */
42 };
43 MESA_DEFINE_CPP_ENUM_BITFIELD_OPERATORS(pred_defined);
44
45 struct ssa_state {
46 bool checked_preds_for_uniform;
47 bool all_preds_uniform;
48 unsigned loop_nest_depth;
49
50 std::vector<pred_defined> any_pred_defined;
51 std::vector<bool> visited;
52 std::vector<Operand> outputs; /* the output per block */
53 };
54
55 Operand get_output(Program* program, unsigned block_idx, ssa_state* state);
56
57 void
init_outputs(Program * program,ssa_state * state,unsigned start,unsigned end)58 init_outputs(Program* program, ssa_state* state, unsigned start, unsigned end)
59 {
60 for (unsigned i = start; i < end; ++i) {
61 if (state->visited[i])
62 continue;
63 state->outputs[i] = get_output(program, i, state);
64 state->visited[i] = true;
65 }
66 }
67
68 Operand
get_output(Program * program,unsigned block_idx,ssa_state * state)69 get_output(Program* program, unsigned block_idx, ssa_state* state)
70 {
71 Block& block = program->blocks[block_idx];
72
73 if (state->any_pred_defined[block_idx] == pred_defined::undef)
74 return Operand(program->lane_mask);
75
76 if (block.loop_nest_depth < state->loop_nest_depth)
77 /* loop-carried value for loop exit phis */
78 return Operand::zero(program->lane_mask.bytes());
79
80 size_t num_preds = block.linear_preds.size();
81
82 if (block.loop_nest_depth > state->loop_nest_depth || num_preds == 1 ||
83 block.kind & block_kind_loop_exit)
84 return state->outputs[block.linear_preds[0]];
85
86 Operand output;
87
88 /* Loop headers can contain back edges, in which case the predecessor
89 * outputs aren't yet determined because the predecessor is after the block.
90 * The predecessor outputs also depend on the output of the loop header,
91 * so allocate a temporary that will store this block's output and use that
92 * to calculate the predecessor block output. In this case, we always emit a phi
93 * to ensure the allocated temporary is defined. */
94 if (block.kind & block_kind_loop_header) {
95 unsigned start_idx = block_idx + 1;
96 unsigned end_idx = block.linear_preds.back() + 1;
97
98 state->outputs[block_idx] = Operand(Temp(program->allocateTmp(program->lane_mask)));
99 init_outputs(program, state, start_idx, end_idx);
100 output = state->outputs[block_idx];
101 } else if (std::all_of(block.linear_preds.begin() + 1, block.linear_preds.end(),
102 [&](unsigned pred) {
103 return state->outputs[pred] == state->outputs[block.linear_preds[0]];
104 })) {
105 return state->outputs[block.linear_preds[0]];
106 } else {
107 output = Operand(Temp(program->allocateTmp(program->lane_mask)));
108 }
109
110 /* create phi */
111 aco_ptr<Pseudo_instruction> phi{create_instruction<Pseudo_instruction>(
112 aco_opcode::p_linear_phi, Format::PSEUDO, num_preds, 1)};
113 for (unsigned i = 0; i < num_preds; i++)
114 phi->operands[i] = state->outputs[block.linear_preds[i]];
115 phi->definitions[0] = Definition(output.getTemp());
116 block.instructions.emplace(block.instructions.begin(), std::move(phi));
117
118 assert(output.size() == program->lane_mask.size());
119
120 return output;
121 }
122
123 void
insert_before_logical_end(Block * block,aco_ptr<Instruction> instr)124 insert_before_logical_end(Block* block, aco_ptr<Instruction> instr)
125 {
126 auto IsLogicalEnd = [](const aco_ptr<Instruction>& inst) -> bool
127 { return inst->opcode == aco_opcode::p_logical_end; };
128 auto it = std::find_if(block->instructions.crbegin(), block->instructions.crend(), IsLogicalEnd);
129
130 if (it == block->instructions.crend()) {
131 assert(block->instructions.back()->isBranch());
132 block->instructions.insert(std::prev(block->instructions.end()), std::move(instr));
133 } else {
134 block->instructions.insert(std::prev(it.base()), std::move(instr));
135 }
136 }
137
138 void
build_merge_code(Program * program,ssa_state * state,Block * block,Operand cur)139 build_merge_code(Program* program, ssa_state* state, Block* block, Operand cur)
140 {
141 unsigned block_idx = block->index;
142 Definition dst = Definition(state->outputs[block_idx].getTemp());
143 Operand prev = get_output(program, block_idx, state);
144 if (cur.isUndefined())
145 cur = Operand::zero(program->lane_mask.bytes());
146
147 Builder bld(program);
148 auto IsLogicalEnd = [](const aco_ptr<Instruction>& instr) -> bool
149 { return instr->opcode == aco_opcode::p_logical_end; };
150 auto it = std::find_if(block->instructions.rbegin(), block->instructions.rend(), IsLogicalEnd);
151 assert(it != block->instructions.rend());
152 bld.reset(&block->instructions, std::prev(it.base()));
153
154 pred_defined defined = state->any_pred_defined[block_idx];
155 if (defined == pred_defined::undef) {
156 return;
157 } else if (defined == pred_defined::const_0) {
158 bld.sop2(Builder::s_and, dst, bld.def(s1, scc), cur, Operand(exec, bld.lm));
159 return;
160 } else if (defined == pred_defined::const_1) {
161 bld.sop2(Builder::s_orn2, dst, bld.def(s1, scc), cur, Operand(exec, bld.lm));
162 return;
163 }
164
165 assert(prev.isTemp());
166 /* simpler sequence in case prev has only zeros in disabled lanes */
167 if ((defined & pred_defined::zero) == pred_defined::zero) {
168 if (cur.isConstant()) {
169 if (!cur.constantValue()) {
170 bld.copy(dst, prev);
171 return;
172 }
173 cur = Operand(exec, bld.lm);
174 } else {
175 cur =
176 bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), cur, Operand(exec, bld.lm));
177 }
178 bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, cur);
179 return;
180 }
181
182 if (cur.isConstant()) {
183 if (cur.constantValue())
184 bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, Operand(exec, bld.lm));
185 else
186 bld.sop2(Builder::s_andn2, dst, bld.def(s1, scc), prev, Operand(exec, bld.lm));
187 return;
188 }
189 prev =
190 bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), prev, Operand(exec, bld.lm));
191 cur = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), cur, Operand(exec, bld.lm));
192 bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, cur);
193 return;
194 }
195
196 void
build_const_else_merge_code(Program * program,Block & invert_block,aco_ptr<Instruction> & phi)197 build_const_else_merge_code(Program* program, Block& invert_block, aco_ptr<Instruction>& phi)
198 {
199 /* When the else-side operand of a binary merge phi is constant,
200 * we can use a simpler way to lower the phi by emitting some
201 * instructions to the invert block instead.
202 * This allows us to actually delete the else block when it's empty.
203 */
204 assert(invert_block.kind & block_kind_invert);
205 Builder bld(program);
206 Operand then = phi->operands[0];
207 const Operand els = phi->operands[1];
208
209 /* Only -1 (all lanes true) and 0 (all lanes false) constants are supported here. */
210 assert(!then.isConstant() || then.constantEquals(0) || then.constantEquals(-1));
211 assert(els.constantEquals(0) || els.constantEquals(-1));
212
213 if (!then.isConstant()) {
214 /* Left-hand operand is not constant, so we need to emit a phi to access it. */
215 bld.reset(&invert_block.instructions, invert_block.instructions.begin());
216 then = bld.pseudo(aco_opcode::p_linear_phi, bld.def(bld.lm), then, Operand(bld.lm));
217 }
218
219 auto after_phis =
220 std::find_if(invert_block.instructions.begin(), invert_block.instructions.end(),
221 [](const aco_ptr<Instruction>& instr) -> bool { return !is_phi(instr.get()); });
222 bld.reset(&invert_block.instructions, after_phis);
223
224 Temp tmp;
225 if (then.constantEquals(-1) && els.constantEquals(0)) {
226 tmp = bld.copy(bld.def(bld.lm), Operand(exec, bld.lm));
227 } else {
228 Builder::WaveSpecificOpcode opc = els.constantEquals(0) ? Builder::s_and : Builder::s_orn2;
229 tmp = bld.sop2(opc, bld.def(bld.lm), bld.def(s1, scc), then, Operand(exec, bld.lm));
230 }
231
232 /* We can't delete the original phi because that'd invalidate the iterator in lower_phis,
233 * so just make it a trivial phi instead.
234 */
235 phi->opcode = aco_opcode::p_linear_phi;
236 phi->operands[0] = Operand(tmp);
237 phi->operands[1] = Operand(tmp);
238 }
239
240 void
init_state(Program * program,Block * block,ssa_state * state,aco_ptr<Instruction> & phi)241 init_state(Program* program, Block* block, ssa_state* state, aco_ptr<Instruction>& phi)
242 {
243 Builder bld(program);
244
245 /* do this here to avoid resizing in case of no boolean phis */
246 state->visited.resize(program->blocks.size());
247 state->outputs.resize(program->blocks.size());
248 state->any_pred_defined.resize(program->blocks.size());
249 state->loop_nest_depth = block->loop_nest_depth;
250 if (block->kind & block_kind_loop_exit)
251 state->loop_nest_depth += 1;
252 std::fill(state->visited.begin(), state->visited.end(), false);
253 std::fill(state->any_pred_defined.begin(), state->any_pred_defined.end(), pred_defined::undef);
254
255 for (unsigned i = 0; i < block->logical_preds.size(); i++) {
256 if (phi->operands[i].isUndefined())
257 continue;
258 pred_defined defined = pred_defined::temp;
259 if (phi->operands[i].isConstant())
260 defined = phi->operands[i].constantValue() ? pred_defined::const_1 : pred_defined::const_0;
261 for (unsigned succ : program->blocks[block->logical_preds[i]].linear_succs)
262 state->any_pred_defined[succ] |= defined;
263 }
264
265 unsigned start = block->logical_preds[0];
266 unsigned end = block->index;
267
268 /* for loop exit phis, start at the loop pre-header */
269 if (block->kind & block_kind_loop_exit) {
270 while (program->blocks[start].loop_nest_depth >= state->loop_nest_depth)
271 start--;
272 /* If the loop-header has a back-edge, we need to insert a phi.
273 * This will contain a defined value */
274 if (program->blocks[start + 1].linear_preds.size() > 1)
275 state->any_pred_defined[start + 1] = pred_defined::temp;
276 }
277 /* for loop header phis, end at the loop exit */
278 if (block->kind & block_kind_loop_header) {
279 while (program->blocks[end].loop_nest_depth >= state->loop_nest_depth)
280 end++;
281 /* don't propagate the incoming value */
282 state->any_pred_defined[block->index] = pred_defined::undef;
283 }
284
285 /* add dominating zero: this allows to emit simpler merge sequences
286 * if we can ensure that all disabled lanes are always zero on incoming values */
287 // TODO: find more occasions where pred_defined::zero is beneficial (e.g. with 2+ temp merges)
288 if (block->kind & block_kind_loop_exit) {
289 /* zero the loop-carried variable */
290 if (program->blocks[start + 1].linear_preds.size() > 1) {
291 state->any_pred_defined[start + 1] |= pred_defined::zero;
292 // TODO: emit this zero explicitly
293 state->any_pred_defined[start] = pred_defined::const_0;
294 }
295 }
296
297 for (unsigned j = start; j < end; j++) {
298 if (state->any_pred_defined[j] == pred_defined::undef)
299 continue;
300 for (unsigned succ : program->blocks[j].linear_succs)
301 state->any_pred_defined[succ] |= state->any_pred_defined[j];
302 }
303
304 state->any_pred_defined[block->index] = pred_defined::undef;
305
306 for (unsigned i = 0; i < phi->operands.size(); i++) {
307 unsigned pred = block->logical_preds[i];
308 if (state->any_pred_defined[pred] != pred_defined::undef)
309 state->outputs[pred] = Operand(bld.tmp(bld.lm));
310 else
311 state->outputs[pred] = phi->operands[i];
312 assert(state->outputs[pred].size() == bld.lm.size());
313 state->visited[pred] = true;
314 }
315
316 init_outputs(program, state, start, end);
317 }
318
319 void
lower_divergent_bool_phi(Program * program,ssa_state * state,Block * block,aco_ptr<Instruction> & phi)320 lower_divergent_bool_phi(Program* program, ssa_state* state, Block* block,
321 aco_ptr<Instruction>& phi)
322 {
323 if (!state->checked_preds_for_uniform) {
324 state->all_preds_uniform = !(block->kind & block_kind_merge) &&
325 block->linear_preds.size() == block->logical_preds.size();
326 for (unsigned pred : block->logical_preds)
327 state->all_preds_uniform =
328 state->all_preds_uniform && (program->blocks[pred].kind & block_kind_uniform);
329 state->checked_preds_for_uniform = true;
330 }
331
332 if (state->all_preds_uniform) {
333 phi->opcode = aco_opcode::p_linear_phi;
334 return;
335 }
336
337 if (phi->operands.size() == 2 && phi->operands[1].isConstant() &&
338 (block->kind & block_kind_merge)) {
339 build_const_else_merge_code(program, program->blocks[block->linear_idom], phi);
340 return;
341 }
342
343 init_state(program, block, state, phi);
344
345 for (unsigned i = 0; i < phi->operands.size(); i++)
346 build_merge_code(program, state, &program->blocks[block->logical_preds[i]], phi->operands[i]);
347
348 unsigned num_preds = block->linear_preds.size();
349 if (phi->operands.size() != num_preds) {
350 Pseudo_instruction* new_phi{create_instruction<Pseudo_instruction>(
351 aco_opcode::p_linear_phi, Format::PSEUDO, num_preds, 1)};
352 new_phi->definitions[0] = phi->definitions[0];
353 phi.reset(new_phi);
354 } else {
355 phi->opcode = aco_opcode::p_linear_phi;
356 }
357 assert(phi->operands.size() == num_preds);
358
359 for (unsigned i = 0; i < num_preds; i++)
360 phi->operands[i] = state->outputs[block->linear_preds[i]];
361
362 return;
363 }
364
365 void
lower_subdword_phis(Program * program,Block * block,aco_ptr<Instruction> & phi)366 lower_subdword_phis(Program* program, Block* block, aco_ptr<Instruction>& phi)
367 {
368 Builder bld(program);
369 for (unsigned i = 0; i < phi->operands.size(); i++) {
370 if (phi->operands[i].isUndefined())
371 continue;
372 if (phi->operands[i].regClass() == phi->definitions[0].regClass())
373 continue;
374
375 assert(phi->operands[i].isTemp());
376 Block* pred = &program->blocks[block->logical_preds[i]];
377 Temp phi_src = phi->operands[i].getTemp();
378
379 assert(phi_src.regClass().type() == RegType::sgpr);
380 Temp tmp = bld.tmp(RegClass(RegType::vgpr, phi_src.size()));
381 insert_before_logical_end(pred, bld.copy(Definition(tmp), phi_src).get_ptr());
382 Temp new_phi_src = bld.tmp(phi->definitions[0].regClass());
383 insert_before_logical_end(pred, bld.pseudo(aco_opcode::p_extract_vector,
384 Definition(new_phi_src), tmp, Operand::zero())
385 .get_ptr());
386
387 phi->operands[i].setTemp(new_phi_src);
388 }
389 return;
390 }
391
392 void
lower_phis(Program * program)393 lower_phis(Program* program)
394 {
395 ssa_state state;
396
397 for (Block& block : program->blocks) {
398 state.checked_preds_for_uniform = false;
399 for (aco_ptr<Instruction>& phi : block.instructions) {
400 if (phi->opcode == aco_opcode::p_phi) {
401 assert(program->wave_size == 64 ? phi->definitions[0].regClass() != s1
402 : phi->definitions[0].regClass() != s2);
403 if (phi->definitions[0].regClass() == program->lane_mask)
404 lower_divergent_bool_phi(program, &state, &block, phi);
405 else if (phi->definitions[0].regClass().is_subdword())
406 lower_subdword_phis(program, &block, phi);
407 } else if (!is_phi(phi)) {
408 break;
409 }
410 }
411 }
412 }
413
414 } // namespace aco
415