• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2024 Valve Corporation
3  *
4  * SPDX-License-Identifier: MIT
5  */
6 
7 #include "aco_ir.h"
8 
9 #include <algorithm>
10 #include <vector>
11 
12 namespace aco {
13 namespace {
14 
15 struct jump_threading_ctx {
16    std::vector<bool> blocks_incoming_exec_used;
17    Program* program;
18 
jump_threading_ctxaco::__anon58783e490111::jump_threading_ctx19    jump_threading_ctx(Program* program_)
20        : blocks_incoming_exec_used(program_->blocks.size(), true), program(program_)
21    {}
22 };
23 
24 bool
is_empty_block(Block * block,bool ignore_exec_writes)25 is_empty_block(Block* block, bool ignore_exec_writes)
26 {
27    /* check if this block is empty and the exec mask is not needed */
28    for (aco_ptr<Instruction>& instr : block->instructions) {
29       switch (instr->opcode) {
30       case aco_opcode::p_linear_phi:
31       case aco_opcode::p_phi:
32       case aco_opcode::p_logical_start:
33       case aco_opcode::p_logical_end:
34       case aco_opcode::p_branch: break;
35       case aco_opcode::p_parallelcopy:
36          for (unsigned i = 0; i < instr->definitions.size(); i++) {
37             if (ignore_exec_writes && instr->definitions[i].physReg() == exec)
38                continue;
39             if (instr->definitions[i].physReg() != instr->operands[i].physReg())
40                return false;
41          }
42          break;
43       case aco_opcode::s_andn2_b64:
44       case aco_opcode::s_andn2_b32:
45          if (ignore_exec_writes && instr->definitions[0].physReg() == exec)
46             break;
47          return false;
48       default: return false;
49       }
50    }
51    return true;
52 }
53 
54 void
try_remove_merge_block(jump_threading_ctx & ctx,Block * block)55 try_remove_merge_block(jump_threading_ctx& ctx, Block* block)
56 {
57    if (block->linear_succs.size() != 1)
58       return;
59 
60    unsigned succ_idx = block->linear_succs[0];
61 
62    /* Check if this block is empty, if the successor is an early block,
63     * we didn't gather incoming_exec_used for it yet.
64     */
65    if (!is_empty_block(block, !ctx.blocks_incoming_exec_used[succ_idx] && block->index < succ_idx))
66       return;
67 
68    /* keep the branch instruction and remove the rest */
69    aco_ptr<Instruction> branch = std::move(block->instructions.back());
70    block->instructions.clear();
71    block->instructions.emplace_back(std::move(branch));
72 }
73 
74 void
try_remove_invert_block(jump_threading_ctx & ctx,Block * block)75 try_remove_invert_block(jump_threading_ctx& ctx, Block* block)
76 {
77    assert(block->linear_succs.size() == 2);
78    /* only remove this block if the successor got removed as well */
79    if (block->linear_succs[0] != block->linear_succs[1])
80       return;
81 
82    unsigned succ_idx = block->linear_succs[0];
83    assert(block->index < succ_idx);
84 
85    /* check if block is otherwise empty */
86    if (!is_empty_block(block, !ctx.blocks_incoming_exec_used[succ_idx]))
87       return;
88 
89    assert(block->linear_preds.size() == 2);
90    for (unsigned i = 0; i < 2; i++) {
91       Block* pred = &ctx.program->blocks[block->linear_preds[i]];
92       pred->linear_succs[0] = succ_idx;
93       ctx.program->blocks[succ_idx].linear_preds[i] = pred->index;
94 
95       Pseudo_branch_instruction& branch = pred->instructions.back()->branch();
96       assert(branch.isBranch());
97       branch.target[0] = succ_idx;
98       branch.target[1] = succ_idx;
99    }
100 
101    block->instructions.clear();
102    block->linear_preds.clear();
103    block->linear_succs.clear();
104 }
105 
106 void
try_remove_simple_block(jump_threading_ctx & ctx,Block * block)107 try_remove_simple_block(jump_threading_ctx& ctx, Block* block)
108 {
109    if (!is_empty_block(block, false))
110       return;
111 
112    Block& pred = ctx.program->blocks[block->linear_preds[0]];
113    Block& succ = ctx.program->blocks[block->linear_succs[0]];
114    Pseudo_branch_instruction& branch = pred.instructions.back()->branch();
115    if (branch.opcode == aco_opcode::p_branch) {
116       branch.target[0] = succ.index;
117       branch.target[1] = succ.index;
118    } else if (branch.target[0] == block->index) {
119       branch.target[0] = succ.index;
120    } else if (branch.target[0] == succ.index) {
121       assert(branch.target[1] == block->index);
122       branch.target[1] = succ.index;
123       branch.opcode = aco_opcode::p_branch;
124       branch.rarely_taken = branch.never_taken = false;
125    } else if (branch.target[1] == block->index) {
126       /* check if there is a fall-through path from block to succ */
127       bool falls_through = block->index < succ.index;
128       for (unsigned j = block->index + 1; falls_through && j < succ.index; j++) {
129          assert(ctx.program->blocks[j].index == j);
130          if (!ctx.program->blocks[j].instructions.empty())
131             falls_through = false;
132       }
133       if (falls_through) {
134          branch.target[1] = succ.index;
135       } else {
136          /* check if there is a fall-through path for the alternative target */
137          if (block->index >= branch.target[0])
138             return;
139          for (unsigned j = block->index + 1; j < branch.target[0]; j++) {
140             if (!ctx.program->blocks[j].instructions.empty())
141                return;
142          }
143 
144          /* This is a (uniform) break or continue block. The branch condition has to be inverted. */
145          if (branch.opcode == aco_opcode::p_cbranch_z)
146             branch.opcode = aco_opcode::p_cbranch_nz;
147          else if (branch.opcode == aco_opcode::p_cbranch_nz)
148             branch.opcode = aco_opcode::p_cbranch_z;
149          else
150             assert(false);
151          /* also invert the linear successors */
152          pred.linear_succs[0] = pred.linear_succs[1];
153          pred.linear_succs[1] = succ.index;
154          branch.target[1] = branch.target[0];
155          branch.target[0] = succ.index;
156       }
157    } else {
158       assert(false);
159    }
160 
161    if (branch.target[0] == branch.target[1]) {
162       while (branch.operands.size())
163          branch.operands.pop_back();
164 
165       branch.opcode = aco_opcode::p_branch;
166       branch.rarely_taken = branch.never_taken = false;
167    }
168 
169    for (unsigned i = 0; i < pred.linear_succs.size(); i++)
170       if (pred.linear_succs[i] == block->index)
171          pred.linear_succs[i] = succ.index;
172 
173    for (unsigned i = 0; i < succ.linear_preds.size(); i++)
174       if (succ.linear_preds[i] == block->index)
175          succ.linear_preds[i] = pred.index;
176 
177    block->instructions.clear();
178    block->linear_preds.clear();
179    block->linear_succs.clear();
180 }
181 
182 bool
is_simple_copy(Instruction * instr)183 is_simple_copy(Instruction* instr)
184 {
185    return instr->opcode == aco_opcode::p_parallelcopy && instr->definitions.size() == 1;
186 }
187 
188 void
try_merge_break_with_continue(jump_threading_ctx & ctx,Block * block)189 try_merge_break_with_continue(jump_threading_ctx& ctx, Block* block)
190 {
191    /* Look for this:
192     * BB1:
193     *    ...
194     *    p_branch_z exec BB3, BB2
195     * BB2:
196     *    ...
197     *    s[0:1], scc = s_andn2 s[0:1], exec
198     *    p_branch_z scc BB4, BB3
199     * BB3:
200     *    exec = p_parallelcopy s[0:1]
201     *    p_branch BB1
202     * BB4:
203     *    ...
204     *
205     * And turn it into this:
206     * BB1:
207     *    ...
208     *    p_branch_z exec BB3, BB2
209     * BB2:
210     *    ...
211     *    p_branch BB3
212     * BB3:
213     *    s[0:1], scc, exec = s_andn2_wrexec s[0:1], exec
214     *    p_branch_nz scc BB1, BB4
215     * BB4:
216     *    ...
217     */
218    if (block->linear_succs.size() != 2 || block->instructions.size() < 2)
219       return;
220 
221    Pseudo_branch_instruction* branch = &block->instructions.back()->branch();
222    if (branch->operands[0].physReg() != scc || branch->opcode != aco_opcode::p_cbranch_z)
223       return;
224 
225    Block* merge = &ctx.program->blocks[branch->target[1]];
226    Block* loopexit = &ctx.program->blocks[branch->target[0]];
227 
228    /* Just a jump to the loop header. */
229    if (merge->linear_succs.size() != 1)
230       return;
231 
232    /* We want to use the loopexit as the fallthrough block from merge,
233     * so there shouldn't be a block inbetween.
234     */
235    for (unsigned i = merge->index + 1; i < loopexit->index; i++) {
236       if (!ctx.program->blocks[i].instructions.empty())
237          return;
238    }
239 
240    for (unsigned merge_pred : merge->linear_preds) {
241       Block* pred = &ctx.program->blocks[merge_pred];
242       if (pred == block)
243          continue;
244 
245       Instruction* pred_branch = pred->instructions.back().get();
246       /* The branch needs to be exec zero only, otherwise we corrupt exec. */
247       if (!pred_branch->isBranch() || pred_branch->opcode != aco_opcode::p_cbranch_z ||
248           pred_branch->operands[0].physReg() != exec)
249          return;
250    }
251 
252    /* merge block: copy to exec, logical_start, logical_end, branch */
253    if (merge->instructions.size() != 4 || !is_empty_block(merge, true))
254       return;
255 
256    aco_ptr<Instruction>& execwrite = merge->instructions[0];
257    if (!is_simple_copy(execwrite.get()) || execwrite->definitions[0].physReg() != exec)
258       return;
259 
260    const aco_opcode andn2 =
261       ctx.program->lane_mask == s2 ? aco_opcode::s_andn2_b64 : aco_opcode::s_andn2_b32;
262    const aco_opcode andn2_wrexec = ctx.program->lane_mask == s2 ? aco_opcode::s_andn2_wrexec_b64
263                                                                 : aco_opcode::s_andn2_wrexec_b32;
264 
265    auto execsrc_it = block->instructions.end() - 2;
266    if ((*execsrc_it)->opcode != andn2 ||
267        (*execsrc_it)->definitions[0].physReg() != execwrite->operands[0].physReg() ||
268        (*execsrc_it)->operands[0].physReg() != execwrite->operands[0].physReg() ||
269        (*execsrc_it)->operands[1].physReg() != exec)
270       return;
271 
272    /* Move s_andn2 to the merge block. */
273    merge->instructions.insert(merge->instructions.begin(), std::move(*execsrc_it));
274    block->instructions.erase(execsrc_it);
275 
276    branch->target[0] = merge->linear_succs[0];
277    branch->target[1] = loopexit->index;
278    branch->opcode = aco_opcode::p_cbranch_nz;
279 
280    merge->instructions.back()->branch().target[0] = merge->index;
281    std::swap(merge->instructions.back(), block->instructions.back());
282 
283    block->linear_succs.clear();
284    block->linear_succs.push_back(merge->index);
285    merge->linear_succs.push_back(loopexit->index);
286    std::swap(merge->linear_succs[0], merge->linear_succs[1]);
287    ctx.blocks_incoming_exec_used[merge->index] = true;
288 
289    std::replace(loopexit->linear_preds.begin(), loopexit->linear_preds.end(), block->index,
290                 merge->index);
291 
292    if (ctx.program->gfx_level < GFX9)
293       return;
294 
295    /* Combine s_andn2 and copy to exec to s_andn2_wrexec. */
296    Instruction* r_exec = merge->instructions[0].get();
297    Instruction* wr_exec = create_instruction(andn2_wrexec, Format::SOP1, 2, 3);
298    wr_exec->operands[0] = r_exec->operands[0];
299    wr_exec->operands[1] = r_exec->operands[1];
300    wr_exec->definitions[0] = r_exec->definitions[0];
301    wr_exec->definitions[1] = r_exec->definitions[1];
302    wr_exec->definitions[2] = Definition(exec, ctx.program->lane_mask);
303 
304    merge->instructions.erase(merge->instructions.begin());
305    merge->instructions[0].reset(wr_exec);
306 }
307 
308 void
eliminate_useless_exec_writes_in_block(jump_threading_ctx & ctx,Block & block)309 eliminate_useless_exec_writes_in_block(jump_threading_ctx& ctx, Block& block)
310 {
311    /* Check if any successor needs the outgoing exec mask from the current block. */
312 
313    bool exec_write_used;
314    if (block.kind & block_kind_end_with_regs) {
315       /* Last block of a program with succeed shader part should respect final exec write. */
316       exec_write_used = true;
317    } else {
318       /* blocks_incoming_exec_used is initialized to true, so this is correct even for loops. */
319       exec_write_used =
320          std::any_of(block.linear_succs.begin(), block.linear_succs.end(),
321                      [&ctx](int succ_idx) { return ctx.blocks_incoming_exec_used[succ_idx]; });
322    }
323 
324    /* Go through all instructions and eliminate useless exec writes. */
325 
326    for (int i = block.instructions.size() - 1; i >= 0; --i) {
327       aco_ptr<Instruction>& instr = block.instructions[i];
328 
329       /* We already take information from phis into account before the loop, so let's just break on
330        * phis. */
331       if (instr->opcode == aco_opcode::p_linear_phi || instr->opcode == aco_opcode::p_phi)
332          break;
333 
334       /* See if the current instruction needs or writes exec. */
335       bool needs_exec = needs_exec_mask(instr.get());
336       bool writes_exec = instr->writes_exec();
337 
338       /* See if we found an unused exec write. */
339       if (writes_exec && !exec_write_used) {
340          /* Don't eliminate an instruction that writes registers other than exec and scc.
341           * It is possible that this is eg. an s_and_saveexec and the saved value is
342           * used by a later branch.
343           */
344          bool writes_other = std::any_of(instr->definitions.begin(), instr->definitions.end(),
345                                          [](const Definition& def) -> bool
346                                          { return def.physReg() != exec && def.physReg() != scc; });
347          if (!writes_other) {
348             instr.reset();
349             continue;
350          }
351       }
352 
353       /* For a newly encountered exec write, clear the used flag. */
354       if (writes_exec)
355          exec_write_used = false;
356 
357       /* If the current instruction needs exec, mark it as used. */
358       exec_write_used |= needs_exec;
359    }
360 
361    /* Remember if the current block needs an incoming exec mask from its predecessors. */
362    ctx.blocks_incoming_exec_used[block.index] = exec_write_used;
363 
364    /* Cleanup: remove deleted instructions from the vector. */
365    auto new_end = std::remove(block.instructions.begin(), block.instructions.end(), nullptr);
366    block.instructions.resize(new_end - block.instructions.begin());
367 }
368 
369 } /* end namespace */
370 
371 void
jump_threading(Program * program)372 jump_threading(Program* program)
373 {
374    jump_threading_ctx ctx(program);
375 
376    for (int i = program->blocks.size() - 1; i >= 0; i--) {
377       Block* block = &program->blocks[i];
378       eliminate_useless_exec_writes_in_block(ctx, *block);
379 
380       if (block->kind & block_kind_break)
381          try_merge_break_with_continue(ctx, block);
382 
383       if (block->kind & block_kind_invert) {
384          try_remove_invert_block(ctx, block);
385          continue;
386       }
387 
388       if (block->linear_succs.size() > 1)
389          continue;
390 
391       if (block->kind & block_kind_merge || block->kind & block_kind_loop_exit)
392          try_remove_merge_block(ctx, block);
393 
394       if (block->linear_preds.size() == 1)
395          try_remove_simple_block(ctx, block);
396    }
397 }
398 } // namespace aco
399