• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2014 Intel 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  * Authors:
24  *    Jason Ekstrand (jason@jlekstrand.net)
25  *
26  */
27 
28 #include "nir.h"
29 #include "nir/nir_builder.h"
30 #include "nir_control_flow.h"
31 #include "nir_search_helpers.h"
32 
33 /*
34  * Implements a small peephole optimization that looks for
35  *
36  * if (cond) {
37  *    <then SSA defs>
38  * } else {
39  *    <else SSA defs>
40  * }
41  * phi
42  * ...
43  * phi
44  *
45  * and replaces it with:
46  *
47  * <then SSA defs>
48  * <else SSA defs>
49  * bcsel
50  * ...
51  * bcsel
52  *
53  * where the SSA defs are ALU operations or other cheap instructions (not
54  * texturing, for example).
55  *
56  * If the number of ALU operations in the branches is greater than the limit
57  * parameter, then the optimization is skipped.  In limit=0 mode, the SSA defs
58  * must only be MOVs which we expect to get copy-propagated away once they're
59  * out of the inner blocks.
60  */
61 
62 static bool
block_check_for_allowed_instrs(nir_block * block,unsigned * count,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)63 block_check_for_allowed_instrs(nir_block *block, unsigned *count,
64                                unsigned limit, bool indirect_load_ok,
65                                bool expensive_alu_ok)
66 {
67    bool alu_ok = limit != 0;
68 
69    /* Used on non-control-flow HW to flatten all IFs. */
70    if (limit == ~0) {
71       nir_foreach_instr(instr, block) {
72          switch (instr->type) {
73          case nir_instr_type_alu:
74          case nir_instr_type_deref:
75          case nir_instr_type_load_const:
76          case nir_instr_type_phi:
77          case nir_instr_type_ssa_undef:
78          case nir_instr_type_tex:
79             break;
80 
81          case nir_instr_type_intrinsic:
82             if (!nir_intrinsic_can_reorder(nir_instr_as_intrinsic(instr)))
83                return false;
84             break;
85 
86          case nir_instr_type_call:
87          case nir_instr_type_jump:
88          case nir_instr_type_parallel_copy:
89             return false;
90          }
91       }
92       return true;
93    }
94 
95    nir_foreach_instr(instr, block) {
96       switch (instr->type) {
97       case nir_instr_type_intrinsic: {
98          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
99 
100          switch (intrin->intrinsic) {
101          case nir_intrinsic_load_deref: {
102             nir_deref_instr *const deref = nir_src_as_deref(intrin->src[0]);
103 
104             switch (deref->modes) {
105             case nir_var_shader_in:
106             case nir_var_uniform:
107                /* Don't try to remove flow control around an indirect load
108                 * because that flow control may be trying to avoid invalid
109                 * loads.
110                 */
111                if (!indirect_load_ok && nir_deref_instr_has_indirect(deref))
112                   return false;
113 
114                break;
115 
116             default:
117                return false;
118             }
119             break;
120          }
121 
122          case nir_intrinsic_load_uniform:
123          case nir_intrinsic_load_helper_invocation:
124          case nir_intrinsic_is_helper_invocation:
125          case nir_intrinsic_load_front_face:
126          case nir_intrinsic_load_view_index:
127          case nir_intrinsic_load_layer_id:
128          case nir_intrinsic_load_frag_coord:
129          case nir_intrinsic_load_sample_pos:
130          case nir_intrinsic_load_sample_id:
131          case nir_intrinsic_load_sample_mask_in:
132          case nir_intrinsic_load_vertex_id_zero_base:
133          case nir_intrinsic_load_first_vertex:
134          case nir_intrinsic_load_base_instance:
135          case nir_intrinsic_load_instance_id:
136          case nir_intrinsic_load_draw_id:
137          case nir_intrinsic_load_num_workgroups:
138          case nir_intrinsic_load_workgroup_id:
139          case nir_intrinsic_load_local_invocation_id:
140          case nir_intrinsic_load_local_invocation_index:
141          case nir_intrinsic_load_subgroup_id:
142          case nir_intrinsic_load_subgroup_invocation:
143          case nir_intrinsic_load_num_subgroups:
144          case nir_intrinsic_load_frag_shading_rate:
145          case nir_intrinsic_is_sparse_texels_resident:
146          case nir_intrinsic_sparse_residency_code_and:
147             if (!alu_ok)
148                return false;
149             break;
150 
151          default:
152             return false;
153          }
154 
155          break;
156       }
157 
158       case nir_instr_type_deref:
159       case nir_instr_type_load_const:
160       case nir_instr_type_ssa_undef:
161          break;
162 
163       case nir_instr_type_alu: {
164          nir_alu_instr *mov = nir_instr_as_alu(instr);
165          bool movelike = false;
166 
167          switch (mov->op) {
168          case nir_op_mov:
169          case nir_op_fneg:
170          case nir_op_ineg:
171          case nir_op_fabs:
172          case nir_op_iabs:
173          case nir_op_vec2:
174          case nir_op_vec3:
175          case nir_op_vec4:
176          case nir_op_vec5:
177          case nir_op_vec8:
178          case nir_op_vec16:
179             movelike = true;
180             break;
181 
182          case nir_op_fcos:
183          case nir_op_fdiv:
184          case nir_op_fexp2:
185          case nir_op_flog2:
186          case nir_op_fmod:
187          case nir_op_fpow:
188          case nir_op_frcp:
189          case nir_op_frem:
190          case nir_op_frsq:
191          case nir_op_fsin:
192          case nir_op_idiv:
193          case nir_op_irem:
194          case nir_op_udiv:
195             if (!alu_ok || !expensive_alu_ok)
196                return false;
197 
198             break;
199 
200          default:
201             if (!alu_ok) {
202                /* It must be a move-like operation. */
203                return false;
204             }
205             break;
206          }
207 
208          /* It must be SSA */
209          if (!mov->dest.dest.is_ssa)
210             return false;
211 
212          if (alu_ok) {
213             /* If the ALU operation is an fsat or a move-like operation, do
214              * not count it.  The expectation is that it will eventually be
215              * merged as a destination modifier or source modifier on some
216              * other instruction.
217              */
218             if (mov->op != nir_op_fsat && !movelike)
219                (*count)++;
220          } else {
221             /* Can't handle saturate */
222             if (mov->dest.saturate)
223                return false;
224 
225             /* It cannot have any if-uses */
226             if (!list_is_empty(&mov->dest.dest.ssa.if_uses))
227                return false;
228 
229             /* The only uses of this definition must be phis in the successor */
230             nir_foreach_use(use, &mov->dest.dest.ssa) {
231                if (use->parent_instr->type != nir_instr_type_phi ||
232                    use->parent_instr->block != block->successors[0])
233                   return false;
234             }
235          }
236          break;
237       }
238 
239       default:
240          return false;
241       }
242    }
243 
244    return true;
245 }
246 
247 /**
248  * Try to collapse nested ifs:
249  * This optimization turns
250  *
251  * if (cond1) {
252  *   <allowed instruction>
253  *   if (cond2) {
254  *     <any code>
255  *   } else {
256  *   }
257  * } else {
258  * }
259  *
260  * into
261  *
262  * <allowed instruction>
263  * if (cond1 && cond2) {
264  *   <any code>
265  * } else {
266  * }
267  *
268  */
269 static bool
nir_opt_collapse_if(nir_if * if_stmt,nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)270 nir_opt_collapse_if(nir_if *if_stmt, nir_shader *shader, unsigned limit,
271                     bool indirect_load_ok, bool expensive_alu_ok)
272 {
273    /* the if has to be nested */
274    if (if_stmt->cf_node.parent->type != nir_cf_node_if)
275       return false;
276 
277    nir_if *parent_if = nir_cf_node_as_if(if_stmt->cf_node.parent);
278    if (parent_if->control == nir_selection_control_dont_flatten)
279       return false;
280 
281    /* check if the else block is empty */
282    if (!nir_cf_list_is_empty_block(&if_stmt->else_list))
283       return false;
284 
285    /* this opt doesn't make much sense if the branch is empty */
286    if (nir_cf_list_is_empty_block(&if_stmt->then_list))
287       return false;
288 
289    /* the nested if has to be the only cf_node:
290     * i.e. <block> <if_stmt> <block> */
291    if (exec_list_length(&parent_if->then_list) != 3)
292       return false;
293 
294    /* check if the else block of the parent if is empty */
295    if (!nir_cf_list_is_empty_block(&parent_if->else_list))
296       return false;
297 
298    /* check if the block after the nested if is empty except for phis */
299    nir_block *last = nir_if_last_then_block(parent_if);
300    nir_instr *last_instr = nir_block_last_instr(last);
301    if (last_instr && last_instr->type != nir_instr_type_phi)
302       return false;
303 
304    /* check if all outer phis become trivial after merging the ifs */
305    nir_foreach_instr(instr, last) {
306       if (parent_if->control == nir_selection_control_flatten)
307          break;
308 
309       nir_phi_instr *phi = nir_instr_as_phi(instr);
310       nir_phi_src *else_src =
311          nir_phi_get_src_from_block(phi, nir_if_first_else_block(if_stmt));
312 
313       nir_foreach_use (src, &phi->dest.ssa) {
314          assert(src->parent_instr->type == nir_instr_type_phi);
315          nir_phi_src *phi_src =
316             nir_phi_get_src_from_block(nir_instr_as_phi(src->parent_instr),
317                                        nir_if_first_else_block(parent_if));
318          if (phi_src->src.ssa != else_src->src.ssa)
319             return false;
320       }
321    }
322 
323    if (parent_if->control == nir_selection_control_flatten) {
324       /* Override driver defaults */
325       indirect_load_ok = true;
326       expensive_alu_ok = true;
327    }
328 
329    /* check if the block before the nested if matches the requirements */
330    nir_block *first = nir_if_first_then_block(parent_if);
331    unsigned count = 0;
332    if (!block_check_for_allowed_instrs(first, &count, limit != 0,
333                                        indirect_load_ok, expensive_alu_ok))
334       return false;
335 
336    if (count > limit && parent_if->control != nir_selection_control_flatten)
337       return false;
338 
339    /* trivialize succeeding phis */
340    nir_foreach_instr(instr, last) {
341       nir_phi_instr *phi = nir_instr_as_phi(instr);
342       nir_phi_src *else_src =
343          nir_phi_get_src_from_block(phi, nir_if_first_else_block(if_stmt));
344       nir_foreach_use_safe(src, &phi->dest.ssa) {
345          nir_phi_src *phi_src =
346             nir_phi_get_src_from_block(nir_instr_as_phi(src->parent_instr),
347                                        nir_if_first_else_block(parent_if));
348          if (phi_src->src.ssa == else_src->src.ssa)
349             nir_instr_rewrite_src(src->parent_instr, &phi_src->src,
350                                   nir_src_for_ssa(&phi->dest.ssa));
351       }
352    }
353 
354    /* combine the conditions */
355    struct nir_builder b;
356    nir_builder_init(&b, nir_cf_node_get_function(&if_stmt->cf_node)->function->impl);
357    b.cursor = nir_before_cf_node(&if_stmt->cf_node);
358    nir_ssa_def *cond = nir_iand(&b, if_stmt->condition.ssa,
359                                 parent_if->condition.ssa);
360    nir_if_rewrite_condition(if_stmt, nir_src_for_ssa(cond));
361 
362    /* move the whole inner if before the parent if */
363    nir_cf_list tmp;
364    nir_cf_extract(&tmp, nir_before_block(first),
365                         nir_after_block(last));
366    nir_cf_reinsert(&tmp, nir_before_cf_node(&parent_if->cf_node));
367 
368    /* The now empty parent if will be cleaned up by other passes */
369    return true;
370 }
371 
372 static bool
nir_opt_peephole_select_block(nir_block * block,nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)373 nir_opt_peephole_select_block(nir_block *block, nir_shader *shader,
374                               unsigned limit, bool indirect_load_ok,
375                               bool expensive_alu_ok)
376 {
377    if (nir_cf_node_is_first(&block->cf_node))
378       return false;
379 
380    nir_cf_node *prev_node = nir_cf_node_prev(&block->cf_node);
381    if (prev_node->type != nir_cf_node_if)
382       return false;
383 
384    nir_block *prev_block = nir_cf_node_as_block(nir_cf_node_prev(prev_node));
385 
386    /* If the last instruction before this if/else block is a jump, we can't
387     * append stuff after it because it would break a bunch of assumption about
388     * control flow (nir_validate expects the successor of a return/halt jump
389     * to be the end of the function, which might not match the successor of
390     * the if/else blocks).
391     */
392    if (nir_block_ends_in_return_or_halt(prev_block))
393       return false;
394 
395    nir_if *if_stmt = nir_cf_node_as_if(prev_node);
396 
397    /* first, try to collapse the if */
398    if (nir_opt_collapse_if(if_stmt, shader, limit,
399                            indirect_load_ok, expensive_alu_ok))
400       return true;
401 
402    if (if_stmt->control == nir_selection_control_dont_flatten)
403       return false;
404 
405    nir_block *then_block = nir_if_first_then_block(if_stmt);
406    nir_block *else_block = nir_if_first_else_block(if_stmt);
407 
408    /* We can only have one block in each side ... */
409    if (nir_if_last_then_block(if_stmt) != then_block ||
410        nir_if_last_else_block(if_stmt) != else_block)
411       return false;
412 
413    if (if_stmt->control == nir_selection_control_flatten) {
414       /* Override driver defaults */
415       indirect_load_ok = true;
416       expensive_alu_ok = true;
417    }
418 
419    /* ... and those blocks must only contain "allowed" instructions. */
420    unsigned count = 0;
421    if (!block_check_for_allowed_instrs(then_block, &count, limit,
422                                        indirect_load_ok, expensive_alu_ok) ||
423        !block_check_for_allowed_instrs(else_block, &count, limit,
424                                        indirect_load_ok, expensive_alu_ok))
425       return false;
426 
427    if (count > limit && if_stmt->control != nir_selection_control_flatten)
428       return false;
429 
430    /* At this point, we know that the previous CFG node is an if-then
431     * statement containing only moves to phi nodes in this block.  We can
432     * just remove that entire CF node and replace all of the phi nodes with
433     * selects.
434     */
435 
436    /* First, we move the remaining instructions from the blocks to the
437     * block before.  We have already guaranteed that this is safe by
438     * calling block_check_for_allowed_instrs()
439     */
440    nir_foreach_instr_safe(instr, then_block) {
441       exec_node_remove(&instr->node);
442       instr->block = prev_block;
443       exec_list_push_tail(&prev_block->instr_list, &instr->node);
444    }
445 
446    nir_foreach_instr_safe(instr, else_block) {
447       exec_node_remove(&instr->node);
448       instr->block = prev_block;
449       exec_list_push_tail(&prev_block->instr_list, &instr->node);
450    }
451 
452    nir_foreach_instr_safe(instr, block) {
453       if (instr->type != nir_instr_type_phi)
454          break;
455 
456       nir_phi_instr *phi = nir_instr_as_phi(instr);
457       nir_alu_instr *sel = nir_alu_instr_create(shader, nir_op_bcsel);
458       nir_src_copy(&sel->src[0].src, &if_stmt->condition);
459       /* Splat the condition to all channels */
460       memset(sel->src[0].swizzle, 0, sizeof sel->src[0].swizzle);
461 
462       assert(exec_list_length(&phi->srcs) == 2);
463       nir_foreach_phi_src(src, phi) {
464          assert(src->pred == then_block || src->pred == else_block);
465          assert(src->src.is_ssa);
466 
467          unsigned idx = src->pred == then_block ? 1 : 2;
468          nir_src_copy(&sel->src[idx].src, &src->src);
469       }
470 
471       nir_ssa_dest_init(&sel->instr, &sel->dest.dest,
472                         phi->dest.ssa.num_components,
473                         phi->dest.ssa.bit_size, NULL);
474       sel->dest.write_mask = (1 << phi->dest.ssa.num_components) - 1;
475 
476       nir_ssa_def_rewrite_uses(&phi->dest.ssa,
477                                &sel->dest.dest.ssa);
478 
479       nir_instr_insert_before(&phi->instr, &sel->instr);
480       nir_instr_remove(&phi->instr);
481    }
482 
483    nir_cf_node_remove(&if_stmt->cf_node);
484    return true;
485 }
486 
487 static bool
nir_opt_peephole_select_impl(nir_function_impl * impl,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)488 nir_opt_peephole_select_impl(nir_function_impl *impl, unsigned limit,
489                              bool indirect_load_ok, bool expensive_alu_ok)
490 {
491    nir_shader *shader = impl->function->shader;
492    bool progress = false;
493 
494    nir_foreach_block_safe(block, impl) {
495       progress |= nir_opt_peephole_select_block(block, shader, limit,
496                                                 indirect_load_ok,
497                                                 expensive_alu_ok);
498    }
499 
500    if (progress) {
501       nir_metadata_preserve(impl, nir_metadata_none);
502    } else {
503       nir_metadata_preserve(impl, nir_metadata_all);
504    }
505 
506    return progress;
507 }
508 
509 bool
nir_opt_peephole_select(nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)510 nir_opt_peephole_select(nir_shader *shader, unsigned limit,
511                         bool indirect_load_ok, bool expensive_alu_ok)
512 {
513    bool progress = false;
514 
515    nir_foreach_function(function, shader) {
516       if (function->impl)
517          progress |= nir_opt_peephole_select_impl(function->impl, limit,
518                                                   indirect_load_ok,
519                                                   expensive_alu_ok);
520    }
521 
522    return progress;
523 }
524