xref: /aosp_15_r20/external/mesa3d/src/compiler/nir/nir_lower_clip.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2015 Red Hat
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  *    Rob Clark <[email protected]>
25  */
26 
27 #include "nir.h"
28 #include "nir_builder.h"
29 
30 #define MAX_CLIP_PLANES 8
31 
32 /* Generates the lowering code for user-clip-planes, generating CLIPDIST
33  * from UCP[n] + CLIPVERTEX or POSITION.  Additionally, an optional pass
34  * for fragment shaders to insert conditional kills based on the inter-
35  * polated CLIPDIST
36  *
37  * NOTE: should be run after nir_lower_outputs_to_temporaries() (or at
38  * least in scenarios where you can count on each output written once
39  * and only once).
40  */
41 
42 static nir_variable *
create_clipdist_var(nir_shader * shader,bool output,gl_varying_slot slot,unsigned array_size)43 create_clipdist_var(nir_shader *shader,
44                     bool output, gl_varying_slot slot, unsigned array_size)
45 {
46    nir_variable *var = rzalloc(shader, nir_variable);
47 
48    if (output) {
49       var->data.driver_location = shader->num_outputs;
50       var->data.mode = nir_var_shader_out;
51       shader->num_outputs += MAX2(1, DIV_ROUND_UP(array_size, 4));
52    } else {
53       var->data.driver_location = shader->num_inputs;
54       var->data.mode = nir_var_shader_in;
55       shader->num_inputs += MAX2(1, DIV_ROUND_UP(array_size, 4));
56    }
57    var->name = ralloc_asprintf(var, "clipdist_%d", slot - VARYING_SLOT_CLIP_DIST0);
58    var->data.index = 0;
59    var->data.location = slot;
60 
61    if (array_size > 0) {
62       var->type = glsl_array_type(glsl_float_type(), array_size,
63                                   sizeof(float));
64       var->data.compact = 1;
65    } else
66       var->type = glsl_vec4_type();
67 
68    nir_shader_add_variable(shader, var);
69    return var;
70 }
71 
72 static void
create_clipdist_vars(nir_shader * shader,nir_variable ** io_vars,unsigned ucp_enables,bool output,bool use_clipdist_array)73 create_clipdist_vars(nir_shader *shader, nir_variable **io_vars,
74                      unsigned ucp_enables, bool output,
75                      bool use_clipdist_array)
76 {
77    shader->info.clip_distance_array_size = util_last_bit(ucp_enables);
78    if (shader->info.io_lowered)
79       return;
80    if (use_clipdist_array) {
81       io_vars[0] =
82          create_clipdist_var(shader, output,
83                              VARYING_SLOT_CLIP_DIST0,
84                              shader->info.clip_distance_array_size);
85    } else {
86       if (ucp_enables & 0x0f)
87          io_vars[0] =
88             create_clipdist_var(shader, output,
89                                 VARYING_SLOT_CLIP_DIST0, 0);
90       if (ucp_enables & 0xf0)
91          io_vars[1] =
92             create_clipdist_var(shader, output,
93                                 VARYING_SLOT_CLIP_DIST1, 0);
94    }
95 }
96 
97 static void
store_clipdist_output(nir_builder * b,nir_variable * out,int location,int location_offset,nir_def ** val,bool use_clipdist_array)98 store_clipdist_output(nir_builder *b, nir_variable *out, int location, int location_offset,
99                       nir_def **val, bool use_clipdist_array)
100 {
101    unsigned num_slots = b->shader->info.clip_distance_array_size;
102    nir_io_semantics semantics = {
103       .location = location,
104       .num_slots = num_slots,
105    };
106 
107    if (location == VARYING_SLOT_CLIP_DIST1 || location_offset)
108       num_slots -= 4;
109    else
110       num_slots = MIN2(num_slots, 4);
111    for (unsigned i = 0; i < num_slots; i++) {
112       nir_store_output(b,
113                        val[i] ? val[i] : nir_imm_zero(b, 1, 32),
114                        nir_imm_int(b, location_offset),
115                        .src_type = nir_type_float32,
116                        .write_mask = 0x1,
117                        .component = i,
118                        .io_semantics = semantics,
119                        .base = out ? out->data.driver_location : 0);
120    }
121 }
122 
123 static void
load_clipdist_input(nir_builder * b,nir_variable * in,int location_offset,nir_def ** val)124 load_clipdist_input(nir_builder *b, nir_variable *in, int location_offset,
125                     nir_def **val)
126 {
127    nir_io_semantics semantics = {
128       .location = in->data.location,
129       .num_slots = 1,
130    };
131 
132    nir_def *load;
133    if (b->shader->options->use_interpolated_input_intrinsics) {
134       /* TODO: use sample when per-sample shading? */
135       nir_def *barycentric = nir_load_barycentric(
136          b, nir_intrinsic_load_barycentric_pixel, INTERP_MODE_NONE);
137       load = nir_load_interpolated_input(
138          b, 4, 32, barycentric, nir_imm_int(b, location_offset),
139          .base = in->data.driver_location,
140          .dest_type = nir_type_float32,
141          .io_semantics = semantics);
142 
143    } else {
144       load = nir_load_input(b, 4, 32, nir_imm_int(b, location_offset),
145                             .base = in->data.driver_location,
146                             .dest_type = nir_type_float32,
147                             .io_semantics = semantics);
148    }
149 
150    val[0] = nir_channel(b, load, 0);
151    val[1] = nir_channel(b, load, 1);
152    val[2] = nir_channel(b, load, 2);
153    val[3] = nir_channel(b, load, 3);
154 }
155 
156 /* TODO: maybe this would be a useful helper?
157  * NOTE: assumes each output is written exactly once (and unconditionally)
158  * so if needed nir_lower_outputs_to_temporaries()
159  */
160 static nir_def *
find_output(nir_builder * b,unsigned location)161 find_output(nir_builder *b, unsigned location)
162 {
163    nir_def *def = NULL;
164    nir_def *components[4] = {NULL};
165    nir_instr *first = NULL;
166    unsigned found = 0;
167    nir_foreach_function_impl(impl, b->shader) {
168       nir_foreach_block_reverse(block, impl) {
169          nir_def *new_def = NULL;
170          nir_foreach_instr_reverse(instr, block) {
171             if (instr->type != nir_instr_type_intrinsic)
172                continue;
173             nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
174             if ((intr->intrinsic == nir_intrinsic_store_output ||
175                intr->intrinsic == nir_intrinsic_store_per_vertex_output ||
176                intr->intrinsic == nir_intrinsic_store_per_primitive_output) &&
177                nir_intrinsic_io_semantics(intr).location == location) {
178                assert(nir_src_is_const(*nir_get_io_offset_src(intr)));
179 
180                int wrmask = nir_intrinsic_write_mask(intr);
181                if (intr->num_components == 4 && wrmask == 0xf) {
182                   new_def = intr->src[0].ssa;
183                } else {
184                   int c = nir_intrinsic_component(intr);
185                   assert(intr->num_components == 1 && wrmask == 0x1);
186                   assert(!components[c]);
187                   components[c] = intr->src[0].ssa;
188                   if (!first)
189                      first = &intr->instr;
190                   found++;
191                }
192             }
193          }
194          assert(!(new_def && def));
195          if (!def)
196             def = new_def;
197 #if !MESA_DEBUG
198          /* for debug builds, scan entire shader to assert
199           * if output is written multiple times.  For release
200           * builds just assume all is well and bail when we
201           * find first:
202           */
203          if (def || found == 4)
204             break;
205 #endif
206       }
207    }
208    assert(def || found == 4);
209    if (found) {
210       b->cursor = nir_after_instr(first);
211       def = nir_vec(b, components, 4);
212    }
213 
214    return def;
215 }
216 
217 static bool
find_clipvertex_and_position_outputs(nir_shader * shader,nir_variable ** clipvertex,nir_variable ** position)218 find_clipvertex_and_position_outputs(nir_shader *shader,
219                                      nir_variable **clipvertex,
220                                      nir_variable **position)
221 {
222    if (shader->info.io_lowered) {
223       if (shader->info.outputs_written & (VARYING_BIT_CLIP_DIST0 | VARYING_BIT_CLIP_DIST1))
224          return false;
225       if (shader->info.outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX))
226          return true;
227       return false;
228    }
229    nir_foreach_shader_out_variable(var, shader) {
230       switch (var->data.location) {
231       case VARYING_SLOT_POS:
232          *position = var;
233          break;
234       case VARYING_SLOT_CLIP_VERTEX:
235          *clipvertex = var;
236          break;
237       case VARYING_SLOT_CLIP_DIST0:
238       case VARYING_SLOT_CLIP_DIST1:
239          /* if shader is already writing CLIPDIST, then
240           * there should be no user-clip-planes to deal
241           * with.
242           *
243           * We assume nir_remove_dead_variables has removed the clipdist
244           * variables if they're not written.
245           */
246          return false;
247       }
248    }
249 
250    return *clipvertex || *position;
251 }
252 
253 static nir_def *
get_ucp(nir_builder * b,int plane,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])254 get_ucp(nir_builder *b, int plane,
255         const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
256 {
257    if (clipplane_state_tokens) {
258       char tmp[100];
259       snprintf(tmp, ARRAY_SIZE(tmp), "gl_ClipPlane%dMESA", plane);
260       nir_variable *var = nir_state_variable_create(b->shader,
261                                                     glsl_vec4_type(),
262                                                     tmp, clipplane_state_tokens[plane]);
263       return nir_load_var(b, var);
264    } else
265       return nir_load_user_clip_plane(b, plane);
266 }
267 
268 static uint64_t
update_mask(uint32_t ucp_enables)269 update_mask(uint32_t ucp_enables)
270 {
271    uint64_t mask = 0;
272 
273    if (ucp_enables & 0x0f)
274       mask |= VARYING_BIT_CLIP_DIST0;
275    if (ucp_enables & 0xf0)
276       mask |= VARYING_BIT_CLIP_DIST1;
277 
278    return mask;
279 }
280 
281 static void
lower_clip_outputs(nir_builder * b,nir_variable * position,nir_variable * clipvertex,nir_variable ** out,unsigned ucp_enables,bool use_vars,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])282 lower_clip_outputs(nir_builder *b, nir_variable *position,
283                    nir_variable *clipvertex, nir_variable **out,
284                    unsigned ucp_enables, bool use_vars,
285                    bool use_clipdist_array,
286                    const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
287 {
288    nir_def *clipdist[MAX_CLIP_PLANES] = {NULL};
289    nir_def *cv;
290 
291    if (use_vars) {
292       cv = nir_load_var(b, clipvertex ? clipvertex : position);
293 
294       if (clipvertex) {
295          clipvertex->data.mode = nir_var_shader_temp;
296          nir_fixup_deref_modes(b->shader);
297       }
298    } else {
299       if (b->shader->info.outputs_written & VARYING_BIT_CLIP_VERTEX)
300          cv = find_output(b, VARYING_SLOT_CLIP_VERTEX);
301       else {
302          cv = find_output(b, VARYING_SLOT_POS);
303       }
304    }
305 
306    for (int plane = 0; plane < MAX_CLIP_PLANES; plane++) {
307       if (ucp_enables & (1 << plane)) {
308          nir_def *ucp = get_ucp(b, plane, clipplane_state_tokens);
309 
310          /* calculate clipdist[plane] - dot(ucp, cv): */
311          clipdist[plane] = nir_fdot(b, ucp, cv);
312       } else {
313          /* 0.0 == don't-clip == disabled: */
314          clipdist[plane] = nir_imm_float(b, 0.0);
315       }
316       if (use_clipdist_array && use_vars && plane < util_last_bit(ucp_enables)) {
317          nir_deref_instr *deref;
318          deref = nir_build_deref_array_imm(b,
319                                            nir_build_deref_var(b, out[0]),
320                                            plane);
321          nir_store_deref(b, deref, clipdist[plane], 1);
322       }
323    }
324 
325    if (!use_clipdist_array || !use_vars) {
326       if (use_vars) {
327          if (ucp_enables & 0x0f)
328             nir_store_var(b, out[0], nir_vec(b, clipdist, 4), 0xf);
329          if (ucp_enables & 0xf0)
330             nir_store_var(b, out[1], nir_vec(b, &clipdist[4], 4), 0xf);
331       } else if (use_clipdist_array) {
332          /* always emit first half of array */
333 
334          store_clipdist_output(b, out[0], VARYING_SLOT_CLIP_DIST0, 0, &clipdist[0], use_clipdist_array);
335          if (ucp_enables & 0xf0)
336             store_clipdist_output(b, out[0], VARYING_SLOT_CLIP_DIST0, 1, &clipdist[4], use_clipdist_array);
337       } else {
338          if (ucp_enables & 0x0f)
339             store_clipdist_output(b, out[0], VARYING_SLOT_CLIP_DIST0, 0, &clipdist[0], use_clipdist_array);
340          if (ucp_enables & 0xf0)
341             store_clipdist_output(b, out[1], VARYING_SLOT_CLIP_DIST1, 0, &clipdist[4], use_clipdist_array);
342       }
343       b->shader->info.outputs_written |= update_mask(ucp_enables);
344    }
345 }
346 
347 /*
348  * VS lowering
349  */
350 
351 /* ucp_enables is bitmask of enabled ucps.  Actual ucp values are
352  * passed in to shader via user_clip_plane system-values
353  *
354  * If use_vars is true, the pass will use variable loads and stores instead
355  * of working with store_output intrinsics.
356  *
357  * If use_clipdist_array is true, the pass will use compact arrays for the
358  * clipdist output instead of two vec4s.
359  */
360 bool
nir_lower_clip_vs(nir_shader * shader,unsigned ucp_enables,bool use_vars,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])361 nir_lower_clip_vs(nir_shader *shader, unsigned ucp_enables, bool use_vars,
362                   bool use_clipdist_array,
363                   const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
364 {
365    nir_function_impl *impl = nir_shader_get_entrypoint(shader);
366    nir_builder b;
367    nir_variable *position = NULL;
368    nir_variable *clipvertex = NULL;
369    nir_variable *out[2] = { NULL };
370 
371    if (!ucp_enables)
372       return false;
373 
374    if (shader->info.io_lowered)
375       use_vars = false;
376 
377    b = nir_builder_create(impl);
378 
379    /* NIR should ensure that, even in case of loops/if-else, there
380     * should be only a single predecessor block to end_block, which
381     * makes the perfect place to insert the clipdist calculations.
382     *
383     * NOTE: in case of early returns, these would have to be lowered
384     * to jumps to end_block predecessor in a previous pass.  Not sure
385     * if there is a good way to sanity check this, but for now the
386     * users of this pass don't support sub-routines.
387     */
388    assert(impl->end_block->predecessors->entries == 1);
389    b.cursor = nir_after_impl(impl);
390 
391    /* find clipvertex/position outputs */
392    if (!find_clipvertex_and_position_outputs(shader, &clipvertex, &position))
393       return false;
394 
395    /* insert CLIPDIST outputs */
396    create_clipdist_vars(shader, out, ucp_enables, true,
397                         use_clipdist_array);
398 
399    lower_clip_outputs(&b, position, clipvertex, out, ucp_enables, use_vars,
400                       use_clipdist_array, clipplane_state_tokens);
401 
402    nir_metadata_preserve(impl, nir_metadata_dominance);
403 
404    return true;
405 }
406 
407 static void
lower_clip_in_gs_block(nir_builder * b,nir_block * block,nir_variable * position,nir_variable * clipvertex,nir_variable ** out,unsigned ucp_enables,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])408 lower_clip_in_gs_block(nir_builder *b, nir_block *block, nir_variable *position,
409                        nir_variable *clipvertex, nir_variable **out,
410                        unsigned ucp_enables, bool use_clipdist_array,
411                        const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
412 {
413    nir_foreach_instr_safe(instr, block) {
414       if (instr->type != nir_instr_type_intrinsic)
415          continue;
416 
417       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
418       switch (intrin->intrinsic) {
419       case nir_intrinsic_emit_vertex_with_counter:
420       case nir_intrinsic_emit_vertex:
421          b->cursor = nir_before_instr(instr);
422          lower_clip_outputs(b, position, clipvertex, out, ucp_enables, !b->shader->info.io_lowered,
423                             use_clipdist_array, clipplane_state_tokens);
424          break;
425       default:
426          /* not interesting; skip this */
427          break;
428       }
429    }
430 }
431 
432 /*
433  * GS lowering
434  */
435 
436 bool
nir_lower_clip_gs(nir_shader * shader,unsigned ucp_enables,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])437 nir_lower_clip_gs(nir_shader *shader, unsigned ucp_enables,
438                   bool use_clipdist_array,
439                   const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
440 {
441    nir_function_impl *impl = nir_shader_get_entrypoint(shader);
442    nir_builder b;
443    nir_variable *position = NULL;
444    nir_variable *clipvertex = NULL;
445    nir_variable *out[2] = { NULL };
446 
447    if (!ucp_enables)
448       return false;
449 
450    /* find clipvertex/position outputs */
451    if (!find_clipvertex_and_position_outputs(shader, &clipvertex, &position))
452       return false;
453 
454    /* insert CLIPDIST outputs */
455    create_clipdist_vars(shader, out, ucp_enables, true,
456                         use_clipdist_array);
457 
458    b = nir_builder_create(impl);
459 
460    nir_foreach_block(block, impl)
461       lower_clip_in_gs_block(&b, block, position, clipvertex, out,
462                              ucp_enables, use_clipdist_array,
463                              clipplane_state_tokens);
464 
465    nir_metadata_preserve(impl, nir_metadata_dominance);
466 
467    return true;
468 }
469 
470 /*
471  * FS lowering
472  */
473 
474 static void
lower_clip_fs(nir_function_impl * impl,unsigned ucp_enables,nir_variable ** in,bool use_clipdist_array)475 lower_clip_fs(nir_function_impl *impl, unsigned ucp_enables,
476               nir_variable **in, bool use_clipdist_array)
477 {
478    nir_def *clipdist[MAX_CLIP_PLANES];
479    nir_builder b = nir_builder_at(nir_before_impl(impl));
480 
481    if (!use_clipdist_array) {
482       if (ucp_enables & 0x0f)
483          load_clipdist_input(&b, in[0], 0, &clipdist[0]);
484       if (ucp_enables & 0xf0)
485          load_clipdist_input(&b, in[1], 0, &clipdist[4]);
486    } else {
487       if (ucp_enables & 0x0f)
488          load_clipdist_input(&b, in[0], 0, &clipdist[0]);
489       if (ucp_enables & 0xf0)
490          load_clipdist_input(&b, in[0], 1, &clipdist[4]);
491    }
492    b.shader->info.inputs_read |= update_mask(ucp_enables);
493 
494    nir_def *cond = NULL;
495 
496    for (int plane = 0; plane < MAX_CLIP_PLANES; plane++) {
497       if (ucp_enables & (1 << plane)) {
498          nir_def *this_cond =
499             nir_flt_imm(&b, clipdist[plane], 0.0);
500 
501          cond = cond ? nir_ior(&b, cond, this_cond) : this_cond;
502       }
503    }
504 
505    if (cond != NULL) {
506       nir_discard_if(&b, cond);
507       b.shader->info.fs.uses_discard = true;
508    }
509 
510    nir_metadata_preserve(impl, nir_metadata_dominance);
511 }
512 
513 static bool
fs_has_clip_dist_input_var(nir_shader * shader,nir_variable ** io_vars,unsigned * ucp_enables)514 fs_has_clip_dist_input_var(nir_shader *shader, nir_variable **io_vars,
515                            unsigned *ucp_enables)
516 {
517    assert(shader->info.stage == MESA_SHADER_FRAGMENT);
518    nir_foreach_shader_in_variable(var, shader) {
519       switch (var->data.location) {
520       case VARYING_SLOT_CLIP_DIST0:
521          assert(var->data.compact);
522          io_vars[0] = var;
523          *ucp_enables &= (1 << glsl_get_length(var->type)) - 1;
524          return true;
525       default:
526          break;
527       }
528    }
529    return false;
530 }
531 
532 /* insert conditional kill based on interpolated CLIPDIST
533  */
534 bool
nir_lower_clip_fs(nir_shader * shader,unsigned ucp_enables,bool use_clipdist_array)535 nir_lower_clip_fs(nir_shader *shader, unsigned ucp_enables,
536                   bool use_clipdist_array)
537 {
538    nir_variable *in[2] = { 0 };
539 
540    if (!ucp_enables)
541       return false;
542 
543    /* this is probably broken until https://gitlab.freedesktop.org/mesa/mesa/-/issues/10826 is fixed */
544    assert(!shader->info.io_lowered);
545 
546    /* No hard reason to require use_clipdist_arr to work with
547     * frag-shader-based gl_ClipDistance, except that the only user that does
548     * not enable this does not support GL 3.0 (or EXT_clip_cull_distance).
549     */
550    if (!fs_has_clip_dist_input_var(shader, in, &ucp_enables))
551       create_clipdist_vars(shader, in, ucp_enables, false, use_clipdist_array);
552    else
553       assert(use_clipdist_array);
554 
555    nir_foreach_function_with_impl(function, impl, shader) {
556       if (!strcmp(function->name, "main"))
557          lower_clip_fs(impl, ucp_enables, in, use_clipdist_array);
558    }
559 
560    return true;
561 }
562