• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 Rob Clark <robclark@freedesktop.org>
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 FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  *
23  * Authors:
24  *    Rob Clark <robclark@freedesktop.org>
25  */
26 
27 #include "util/debug.h"
28 #include "util/u_math.h"
29 
30 #include "ir3_compiler.h"
31 #include "ir3_nir.h"
32 #include "ir3_shader.h"
33 
34 static bool
ir3_nir_should_vectorize_mem(unsigned align_mul,unsigned align_offset,unsigned bit_size,unsigned num_components,nir_intrinsic_instr * low,nir_intrinsic_instr * high,void * data)35 ir3_nir_should_vectorize_mem(unsigned align_mul, unsigned align_offset,
36                              unsigned bit_size, unsigned num_components,
37                              nir_intrinsic_instr *low,
38                              nir_intrinsic_instr *high, void *data)
39 {
40    unsigned byte_size = bit_size / 8;
41 
42    if (low->intrinsic != nir_intrinsic_load_ubo) {
43       return bit_size <= 32 && align_mul >= byte_size &&
44          align_offset % byte_size == 0 &&
45          num_components <= 4;
46    }
47 
48    assert(bit_size >= 8);
49    if (bit_size != 32)
50       return false;
51 
52    int size = num_components * byte_size;
53 
54    /* Don't care about alignment past vec4. */
55    assert(util_is_power_of_two_nonzero(align_mul));
56    align_mul = MIN2(align_mul, 16);
57    align_offset &= 15;
58 
59    /* Our offset alignment should aways be at least 4 bytes */
60    if (align_mul < 4)
61       return false;
62 
63    unsigned worst_start_offset = 16 - align_mul + align_offset;
64    if (worst_start_offset + size > 16)
65       return false;
66 
67    return true;
68 }
69 
70 #define OPT(nir, pass, ...)                                                    \
71    ({                                                                          \
72       bool this_progress = false;                                              \
73       NIR_PASS(this_progress, nir, pass, ##__VA_ARGS__);                       \
74       this_progress;                                                           \
75    })
76 
77 #define OPT_V(nir, pass, ...) NIR_PASS_V(nir, pass, ##__VA_ARGS__)
78 
79 void
ir3_optimize_loop(struct ir3_compiler * compiler,nir_shader * s)80 ir3_optimize_loop(struct ir3_compiler *compiler, nir_shader *s)
81 {
82    bool progress;
83    unsigned lower_flrp = (s->options->lower_flrp16 ? 16 : 0) |
84                          (s->options->lower_flrp32 ? 32 : 0) |
85                          (s->options->lower_flrp64 ? 64 : 0);
86 
87    do {
88       progress = false;
89 
90       OPT_V(s, nir_lower_vars_to_ssa);
91       progress |= OPT(s, nir_lower_alu_to_scalar, NULL, NULL);
92       progress |= OPT(s, nir_lower_phis_to_scalar, false);
93 
94       progress |= OPT(s, nir_copy_prop);
95       progress |= OPT(s, nir_opt_deref);
96       progress |= OPT(s, nir_opt_dce);
97       progress |= OPT(s, nir_opt_cse);
98 
99       progress |= OPT(s, nir_opt_find_array_copies);
100       progress |= OPT(s, nir_opt_copy_prop_vars);
101       progress |= OPT(s, nir_opt_dead_write_vars);
102 
103       static int gcm = -1;
104       if (gcm == -1)
105          gcm = env_var_as_unsigned("GCM", 0);
106       if (gcm == 1)
107          progress |= OPT(s, nir_opt_gcm, true);
108       else if (gcm == 2)
109          progress |= OPT(s, nir_opt_gcm, false);
110       progress |= OPT(s, nir_opt_peephole_select, 16, true, true);
111       progress |= OPT(s, nir_opt_intrinsics);
112       /* NOTE: GS lowering inserts an output var with varying slot that
113        * is larger than VARYING_SLOT_MAX (ie. GS_VERTEX_FLAGS_IR3),
114        * which triggers asserts in nir_shader_gather_info().  To work
115        * around that skip lowering phi precision for GS.
116        *
117        * Calling nir_shader_gather_info() late also seems to cause
118        * problems for tess lowering, for now since we only enable
119        * fp16/int16 for frag and compute, skip phi precision lowering
120        * for other stages.
121        */
122       if ((s->info.stage == MESA_SHADER_FRAGMENT) ||
123           (s->info.stage == MESA_SHADER_COMPUTE) ||
124           (s->info.stage == MESA_SHADER_KERNEL)) {
125          progress |= OPT(s, nir_opt_phi_precision);
126       }
127       progress |= OPT(s, nir_opt_algebraic);
128       progress |= OPT(s, nir_lower_alu);
129       progress |= OPT(s, nir_lower_pack);
130       progress |= OPT(s, nir_opt_constant_folding);
131 
132       static const nir_opt_offsets_options offset_options = {
133          /* How large an offset we can encode in the instr's immediate field.
134           */
135          .uniform_max = (1 << 9) - 1,
136 
137          .shared_max = (1 << 13) - 1,
138 
139          .buffer_max = ~0,
140       };
141       progress |= OPT(s, nir_opt_offsets, &offset_options);
142 
143       nir_load_store_vectorize_options vectorize_opts = {
144          .modes = nir_var_mem_ubo | nir_var_mem_ssbo,
145          .callback = ir3_nir_should_vectorize_mem,
146          .robust_modes = compiler->robust_buffer_access2 ? nir_var_mem_ubo | nir_var_mem_ssbo: 0,
147       };
148       progress |= OPT(s, nir_opt_load_store_vectorize, &vectorize_opts);
149 
150       if (lower_flrp != 0) {
151          if (OPT(s, nir_lower_flrp, lower_flrp, false /* always_precise */)) {
152             OPT(s, nir_opt_constant_folding);
153             progress = true;
154          }
155 
156          /* Nothing should rematerialize any flrps, so we only
157           * need to do this lowering once.
158           */
159          lower_flrp = 0;
160       }
161 
162       progress |= OPT(s, nir_opt_dead_cf);
163       if (OPT(s, nir_opt_trivial_continues)) {
164          progress |= true;
165          /* If nir_opt_trivial_continues makes progress, then we need to clean
166           * things up if we want any hope of nir_opt_if or nir_opt_loop_unroll
167           * to make progress.
168           */
169          OPT(s, nir_copy_prop);
170          OPT(s, nir_opt_dce);
171       }
172       progress |= OPT(s, nir_opt_if, nir_opt_if_optimize_phi_true_false);
173       progress |= OPT(s, nir_opt_loop_unroll);
174       progress |= OPT(s, nir_lower_64bit_phis);
175       progress |= OPT(s, nir_opt_remove_phis);
176       progress |= OPT(s, nir_opt_undef);
177    } while (progress);
178 
179    OPT(s, nir_lower_var_copies);
180 }
181 
182 static bool
should_split_wrmask(const nir_instr * instr,const void * data)183 should_split_wrmask(const nir_instr *instr, const void *data)
184 {
185    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
186 
187    switch (intr->intrinsic) {
188    case nir_intrinsic_store_ssbo:
189    case nir_intrinsic_store_shared:
190    case nir_intrinsic_store_global:
191    case nir_intrinsic_store_scratch:
192       return true;
193    default:
194       return false;
195    }
196 }
197 
198 static bool
ir3_nir_lower_ssbo_size_filter(const nir_instr * instr,const void * data)199 ir3_nir_lower_ssbo_size_filter(const nir_instr *instr, const void *data)
200 {
201    return instr->type == nir_instr_type_intrinsic &&
202           nir_instr_as_intrinsic(instr)->intrinsic ==
203              nir_intrinsic_get_ssbo_size;
204 }
205 
206 static nir_ssa_def *
ir3_nir_lower_ssbo_size_instr(nir_builder * b,nir_instr * instr,void * data)207 ir3_nir_lower_ssbo_size_instr(nir_builder *b, nir_instr *instr, void *data)
208 {
209    uint8_t ssbo_size_to_bytes_shift = *(uint8_t *) data;
210    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
211    return nir_ishl(b, &intr->dest.ssa, nir_imm_int(b, ssbo_size_to_bytes_shift));
212 }
213 
214 static bool
ir3_nir_lower_ssbo_size(nir_shader * s,uint8_t ssbo_size_to_bytes_shift)215 ir3_nir_lower_ssbo_size(nir_shader *s, uint8_t ssbo_size_to_bytes_shift)
216 {
217    return nir_shader_lower_instructions(s, ir3_nir_lower_ssbo_size_filter,
218                                         ir3_nir_lower_ssbo_size_instr,
219                                         &ssbo_size_to_bytes_shift);
220 }
221 
222 void
ir3_nir_lower_io_to_temporaries(nir_shader * s)223 ir3_nir_lower_io_to_temporaries(nir_shader *s)
224 {
225    /* Outputs consumed by the VPC, VS inputs, and FS outputs are all handled
226     * by the hardware pre-loading registers at the beginning and then reading
227     * them at the end, so we can't access them indirectly except through
228     * normal register-indirect accesses, and therefore ir3 doesn't support
229     * indirect accesses on those. Other i/o is lowered in ir3_nir_lower_tess,
230     * and indirects work just fine for those. GS outputs may be consumed by
231     * VPC, but have their own lowering in ir3_nir_lower_gs() which does
232     * something similar to nir_lower_io_to_temporaries so we shouldn't need
233     * to lower them.
234     *
235     * Note: this might be a little inefficient for VS or TES outputs which are
236     * when the next stage isn't an FS, but it probably don't make sense to
237     * depend on the next stage before variant creation.
238     *
239     * TODO: for gallium, mesa/st also does some redundant lowering, including
240     * running this pass for GS inputs/outputs which we don't want but not
241     * including TES outputs or FS inputs which we do need. We should probably
242     * stop doing that once we're sure all drivers are doing their own
243     * indirect i/o lowering.
244     */
245    bool lower_input = s->info.stage == MESA_SHADER_VERTEX ||
246                       s->info.stage == MESA_SHADER_FRAGMENT;
247    bool lower_output = s->info.stage != MESA_SHADER_TESS_CTRL &&
248                        s->info.stage != MESA_SHADER_GEOMETRY;
249    if (lower_input || lower_output) {
250       NIR_PASS_V(s, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(s),
251                  lower_output, lower_input);
252 
253       /* nir_lower_io_to_temporaries() creates global variables and copy
254        * instructions which need to be cleaned up.
255        */
256       NIR_PASS_V(s, nir_split_var_copies);
257       NIR_PASS_V(s, nir_lower_var_copies);
258       NIR_PASS_V(s, nir_lower_global_vars_to_local);
259    }
260 
261    /* Regardless of the above, we need to lower indirect references to
262     * compact variables such as clip/cull distances because due to how
263     * TCS<->TES IO works we cannot handle indirect accesses that "straddle"
264     * vec4 components. nir_lower_indirect_derefs has a special case for
265     * compact variables, so it will actually lower them even though we pass
266     * in 0 modes.
267     *
268     * Using temporaries would be slightly better but
269     * nir_lower_io_to_temporaries currently doesn't support TCS i/o.
270     */
271    NIR_PASS_V(s, nir_lower_indirect_derefs, 0, UINT32_MAX);
272 }
273 
274 /**
275  * Inserts an add of 0.5 to floating point array index values in texture coordinates.
276  */
277 static bool
ir3_nir_lower_array_sampler_cb(struct nir_builder * b,nir_instr * instr,void * _data)278 ir3_nir_lower_array_sampler_cb(struct nir_builder *b, nir_instr *instr, void *_data)
279 {
280    if (instr->type != nir_instr_type_tex)
281       return false;
282 
283    nir_tex_instr *tex = nir_instr_as_tex(instr);
284    if (!tex->is_array || tex->op == nir_texop_lod)
285       return false;
286 
287    int coord_idx = nir_tex_instr_src_index(tex, nir_tex_src_coord);
288    if (coord_idx == -1 ||
289        nir_tex_instr_src_type(tex, coord_idx) != nir_type_float)
290       return false;
291 
292    b->cursor = nir_before_instr(&tex->instr);
293 
294    unsigned ncomp = tex->coord_components;
295    nir_ssa_def *src = nir_ssa_for_src(b, tex->src[coord_idx].src, ncomp);
296 
297    assume(ncomp >= 1);
298    nir_ssa_def *ai = nir_channel(b, src, ncomp - 1);
299    ai = nir_fadd(b, ai, nir_imm_floatN_t(b, 0.5, src->bit_size));
300    nir_instr_rewrite_src(&tex->instr, &tex->src[coord_idx].src,
301                          nir_src_for_ssa(nir_vector_insert_imm(b, src, ai, ncomp - 1)));
302    return true;
303 }
304 
305 static bool
ir3_nir_lower_array_sampler(nir_shader * shader)306 ir3_nir_lower_array_sampler(nir_shader *shader)
307 {
308    return nir_shader_instructions_pass(
309       shader, ir3_nir_lower_array_sampler_cb,
310       nir_metadata_block_index | nir_metadata_dominance, NULL);
311 }
312 
313 void
ir3_finalize_nir(struct ir3_compiler * compiler,nir_shader * s)314 ir3_finalize_nir(struct ir3_compiler *compiler, nir_shader *s)
315 {
316    struct nir_lower_tex_options tex_options = {
317       .lower_rect = 0,
318       .lower_tg4_offsets = true,
319       .lower_invalid_implicit_lod = true,
320    };
321 
322    if (compiler->gen >= 4) {
323       /* a4xx seems to have *no* sam.p */
324       tex_options.lower_txp = ~0; /* lower all txp */
325    } else {
326       /* a3xx just needs to avoid sam.p for 3d tex */
327       tex_options.lower_txp = (1 << GLSL_SAMPLER_DIM_3D);
328    }
329 
330    if (ir3_shader_debug & IR3_DBG_DISASM) {
331       mesa_logi("----------------------");
332       nir_log_shaderi(s);
333       mesa_logi("----------------------");
334    }
335 
336    if (s->info.stage == MESA_SHADER_GEOMETRY)
337       NIR_PASS_V(s, ir3_nir_lower_gs);
338 
339    NIR_PASS_V(s, nir_lower_amul, ir3_glsl_type_size);
340 
341    OPT_V(s, nir_lower_regs_to_ssa);
342    OPT_V(s, nir_lower_wrmasks, should_split_wrmask, s);
343 
344    OPT_V(s, nir_lower_tex, &tex_options);
345    OPT_V(s, nir_lower_load_const_to_scalar);
346 
347    if (compiler->array_index_add_half)
348       OPT_V(s, ir3_nir_lower_array_sampler);
349 
350    ir3_optimize_loop(compiler, s);
351 
352    /* do idiv lowering after first opt loop to get a chance to propagate
353     * constants for divide by immed power-of-two:
354     */
355    nir_lower_idiv_options idiv_options = {
356       .imprecise_32bit_lowering = true,
357       .allow_fp16 = true,
358    };
359    const bool idiv_progress = OPT(s, nir_lower_idiv, &idiv_options);
360 
361    if (idiv_progress)
362       ir3_optimize_loop(compiler, s);
363 
364    OPT_V(s, nir_remove_dead_variables, nir_var_function_temp, NULL);
365 
366    if (ir3_shader_debug & IR3_DBG_DISASM) {
367       mesa_logi("----------------------");
368       nir_log_shaderi(s);
369       mesa_logi("----------------------");
370    }
371 
372    /* st_program.c's parameter list optimization requires that future nir
373     * variants don't reallocate the uniform storage, so we have to remove
374     * uniforms that occupy storage.  But we don't want to remove samplers,
375     * because they're needed for YUV variant lowering.
376     */
377    nir_foreach_uniform_variable_safe (var, s) {
378       if (var->data.mode == nir_var_uniform &&
379           (glsl_type_get_image_count(var->type) ||
380            glsl_type_get_sampler_count(var->type)))
381          continue;
382 
383       exec_node_remove(&var->node);
384    }
385    nir_validate_shader(s, "after uniform var removal");
386 
387    nir_sweep(s);
388 }
389 
390 static bool
lower_subgroup_id_filter(const nir_instr * instr,const void * unused)391 lower_subgroup_id_filter(const nir_instr *instr, const void *unused)
392 {
393    (void)unused;
394 
395    if (instr->type != nir_instr_type_intrinsic)
396       return false;
397 
398    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
399    return intr->intrinsic == nir_intrinsic_load_subgroup_invocation ||
400           intr->intrinsic == nir_intrinsic_load_subgroup_id ||
401           intr->intrinsic == nir_intrinsic_load_num_subgroups;
402 }
403 
404 static nir_ssa_def *
lower_subgroup_id(nir_builder * b,nir_instr * instr,void * unused)405 lower_subgroup_id(nir_builder *b, nir_instr *instr, void *unused)
406 {
407    (void)unused;
408 
409    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
410    if (intr->intrinsic == nir_intrinsic_load_subgroup_invocation) {
411       return nir_iand(
412          b, nir_load_local_invocation_index(b),
413          nir_isub(b, nir_load_subgroup_size(b), nir_imm_int(b, 1)));
414    } else if (intr->intrinsic == nir_intrinsic_load_subgroup_id) {
415       return nir_ishr(b, nir_load_local_invocation_index(b),
416                       nir_load_subgroup_id_shift_ir3(b));
417    } else {
418       assert(intr->intrinsic == nir_intrinsic_load_num_subgroups);
419       /* If the workgroup size is constant,
420        * nir_lower_compute_system_values() will replace local_size with a
421        * constant so this can mostly be constant folded away.
422        */
423       nir_ssa_def *local_size = nir_load_workgroup_size(b);
424       nir_ssa_def *size =
425          nir_imul24(b, nir_channel(b, local_size, 0),
426                     nir_imul24(b, nir_channel(b, local_size, 1),
427                                nir_channel(b, local_size, 2)));
428       nir_ssa_def *one = nir_imm_int(b, 1);
429       return nir_iadd(b, one,
430                       nir_ishr(b, nir_isub(b, size, one),
431                                nir_load_subgroup_id_shift_ir3(b)));
432    }
433 }
434 
435 static bool
ir3_nir_lower_subgroup_id_cs(nir_shader * shader)436 ir3_nir_lower_subgroup_id_cs(nir_shader *shader)
437 {
438    return nir_shader_lower_instructions(shader, lower_subgroup_id_filter,
439                                         lower_subgroup_id, NULL);
440 }
441 
442 /**
443  * Late passes that need to be done after pscreen->finalize_nir()
444  */
445 void
ir3_nir_post_finalize(struct ir3_shader * shader)446 ir3_nir_post_finalize(struct ir3_shader *shader)
447 {
448    struct nir_shader *s = shader->nir;
449    struct ir3_compiler *compiler = shader->compiler;
450 
451    NIR_PASS_V(s, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
452               ir3_glsl_type_size, (nir_lower_io_options)0);
453 
454    if (s->info.stage == MESA_SHADER_FRAGMENT) {
455       /* NOTE: lower load_barycentric_at_sample first, since it
456        * produces load_barycentric_at_offset:
457        */
458       NIR_PASS_V(s, ir3_nir_lower_load_barycentric_at_sample);
459       NIR_PASS_V(s, ir3_nir_lower_load_barycentric_at_offset);
460       NIR_PASS_V(s, ir3_nir_move_varying_inputs);
461       NIR_PASS_V(s, nir_lower_fb_read);
462    }
463 
464    if (compiler->gen >= 6 && s->info.stage == MESA_SHADER_FRAGMENT &&
465        !(ir3_shader_debug & IR3_DBG_NOFP16)) {
466       NIR_PASS_V(s, nir_lower_mediump_io, nir_var_shader_out, 0, false);
467    }
468 
469    if ((s->info.stage == MESA_SHADER_COMPUTE) ||
470        (s->info.stage == MESA_SHADER_KERNEL) ||
471        compiler->has_getfiberid) {
472       /* If the API-facing subgroup size is forced to a particular value, lower
473        * it here. Beyond this point nir_intrinsic_load_subgroup_size will return
474        * the "real" subgroup size.
475        */
476       unsigned subgroup_size = 0, max_subgroup_size = 0;
477       switch (shader->api_wavesize) {
478       case IR3_SINGLE_ONLY:
479          subgroup_size = max_subgroup_size = compiler->threadsize_base;
480          break;
481       case IR3_DOUBLE_ONLY:
482          subgroup_size = max_subgroup_size = compiler->threadsize_base * 2;
483          break;
484       case IR3_SINGLE_OR_DOUBLE:
485          /* For vertex stages, we know the wavesize will never be doubled.
486           * Lower subgroup_size here, to avoid having to deal with it when
487           * translating from NIR. Otherwise use the "real" wavesize obtained as
488           * a driver param.
489           */
490          if (s->info.stage != MESA_SHADER_COMPUTE &&
491              s->info.stage != MESA_SHADER_FRAGMENT) {
492             subgroup_size = max_subgroup_size = compiler->threadsize_base;
493          } else {
494             subgroup_size = 0;
495             max_subgroup_size = compiler->threadsize_base * 2;
496          }
497          break;
498       }
499 
500       OPT(s, nir_lower_subgroups,
501           &(nir_lower_subgroups_options){
502              .subgroup_size = subgroup_size,
503              .ballot_bit_size = 32,
504              .ballot_components = max_subgroup_size / 32,
505              .lower_to_scalar = true,
506              .lower_vote_eq = true,
507              .lower_subgroup_masks = true,
508              .lower_read_invocation_to_cond = true,
509              .lower_shuffle = true,
510              .lower_relative_shuffle = true,
511           });
512    }
513 
514    if ((s->info.stage == MESA_SHADER_COMPUTE) ||
515        (s->info.stage == MESA_SHADER_KERNEL)) {
516       bool progress = false;
517       NIR_PASS(progress, s, ir3_nir_lower_subgroup_id_cs);
518 
519       /* ir3_nir_lower_subgroup_id_cs creates extra compute intrinsics which
520        * we need to lower again.
521        */
522       if (progress)
523          NIR_PASS_V(s, nir_lower_compute_system_values, NULL);
524    }
525 
526    /* we cannot ensure that ir3_finalize_nir() is only called once, so
527     * we also need to do any run-once workarounds here:
528     */
529    OPT_V(s, ir3_nir_apply_trig_workarounds);
530 
531    const nir_lower_image_options lower_image_opts = {
532       .lower_cube_size = true,
533    };
534    NIR_PASS_V(s, nir_lower_image, &lower_image_opts);
535 
536    const nir_lower_idiv_options lower_idiv_options = {
537       .imprecise_32bit_lowering = true,
538       .allow_fp16 = true,
539    };
540    NIR_PASS_V(s, nir_lower_idiv, &lower_idiv_options); /* idiv generated by cube lowering */
541 
542 
543    /* The resinfo opcode returns the size in dwords on a4xx */
544    if (compiler->gen == 4)
545       OPT_V(s, ir3_nir_lower_ssbo_size, 2);
546 
547    /* The resinfo opcode we have for getting the SSBO size on a6xx returns a
548     * byte length divided by IBO_0_FMT, while the NIR intrinsic coming in is a
549     * number of bytes. Switch things so the NIR intrinsic in our backend means
550     * dwords.
551     */
552    if (compiler->gen >= 6)
553       OPT_V(s, ir3_nir_lower_ssbo_size, compiler->storage_16bit ? 1 : 2);
554 
555    ir3_optimize_loop(compiler, s);
556 }
557 
558 static bool
ir3_nir_lower_view_layer_id(nir_shader * nir,bool layer_zero,bool view_zero)559 ir3_nir_lower_view_layer_id(nir_shader *nir, bool layer_zero, bool view_zero)
560 {
561    unsigned layer_id_loc = ~0, view_id_loc = ~0;
562    nir_foreach_shader_in_variable (var, nir) {
563       if (var->data.location == VARYING_SLOT_LAYER)
564          layer_id_loc = var->data.driver_location;
565       if (var->data.location == VARYING_SLOT_VIEWPORT)
566          view_id_loc = var->data.driver_location;
567    }
568 
569    assert(!layer_zero || layer_id_loc != ~0);
570    assert(!view_zero || view_id_loc != ~0);
571 
572    bool progress = false;
573    nir_builder b;
574 
575    nir_foreach_function (func, nir) {
576       nir_builder_init(&b, func->impl);
577 
578       nir_foreach_block (block, func->impl) {
579          nir_foreach_instr_safe (instr, block) {
580             if (instr->type != nir_instr_type_intrinsic)
581                continue;
582 
583             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
584 
585             if (intrin->intrinsic != nir_intrinsic_load_input)
586                continue;
587 
588             unsigned base = nir_intrinsic_base(intrin);
589             if (base != layer_id_loc && base != view_id_loc)
590                continue;
591 
592             b.cursor = nir_before_instr(&intrin->instr);
593             nir_ssa_def *zero = nir_imm_int(&b, 0);
594             nir_ssa_def_rewrite_uses(&intrin->dest.ssa, zero);
595             nir_instr_remove(&intrin->instr);
596             progress = true;
597          }
598       }
599 
600       if (progress) {
601          nir_metadata_preserve(
602             func->impl, nir_metadata_block_index | nir_metadata_dominance);
603       } else {
604          nir_metadata_preserve(func->impl, nir_metadata_all);
605       }
606    }
607 
608    return progress;
609 }
610 
611 static bool
lower_ucp_vs(struct ir3_shader_variant * so)612 lower_ucp_vs(struct ir3_shader_variant *so)
613 {
614    if (!so->key.ucp_enables)
615       return false;
616 
617    gl_shader_stage last_geom_stage = MESA_SHADER_VERTEX;
618 
619    if (so->key.tessellation) {
620       last_geom_stage = MESA_SHADER_TESS_EVAL;
621    } else if (so->key.has_gs) {
622       last_geom_stage = MESA_SHADER_GEOMETRY;
623    } else {
624       last_geom_stage = MESA_SHADER_VERTEX;
625    }
626 
627    return so->type == last_geom_stage;
628 }
629 
630 void
ir3_nir_lower_variant(struct ir3_shader_variant * so,nir_shader * s)631 ir3_nir_lower_variant(struct ir3_shader_variant *so, nir_shader *s)
632 {
633    if (ir3_shader_debug & IR3_DBG_DISASM) {
634       mesa_logi("----------------------");
635       nir_log_shaderi(s);
636       mesa_logi("----------------------");
637    }
638 
639    bool progress = false;
640 
641    if (so->key.has_gs || so->key.tessellation) {
642       switch (so->type) {
643       case MESA_SHADER_VERTEX:
644          NIR_PASS_V(s, ir3_nir_lower_to_explicit_output, so,
645                     so->key.tessellation);
646          progress = true;
647          break;
648       case MESA_SHADER_TESS_CTRL:
649          NIR_PASS_V(s, ir3_nir_lower_tess_ctrl, so, so->key.tessellation);
650          NIR_PASS_V(s, ir3_nir_lower_to_explicit_input, so);
651          progress = true;
652          break;
653       case MESA_SHADER_TESS_EVAL:
654          NIR_PASS_V(s, ir3_nir_lower_tess_eval, so, so->key.tessellation);
655          if (so->key.has_gs)
656             NIR_PASS_V(s, ir3_nir_lower_to_explicit_output, so,
657                        so->key.tessellation);
658          progress = true;
659          break;
660       case MESA_SHADER_GEOMETRY:
661          NIR_PASS_V(s, ir3_nir_lower_to_explicit_input, so);
662          progress = true;
663          break;
664       default:
665          break;
666       }
667    }
668 
669    /* Note that it is intentional to use the VS lowering pass for GS, since we
670     * lower GS into something that looks more like a VS in ir3_nir_lower_gs():
671     */
672    if (lower_ucp_vs(so)) {
673       progress |= OPT(s, nir_lower_clip_vs, so->key.ucp_enables, false, true, NULL);
674    } else if (s->info.stage == MESA_SHADER_FRAGMENT) {
675       bool layer_zero =
676          so->key.layer_zero && (s->info.inputs_read & VARYING_BIT_LAYER);
677       bool view_zero =
678          so->key.view_zero && (s->info.inputs_read & VARYING_BIT_VIEWPORT);
679 
680       if (so->key.ucp_enables && !so->compiler->has_clip_cull)
681          progress |= OPT(s, nir_lower_clip_fs, so->key.ucp_enables, true);
682       if (layer_zero || view_zero)
683          progress |= OPT(s, ir3_nir_lower_view_layer_id, layer_zero, view_zero);
684    }
685 
686    /* Move large constant variables to the constants attached to the NIR
687     * shader, which we will upload in the immediates range.  This generates
688     * amuls, so we need to clean those up after.
689     *
690     * Passing no size_align, we would get packed values, which if we end up
691     * having to load with LDC would result in extra reads to unpack from
692     * straddling loads.  Align everything to vec4 to avoid that, though we
693     * could theoretically do better.
694     */
695    OPT_V(s, nir_opt_large_constants, glsl_get_vec4_size_align_bytes,
696          32 /* bytes */);
697    OPT_V(s, ir3_nir_lower_load_constant, so);
698 
699    /* Lower large temporaries to scratch, which in Qualcomm terms is private
700     * memory, to avoid excess register pressure. This should happen after
701     * nir_opt_large_constants, because loading from a UBO is much, much less
702     * expensive.
703     */
704    if (so->compiler->has_pvtmem) {
705       progress |= OPT(s, nir_lower_vars_to_scratch, nir_var_function_temp,
706                       16 * 16 /* bytes */, glsl_get_natural_size_align_bytes);
707    }
708 
709    /* Lower scratch writemasks */
710    progress |= OPT(s, nir_lower_wrmasks, should_split_wrmask, s);
711 
712    progress |= OPT(s, ir3_nir_lower_wide_load_store);
713    progress |= OPT(s, ir3_nir_lower_64b_global);
714    progress |= OPT(s, ir3_nir_lower_64b_intrinsics);
715    progress |= OPT(s, ir3_nir_lower_64b_undef);
716    progress |= OPT(s, nir_lower_int64);
717 
718    /* Cleanup code leftover from lowering passes before opt_preamble */
719    if (progress) {
720       progress |= OPT(s, nir_opt_constant_folding);
721    }
722 
723    /* Do the preamble before analysing UBO ranges, because it's usually
724     * higher-value and because it can result in eliminating some indirect UBO
725     * accesses where otherwise we'd have to push the whole range. However we
726     * have to lower the preamble after UBO lowering so that UBO lowering can
727     * insert instructions in the preamble to push UBOs.
728     */
729    if (so->compiler->has_preamble &&
730        !(ir3_shader_debug & IR3_DBG_NOPREAMBLE))
731       progress |= OPT(s, ir3_nir_opt_preamble, so);
732 
733    if (!so->binning_pass)
734       OPT_V(s, ir3_nir_analyze_ubo_ranges, so);
735 
736    progress |= OPT(s, ir3_nir_lower_ubo_loads, so);
737 
738    progress |= OPT(s, ir3_nir_lower_preamble, so);
739 
740    OPT_V(s, nir_lower_amul, ir3_glsl_type_size);
741 
742    /* UBO offset lowering has to come after we've decided what will
743     * be left as load_ubo
744     */
745    if (so->compiler->gen >= 6)
746       progress |= OPT(s, nir_lower_ubo_vec4);
747 
748    OPT_V(s, ir3_nir_lower_io_offsets);
749 
750    if (progress)
751       ir3_optimize_loop(so->compiler, s);
752 
753    /* Fixup indirect load_uniform's which end up with a const base offset
754     * which is too large to encode.  Do this late(ish) so we actually
755     * can differentiate indirect vs non-indirect.
756     */
757    if (OPT(s, ir3_nir_fixup_load_uniform))
758       ir3_optimize_loop(so->compiler, s);
759 
760    /* Do late algebraic optimization to turn add(a, neg(b)) back into
761     * subs, then the mandatory cleanup after algebraic.  Note that it may
762     * produce fnegs, and if so then we need to keep running to squash
763     * fneg(fneg(a)).
764     */
765    bool more_late_algebraic = true;
766    while (more_late_algebraic) {
767       more_late_algebraic = OPT(s, nir_opt_algebraic_late);
768       if (!more_late_algebraic && so->compiler->gen >= 5) {
769          /* Lowers texture operations that have only f2f16 or u2u16 called on
770           * them to have a 16-bit destination.  Also, lower 16-bit texture
771           * coordinates that had been upconverted to 32-bits just for the
772           * sampler to just be 16-bit texture sources.
773           */
774          struct nir_fold_tex_srcs_options fold_srcs_options = {
775             .sampler_dims = ~0,
776             .src_types = (1 << nir_tex_src_coord) |
777                          (1 << nir_tex_src_lod) |
778                          (1 << nir_tex_src_bias) |
779                          (1 << nir_tex_src_offset) |
780                          (1 << nir_tex_src_comparator) |
781                          (1 << nir_tex_src_min_lod) |
782                          (1 << nir_tex_src_ms_index) |
783                          (1 << nir_tex_src_ddx) |
784                          (1 << nir_tex_src_ddy),
785          };
786          struct nir_fold_16bit_tex_image_options fold_16bit_options = {
787             .rounding_mode = nir_rounding_mode_rtz,
788             .fold_tex_dest = true,
789             /* blob dumps have no half regs on pixel 2's ldib or stib, so only enable for a6xx+. */
790             .fold_image_load_store_data = so->compiler->gen >= 6,
791             .fold_srcs_options_count = 1,
792             .fold_srcs_options = &fold_srcs_options,
793          };
794          OPT(s, nir_fold_16bit_tex_image, &fold_16bit_options);
795       }
796       OPT_V(s, nir_opt_constant_folding);
797       OPT_V(s, nir_copy_prop);
798       OPT_V(s, nir_opt_dce);
799       OPT_V(s, nir_opt_cse);
800    }
801 
802    OPT_V(s, nir_opt_sink, nir_move_const_undef);
803 
804    if (ir3_shader_debug & IR3_DBG_DISASM) {
805       mesa_logi("----------------------");
806       nir_log_shaderi(s);
807       mesa_logi("----------------------");
808    }
809 
810    nir_sweep(s);
811 
812    /* Binning pass variants re-use  the const_state of the corresponding
813     * draw pass shader, so that same const emit can be re-used for both
814     * passes:
815     */
816    if (!so->binning_pass)
817       ir3_setup_const_state(s, so, ir3_const_state(so));
818 }
819 
820 static void
ir3_nir_scan_driver_consts(struct ir3_compiler * compiler,nir_shader * shader,struct ir3_const_state * layout)821 ir3_nir_scan_driver_consts(struct ir3_compiler *compiler, nir_shader *shader, struct ir3_const_state *layout)
822 {
823    nir_foreach_function (function, shader) {
824       if (!function->impl)
825          continue;
826 
827       nir_foreach_block (block, function->impl) {
828          nir_foreach_instr (instr, block) {
829             if (instr->type != nir_instr_type_intrinsic)
830                continue;
831 
832             nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
833             unsigned idx;
834 
835             switch (intr->intrinsic) {
836             case nir_intrinsic_image_atomic_add:
837             case nir_intrinsic_image_atomic_imin:
838             case nir_intrinsic_image_atomic_umin:
839             case nir_intrinsic_image_atomic_imax:
840             case nir_intrinsic_image_atomic_umax:
841             case nir_intrinsic_image_atomic_and:
842             case nir_intrinsic_image_atomic_or:
843             case nir_intrinsic_image_atomic_xor:
844             case nir_intrinsic_image_atomic_exchange:
845             case nir_intrinsic_image_atomic_comp_swap:
846             case nir_intrinsic_image_load:
847             case nir_intrinsic_image_store:
848             case nir_intrinsic_image_size:
849                /* a4xx gets these supplied by the hw directly (maybe CP?) */
850                if (compiler->gen == 5 &&
851                    !(intr->intrinsic == nir_intrinsic_image_load &&
852                      !(nir_intrinsic_access(intr) & ACCESS_COHERENT))) {
853                   idx = nir_src_as_uint(intr->src[0]);
854                   if (layout->image_dims.mask & (1 << idx))
855                      break;
856                   layout->image_dims.mask |= (1 << idx);
857                   layout->image_dims.off[idx] = layout->image_dims.count;
858                   layout->image_dims.count += 3; /* three const per */
859                }
860                break;
861             case nir_intrinsic_load_base_vertex:
862             case nir_intrinsic_load_first_vertex:
863                layout->num_driver_params =
864                   MAX2(layout->num_driver_params, IR3_DP_VTXID_BASE + 1);
865                break;
866             case nir_intrinsic_load_base_instance:
867                layout->num_driver_params =
868                   MAX2(layout->num_driver_params, IR3_DP_INSTID_BASE + 1);
869                break;
870             case nir_intrinsic_load_user_clip_plane:
871                idx = nir_intrinsic_ucp_id(intr);
872                layout->num_driver_params = MAX2(layout->num_driver_params,
873                                                 IR3_DP_UCP0_X + (idx + 1) * 4);
874                break;
875             case nir_intrinsic_load_num_workgroups:
876                layout->num_driver_params =
877                   MAX2(layout->num_driver_params, IR3_DP_NUM_WORK_GROUPS_Z + 1);
878                break;
879             case nir_intrinsic_load_workgroup_id:
880                if (!compiler->has_shared_regfile) {
881                   layout->num_driver_params =
882                      MAX2(layout->num_driver_params, IR3_DP_WORKGROUP_ID_Z + 1);
883                }
884                break;
885             case nir_intrinsic_load_workgroup_size:
886                layout->num_driver_params = MAX2(layout->num_driver_params,
887                                                 IR3_DP_LOCAL_GROUP_SIZE_Z + 1);
888                break;
889             case nir_intrinsic_load_base_workgroup_id:
890                layout->num_driver_params =
891                   MAX2(layout->num_driver_params, IR3_DP_BASE_GROUP_Z + 1);
892                break;
893             case nir_intrinsic_load_subgroup_size: {
894                assert(shader->info.stage == MESA_SHADER_COMPUTE ||
895                       shader->info.stage == MESA_SHADER_FRAGMENT);
896                enum ir3_driver_param size = shader->info.stage == MESA_SHADER_COMPUTE ?
897                   IR3_DP_CS_SUBGROUP_SIZE : IR3_DP_FS_SUBGROUP_SIZE;
898                layout->num_driver_params =
899                   MAX2(layout->num_driver_params, size + 1);
900                break;
901             }
902             case nir_intrinsic_load_subgroup_id_shift_ir3:
903                layout->num_driver_params =
904                   MAX2(layout->num_driver_params, IR3_DP_SUBGROUP_ID_SHIFT + 1);
905                break;
906             case nir_intrinsic_load_draw_id:
907                layout->num_driver_params =
908                   MAX2(layout->num_driver_params, IR3_DP_DRAWID + 1);
909                break;
910             default:
911                break;
912             }
913          }
914       }
915    }
916 
917    /* TODO: Provide a spot somewhere to safely upload unwanted values, and a way
918     * to determine if they're wanted or not. For now we always make the whole
919     * driver param range available, since the driver will always instruct the
920     * hardware to upload these.
921     */
922    if (!compiler->has_shared_regfile &&
923          shader->info.stage == MESA_SHADER_COMPUTE) {
924       layout->num_driver_params =
925          MAX2(layout->num_driver_params, IR3_DP_WORKGROUP_ID_Z + 1);
926    }
927 }
928 
929 /* Sets up the variant-dependent constant state for the ir3_shader.  Note
930  * that it is also used from ir3_nir_analyze_ubo_ranges() to figure out the
931  * maximum number of driver params that would eventually be used, to leave
932  * space for this function to allocate the driver params.
933  */
934 void
ir3_setup_const_state(nir_shader * nir,struct ir3_shader_variant * v,struct ir3_const_state * const_state)935 ir3_setup_const_state(nir_shader *nir, struct ir3_shader_variant *v,
936                       struct ir3_const_state *const_state)
937 {
938    struct ir3_compiler *compiler = v->compiler;
939 
940    memset(&const_state->offsets, ~0, sizeof(const_state->offsets));
941 
942    ir3_nir_scan_driver_consts(compiler, nir, const_state);
943 
944    if ((compiler->gen < 5) && (v->stream_output.num_outputs > 0)) {
945       const_state->num_driver_params =
946          MAX2(const_state->num_driver_params, IR3_DP_VTXCNT_MAX + 1);
947    }
948 
949    const_state->num_ubos = nir->info.num_ubos;
950 
951    assert((const_state->ubo_state.size % 16) == 0);
952    unsigned constoff = v->num_reserved_user_consts +
953       const_state->ubo_state.size / 16 +
954       const_state->preamble_size;
955    unsigned ptrsz = ir3_pointer_size(compiler);
956 
957    if (const_state->num_ubos > 0) {
958       const_state->offsets.ubo = constoff;
959       constoff += align(const_state->num_ubos * ptrsz, 4) / 4;
960    }
961 
962    if (const_state->image_dims.count > 0) {
963       unsigned cnt = const_state->image_dims.count;
964       const_state->offsets.image_dims = constoff;
965       constoff += align(cnt, 4) / 4;
966    }
967 
968    if (v->type == MESA_SHADER_KERNEL) {
969       const_state->offsets.kernel_params = constoff;
970       constoff += align(v->cs.req_input_mem, 4) / 4;
971    }
972 
973    if (const_state->num_driver_params > 0) {
974       /* num_driver_params in dwords.  we only need to align to vec4s for the
975        * common case of immediate constant uploads, but for indirect dispatch
976        * the constants may also be indirect and so we have to align the area in
977        * const space to that requirement.
978        */
979       const_state->num_driver_params = align(const_state->num_driver_params, 4);
980       unsigned upload_unit = 1;
981       if (v->type == MESA_SHADER_COMPUTE ||
982           (const_state->num_driver_params >= IR3_DP_VTXID_BASE)) {
983          upload_unit = compiler->const_upload_unit;
984       }
985 
986       /* offset cannot be 0 for vs params loaded by CP_DRAW_INDIRECT_MULTI */
987       if (v->type == MESA_SHADER_VERTEX && compiler->gen >= 6)
988          constoff = MAX2(constoff, 1);
989       constoff = align(constoff, upload_unit);
990       const_state->offsets.driver_param = constoff;
991 
992       constoff += align(const_state->num_driver_params / 4, upload_unit);
993    }
994 
995    if ((v->type == MESA_SHADER_VERTEX) && (compiler->gen < 5) &&
996        v->stream_output.num_outputs > 0) {
997       const_state->offsets.tfbo = constoff;
998       constoff += align(IR3_MAX_SO_BUFFERS * ptrsz, 4) / 4;
999    }
1000 
1001    switch (v->type) {
1002    case MESA_SHADER_VERTEX:
1003       const_state->offsets.primitive_param = constoff;
1004       constoff += 1;
1005       break;
1006    case MESA_SHADER_TESS_CTRL:
1007    case MESA_SHADER_TESS_EVAL:
1008       const_state->offsets.primitive_param = constoff;
1009       constoff += 2;
1010 
1011       const_state->offsets.primitive_map = constoff;
1012       constoff += DIV_ROUND_UP(v->input_size, 4);
1013       break;
1014    case MESA_SHADER_GEOMETRY:
1015       const_state->offsets.primitive_param = constoff;
1016       constoff += 1;
1017 
1018       const_state->offsets.primitive_map = constoff;
1019       constoff += DIV_ROUND_UP(v->input_size, 4);
1020       break;
1021    default:
1022       break;
1023    }
1024 
1025    const_state->offsets.immediate = constoff;
1026 
1027    assert(constoff <= ir3_max_const(v));
1028 }
1029