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