• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2016 Red Hat.
3  * Copyright © 2016 Bas Nieuwenhuizen
4  *
5  * based in part on anv driver which is:
6  * Copyright © 2015 Intel Corporation
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the next
16  * paragraph) shall be included in all copies or substantial portions of the
17  * Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25  * IN THE SOFTWARE.
26  */
27 
28 #include "radv_shader.h"
29 #include "nir/nir.h"
30 #include "nir/nir_builder.h"
31 #include "nir/nir_xfb_info.h"
32 #include "spirv/nir_spirv.h"
33 #include "util/memstream.h"
34 #include "util/mesa-sha1.h"
35 #include "util/u_atomic.h"
36 #include "radv_debug.h"
37 #include "radv_meta.h"
38 #include "radv_private.h"
39 #include "radv_shader_args.h"
40 
41 #include "util/debug.h"
42 #include "ac_binary.h"
43 #include "ac_nir.h"
44 #ifndef _WIN32
45 #include "ac_rtld.h"
46 #endif
47 #include "aco_interface.h"
48 #include "sid.h"
49 #include "vk_format.h"
50 
51 #include "aco_shader_info.h"
52 #include "radv_aco_shader_info.h"
53 #ifdef LLVM_AVAILABLE
54 #include "ac_llvm_util.h"
55 #endif
56 
57 static void
get_nir_options_for_stage(struct radv_physical_device * device,gl_shader_stage stage)58 get_nir_options_for_stage(struct radv_physical_device *device, gl_shader_stage stage)
59 {
60    bool split_fma = (stage <= MESA_SHADER_GEOMETRY || stage == MESA_SHADER_MESH) &&
61                     device->instance->debug_flags & RADV_DEBUG_SPLIT_FMA;
62    device->nir_options[stage] = (nir_shader_compiler_options){
63       .vertex_id_zero_based = true,
64       .lower_scmp = true,
65       .lower_flrp16 = true,
66       .lower_flrp32 = true,
67       .lower_flrp64 = true,
68       .lower_device_index_to_zero = true,
69       .lower_fdiv = true,
70       .lower_fmod = true,
71       .lower_ineg = true,
72       .lower_bitfield_insert_to_bitfield_select = true,
73       .lower_bitfield_extract = true,
74       .lower_pack_snorm_4x8 = true,
75       .lower_pack_unorm_4x8 = true,
76       .lower_pack_half_2x16 = true,
77       .lower_pack_64_2x32 = true,
78       .lower_pack_64_4x16 = true,
79       .lower_pack_32_2x16 = true,
80       .lower_unpack_snorm_2x16 = true,
81       .lower_unpack_snorm_4x8 = true,
82       .lower_unpack_unorm_2x16 = true,
83       .lower_unpack_unorm_4x8 = true,
84       .lower_unpack_half_2x16 = true,
85       .lower_ffma16 = split_fma || device->rad_info.gfx_level < GFX9,
86       .lower_ffma32 = split_fma || device->rad_info.gfx_level < GFX10_3,
87       .lower_ffma64 = split_fma,
88       .lower_fpow = true,
89       .lower_mul_2x32_64 = true,
90       .lower_rotate = true,
91       .lower_iadd_sat = device->rad_info.gfx_level <= GFX8,
92       .lower_hadd = true,
93       .lower_mul_32x16 = true,
94       .has_fsub = true,
95       .has_isub = true,
96       .has_sdot_4x8 = device->rad_info.has_accelerated_dot_product,
97       .has_udot_4x8 = device->rad_info.has_accelerated_dot_product,
98       .has_dot_2x16 = device->rad_info.has_accelerated_dot_product,
99       .use_scoped_barrier = true,
100 #ifdef LLVM_AVAILABLE
101       .has_fmulz = !device->use_llvm || LLVM_VERSION_MAJOR >= 12,
102 #else
103       .has_fmulz = true,
104 #endif
105       .max_unroll_iterations = 32,
106       .max_unroll_iterations_aggressive = 128,
107       .use_interpolated_input_intrinsics = true,
108       .vectorize_vec2_16bit = true,
109       /* nir_lower_int64() isn't actually called for the LLVM backend,
110        * but this helps the loop unrolling heuristics. */
111       .lower_int64_options = nir_lower_imul64 | nir_lower_imul_high64 | nir_lower_imul_2x32_64 |
112                              nir_lower_divmod64 | nir_lower_minmax64 | nir_lower_iabs64 |
113                              nir_lower_iadd_sat64,
114       .lower_doubles_options = nir_lower_drcp | nir_lower_dsqrt | nir_lower_drsq | nir_lower_ddiv,
115       .divergence_analysis_options = nir_divergence_view_index_uniform,
116    };
117 }
118 
119 void
radv_get_nir_options(struct radv_physical_device * device)120 radv_get_nir_options(struct radv_physical_device *device)
121 {
122    for (gl_shader_stage stage = MESA_SHADER_VERTEX; stage < MESA_VULKAN_SHADER_STAGES; stage++)
123       get_nir_options_for_stage(device, stage);
124 }
125 
126 static uint8_t
vectorize_vec2_16bit(const nir_instr * instr,const void * _)127 vectorize_vec2_16bit(const nir_instr *instr, const void *_)
128 {
129    if (instr->type != nir_instr_type_alu)
130       return 0;
131 
132    const nir_alu_instr *alu = nir_instr_as_alu(instr);
133    const unsigned bit_size = alu->dest.dest.ssa.bit_size;
134    if (bit_size == 16)
135       return 2;
136    else
137       return 1;
138 }
139 
140 static bool
is_meta_shader(nir_shader * nir)141 is_meta_shader(nir_shader *nir)
142 {
143    return nir && nir->info.internal;
144 }
145 
146 bool
radv_can_dump_shader(struct radv_device * device,nir_shader * nir,bool meta_shader)147 radv_can_dump_shader(struct radv_device *device, nir_shader *nir, bool meta_shader)
148 {
149    if (!(device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS))
150       return false;
151 
152    if ((is_meta_shader(nir) || meta_shader) &&
153        !(device->instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS))
154       return false;
155 
156    return true;
157 }
158 
159 bool
radv_can_dump_shader_stats(struct radv_device * device,nir_shader * nir)160 radv_can_dump_shader_stats(struct radv_device *device, nir_shader *nir)
161 {
162    /* Only dump non-meta shader stats. */
163    return device->instance->debug_flags & RADV_DEBUG_DUMP_SHADER_STATS && !is_meta_shader(nir);
164 }
165 
166 void
radv_optimize_nir(struct nir_shader * shader,bool optimize_conservatively,bool allow_copies)167 radv_optimize_nir(struct nir_shader *shader, bool optimize_conservatively, bool allow_copies)
168 {
169    bool progress;
170 
171    do {
172       progress = false;
173 
174       NIR_PASS(progress, shader, nir_split_array_vars, nir_var_function_temp);
175       NIR_PASS(progress, shader, nir_shrink_vec_array_vars, nir_var_function_temp);
176 
177       if (allow_copies) {
178          /* Only run this pass in the first call to
179           * radv_optimize_nir.  Later calls assume that we've
180           * lowered away any copy_deref instructions and we
181           *  don't want to introduce any more.
182           */
183          NIR_PASS(progress, shader, nir_opt_find_array_copies);
184       }
185 
186       NIR_PASS(progress, shader, nir_opt_copy_prop_vars);
187       NIR_PASS(progress, shader, nir_opt_dead_write_vars);
188       NIR_PASS(_, shader, nir_lower_vars_to_ssa);
189 
190       NIR_PASS(_, shader, nir_lower_alu_width, vectorize_vec2_16bit, NULL);
191       NIR_PASS(_, shader, nir_lower_phis_to_scalar, true);
192 
193       NIR_PASS(progress, shader, nir_copy_prop);
194       NIR_PASS(progress, shader, nir_opt_remove_phis);
195       NIR_PASS(progress, shader, nir_opt_dce);
196       if (nir_opt_trivial_continues(shader)) {
197          progress = true;
198          NIR_PASS(progress, shader, nir_copy_prop);
199          NIR_PASS(progress, shader, nir_opt_remove_phis);
200          NIR_PASS(progress, shader, nir_opt_dce);
201       }
202       NIR_PASS(progress, shader, nir_opt_if,
203                nir_opt_if_aggressive_last_continue | nir_opt_if_optimize_phi_true_false);
204       NIR_PASS(progress, shader, nir_opt_dead_cf);
205       NIR_PASS(progress, shader, nir_opt_cse);
206       NIR_PASS(progress, shader, nir_opt_peephole_select, 8, true, true);
207       NIR_PASS(progress, shader, nir_opt_constant_folding);
208       NIR_PASS(progress, shader, nir_opt_algebraic);
209 
210       NIR_PASS(progress, shader, nir_opt_undef);
211 
212       if (shader->options->max_unroll_iterations) {
213          NIR_PASS(progress, shader, nir_opt_loop_unroll);
214       }
215    } while (progress && !optimize_conservatively);
216 
217    NIR_PASS(progress, shader, nir_opt_shrink_vectors);
218    NIR_PASS(progress, shader, nir_remove_dead_variables,
219             nir_var_function_temp | nir_var_shader_in | nir_var_shader_out, NULL);
220 
221    if (shader->info.stage == MESA_SHADER_FRAGMENT &&
222        (shader->info.fs.uses_discard || shader->info.fs.uses_demote)) {
223       NIR_PASS(progress, shader, nir_opt_conditional_discard);
224       NIR_PASS(progress, shader, nir_opt_move_discards_to_top);
225    }
226 
227    NIR_PASS(progress, shader, nir_opt_move, nir_move_load_ubo);
228 }
229 
230 void
radv_optimize_nir_algebraic(nir_shader * nir,bool opt_offsets)231 radv_optimize_nir_algebraic(nir_shader *nir, bool opt_offsets)
232 {
233    bool more_algebraic = true;
234    while (more_algebraic) {
235       more_algebraic = false;
236       NIR_PASS(_, nir, nir_copy_prop);
237       NIR_PASS(_, nir, nir_opt_dce);
238       NIR_PASS(_, nir, nir_opt_constant_folding);
239       NIR_PASS(_, nir, nir_opt_cse);
240       NIR_PASS(more_algebraic, nir, nir_opt_algebraic);
241    }
242 
243    if (opt_offsets) {
244       static const nir_opt_offsets_options offset_options = {
245          .uniform_max = 0,
246          .buffer_max = ~0,
247          .shared_max = ~0,
248       };
249       NIR_PASS(_, nir, nir_opt_offsets, &offset_options);
250    }
251 
252    /* Do late algebraic optimization to turn add(a,
253     * neg(b)) back into subs, then the mandatory cleanup
254     * after algebraic.  Note that it may produce fnegs,
255     * and if so then we need to keep running to squash
256     * fneg(fneg(a)).
257     */
258    bool more_late_algebraic = true;
259    while (more_late_algebraic) {
260       more_late_algebraic = false;
261       NIR_PASS(more_late_algebraic, nir, nir_opt_algebraic_late);
262       NIR_PASS(_, nir, nir_opt_constant_folding);
263       NIR_PASS(_, nir, nir_copy_prop);
264       NIR_PASS(_, nir, nir_opt_dce);
265       NIR_PASS(_, nir, nir_opt_cse);
266    }
267 }
268 
269 static void
shared_var_info(const struct glsl_type * type,unsigned * size,unsigned * align)270 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
271 {
272    assert(glsl_type_is_vector_or_scalar(type));
273 
274    uint32_t comp_size = glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
275    unsigned length = glsl_get_vector_elements(type);
276    *size = comp_size * length, *align = comp_size;
277 }
278 
279 struct radv_shader_debug_data {
280    struct radv_device *device;
281    const struct vk_object_base *object;
282 };
283 
284 static void
radv_spirv_nir_debug(void * private_data,enum nir_spirv_debug_level level,size_t spirv_offset,const char * message)285 radv_spirv_nir_debug(void *private_data, enum nir_spirv_debug_level level, size_t spirv_offset,
286                      const char *message)
287 {
288    struct radv_shader_debug_data *debug_data = private_data;
289    struct radv_instance *instance = debug_data->device->instance;
290 
291    static const VkDebugReportFlagsEXT vk_flags[] = {
292       [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
293       [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
294       [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
295    };
296    char buffer[256];
297 
298    snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long)spirv_offset, message);
299 
300    vk_debug_report(&instance->vk, vk_flags[level], debug_data->object, 0, 0, "radv", buffer);
301 }
302 
303 static void
radv_compiler_debug(void * private_data,enum aco_compiler_debug_level level,const char * message)304 radv_compiler_debug(void *private_data, enum aco_compiler_debug_level level, const char *message)
305 {
306    struct radv_shader_debug_data *debug_data = private_data;
307    struct radv_instance *instance = debug_data->device->instance;
308 
309    static const VkDebugReportFlagsEXT vk_flags[] = {
310       [ACO_COMPILER_DEBUG_LEVEL_PERFWARN] = VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
311       [ACO_COMPILER_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
312    };
313 
314    /* VK_DEBUG_REPORT_DEBUG_BIT_EXT specifies diagnostic information
315     * from the implementation and layers.
316     */
317    vk_debug_report(&instance->vk, vk_flags[level] | VK_DEBUG_REPORT_DEBUG_BIT_EXT,
318                    NULL, 0, 0, "radv", message);
319 }
320 
321 static bool
lower_intrinsics(nir_shader * nir,const struct radv_pipeline_key * key)322 lower_intrinsics(nir_shader *nir, const struct radv_pipeline_key *key)
323 {
324    nir_function_impl *entry = nir_shader_get_entrypoint(nir);
325    bool progress = false;
326    nir_builder b;
327 
328    nir_builder_init(&b, entry);
329 
330    nir_foreach_block (block, entry) {
331       nir_foreach_instr_safe (instr, block) {
332          if (instr->type != nir_instr_type_intrinsic)
333             continue;
334 
335          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
336          b.cursor = nir_before_instr(&intrin->instr);
337 
338          nir_ssa_def *def = NULL;
339          switch (intrin->intrinsic) {
340          case nir_intrinsic_is_sparse_texels_resident:
341             def = nir_ieq_imm(&b, intrin->src[0].ssa, 0);
342             break;
343          case nir_intrinsic_sparse_residency_code_and:
344             def = nir_ior(&b, intrin->src[0].ssa, intrin->src[1].ssa);
345             break;
346          case nir_intrinsic_load_view_index:
347             if (key->has_multiview_view_index)
348                continue;
349             def = nir_imm_zero(&b, 1, 32);
350             break;
351          default:
352             continue;
353          }
354 
355          nir_ssa_def_rewrite_uses(&intrin->dest.ssa, def);
356 
357          nir_instr_remove(instr);
358          progress = true;
359       }
360    }
361 
362    if (progress)
363       nir_metadata_preserve(entry, nir_metadata_block_index | nir_metadata_dominance);
364    else
365       nir_metadata_preserve(entry, nir_metadata_all);
366 
367    return progress;
368 }
369 
370 static bool
radv_lower_primitive_shading_rate(nir_shader * nir,enum amd_gfx_level gfx_level)371 radv_lower_primitive_shading_rate(nir_shader *nir, enum amd_gfx_level gfx_level)
372 {
373    nir_function_impl *impl = nir_shader_get_entrypoint(nir);
374    bool progress = false;
375 
376    nir_builder b;
377    nir_builder_init(&b, impl);
378 
379    /* Iterate in reverse order since there should be only one deref store to PRIMITIVE_SHADING_RATE
380     * after lower_io_to_temporaries for vertex shaders.
381     */
382    nir_foreach_block_reverse(block, impl) {
383       nir_foreach_instr_reverse(instr, block) {
384          if (instr->type != nir_instr_type_intrinsic)
385             continue;
386 
387          nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
388          if (intr->intrinsic != nir_intrinsic_store_deref)
389             continue;
390 
391          nir_variable *var = nir_intrinsic_get_var(intr, 0);
392          if (var->data.mode != nir_var_shader_out ||
393              var->data.location != VARYING_SLOT_PRIMITIVE_SHADING_RATE)
394             continue;
395 
396          b.cursor = nir_before_instr(instr);
397 
398          nir_ssa_def *val = nir_ssa_for_src(&b, intr->src[1], 1);
399 
400          /* x_rate = (shadingRate & (Horizontal2Pixels | Horizontal4Pixels)) ? 0x1 : 0x0; */
401          nir_ssa_def *x_rate = nir_iand_imm(&b, val, 12);
402          x_rate = nir_b2i32(&b, nir_ine_imm(&b, x_rate, 0));
403 
404          /* y_rate = (shadingRate & (Vertical2Pixels | Vertical4Pixels)) ? 0x1 : 0x0; */
405          nir_ssa_def *y_rate = nir_iand_imm(&b, val, 3);
406          y_rate = nir_b2i32(&b, nir_ine_imm(&b, y_rate, 0));
407 
408          nir_ssa_def *out = NULL;
409 
410          /* MS:
411           * Primitive shading rate is a per-primitive output, it is
412           * part of the second channel of the primitive export.
413           * Bits [28:31] = VRS rate
414           * This will be added to the other bits of that channel in the backend.
415           *
416           * VS, TES, GS:
417           * Primitive shading rate is a per-vertex output pos export.
418           * Bits [2:5] = VRS rate
419           * HW shading rate = (xRate << 2) | (yRate << 4)
420           *
421           * GFX11: 4-bit VRS_SHADING_RATE enum
422           * GFX10: X = low 2 bits, Y = high 2 bits
423           */
424          unsigned x_rate_shift = 2;
425          unsigned y_rate_shift = 4;
426 
427          if (gfx_level >= GFX11) {
428             x_rate_shift = 4;
429             y_rate_shift = 2;
430          }
431          if (nir->info.stage == MESA_SHADER_MESH) {
432             x_rate_shift += 26;
433             y_rate_shift += 26;
434          }
435 
436          out = nir_ior(&b, nir_ishl_imm(&b, x_rate, x_rate_shift), nir_ishl_imm(&b, y_rate, y_rate_shift));
437 
438          nir_instr_rewrite_src(&intr->instr, &intr->src[1], nir_src_for_ssa(out));
439 
440          progress = true;
441          if (nir->info.stage == MESA_SHADER_VERTEX)
442             break;
443       }
444       if (nir->info.stage == MESA_SHADER_VERTEX && progress)
445          break;
446    }
447 
448    if (progress)
449       nir_metadata_preserve(impl, nir_metadata_block_index | nir_metadata_dominance);
450    else
451       nir_metadata_preserve(impl, nir_metadata_all);
452 
453    return progress;
454 }
455 
456 bool
radv_force_primitive_shading_rate(nir_shader * nir,struct radv_device * device)457 radv_force_primitive_shading_rate(nir_shader *nir, struct radv_device *device)
458 {
459    nir_function_impl *impl = nir_shader_get_entrypoint(nir);
460    bool progress = false;
461 
462    nir_builder b;
463    nir_builder_init(&b, impl);
464 
465    nir_foreach_block_reverse(block, impl) {
466       nir_foreach_instr_reverse(instr, block) {
467          if (instr->type != nir_instr_type_intrinsic)
468             continue;
469 
470          nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
471          if (intr->intrinsic != nir_intrinsic_store_deref)
472             continue;
473 
474          nir_variable *var = nir_intrinsic_get_var(intr, 0);
475          if (var->data.mode != nir_var_shader_out ||
476              var->data.location != VARYING_SLOT_POS)
477             continue;
478 
479          b.cursor = nir_after_instr(instr);
480 
481          nir_ssa_scalar scalar_idx = nir_ssa_scalar_resolved(intr->src[1].ssa, 3);
482 
483          /* Use coarse shading if the value of Pos.W can't be determined or if its value is != 1
484           * (typical for non-GUI elements).
485           */
486          if (!nir_ssa_scalar_is_const(scalar_idx) ||
487              nir_ssa_scalar_as_uint(scalar_idx) != 0x3f800000u) {
488 
489             var = nir_variable_create(nir, nir_var_shader_out, glsl_int_type(), "vrs rate");
490             var->data.location = VARYING_SLOT_PRIMITIVE_SHADING_RATE;
491             var->data.interpolation = INTERP_MODE_NONE;
492 
493             nir_ssa_def *vrs_rates = nir_load_force_vrs_rates_amd(&b);
494 
495             nir_ssa_def *pos_w = nir_channel(&b, intr->src[1].ssa, 3);
496             nir_ssa_def *val = nir_bcsel(&b, nir_fneu(&b, pos_w, nir_imm_float(&b, 1.0f)),
497                                              vrs_rates, nir_imm_int(&b, 0));
498 
499             nir_deref_instr *deref = nir_build_deref_var(&b, var);
500             nir_store_deref(&b, deref, val, 0x1);
501 
502             /* Update outputs_written to reflect that the pass added a new output. */
503             nir->info.outputs_written |= BITFIELD64_BIT(VARYING_SLOT_PRIMITIVE_SHADING_RATE);
504 
505             progress = true;
506             if (nir->info.stage == MESA_SHADER_VERTEX)
507                break;
508          }
509       }
510       if (nir->info.stage == MESA_SHADER_VERTEX && progress)
511          break;
512    }
513 
514    if (progress)
515       nir_metadata_preserve(impl, nir_metadata_block_index | nir_metadata_dominance);
516    else
517       nir_metadata_preserve(impl, nir_metadata_all);
518 
519    return progress;
520 }
521 
522 bool
radv_lower_fs_intrinsics(nir_shader * nir,const struct radv_pipeline_stage * fs_stage,const struct radv_pipeline_key * key)523 radv_lower_fs_intrinsics(nir_shader *nir, const struct radv_pipeline_stage *fs_stage,
524                          const struct radv_pipeline_key *key)
525 {
526    const struct radv_shader_info *info = &fs_stage->info;
527    const struct radv_shader_args *args = &fs_stage->args;
528    nir_function_impl *impl = nir_shader_get_entrypoint(nir);
529    bool progress = false;
530 
531    nir_builder b;
532    nir_builder_init(&b, impl);
533 
534    nir_foreach_block(block, impl) {
535       nir_foreach_instr_safe(instr, block) {
536          if (instr->type != nir_instr_type_intrinsic)
537             continue;
538 
539          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
540          b.cursor = nir_after_instr(&intrin->instr);
541 
542          switch (intrin->intrinsic) {
543          case nir_intrinsic_load_sample_mask_in: {
544             uint8_t log2_ps_iter_samples;
545 
546             if (info->ps.uses_sample_shading) {
547                log2_ps_iter_samples = util_logbase2(key->ps.num_samples);
548             } else {
549                log2_ps_iter_samples = key->ps.log2_ps_iter_samples;
550             }
551 
552             nir_ssa_def *sample_coverage =
553                nir_load_vector_arg_amd(&b, 1, .base = args->ac.sample_coverage.arg_index);
554 
555             nir_ssa_def *def = NULL;
556             if (log2_ps_iter_samples) {
557                /* gl_SampleMaskIn[0] = (SampleCoverage & (1 << gl_SampleID)). */
558                nir_ssa_def *sample_id = nir_load_sample_id(&b);
559                def = nir_iand(&b, sample_coverage, nir_ishl(&b, nir_imm_int(&b, 1u), sample_id));
560             } else {
561                def = sample_coverage;
562             }
563 
564             nir_ssa_def_rewrite_uses(&intrin->dest.ssa, def);
565 
566             nir_instr_remove(instr);
567             progress = true;
568             break;
569          }
570          case nir_intrinsic_load_frag_coord: {
571             if (!key->adjust_frag_coord_z)
572                continue;
573 
574             if (!(nir_ssa_def_components_read(&intrin->dest.ssa) & (1 << 2)))
575                continue;
576 
577             nir_ssa_def *frag_z = nir_channel(&b, &intrin->dest.ssa, 2);
578 
579             /* adjusted_frag_z = fddx_fine(frag_z) * 0.0625 + frag_z */
580             nir_ssa_def *adjusted_frag_z = nir_fddx_fine(&b, frag_z);
581             adjusted_frag_z = nir_ffma_imm1(&b, adjusted_frag_z, 0.0625f, frag_z);
582 
583             /* VRS Rate X = Ancillary[2:3] */
584             nir_ssa_def *ancillary =
585                nir_load_vector_arg_amd(&b, 1, .base = args->ac.ancillary.arg_index);
586             nir_ssa_def *x_rate = nir_ubfe_imm(&b, ancillary, 2, 2);
587 
588             /* xRate = xRate == 0x1 ? adjusted_frag_z : frag_z. */
589             nir_ssa_def *cond = nir_ieq_imm(&b, x_rate, 1);
590             frag_z = nir_bcsel(&b, cond, adjusted_frag_z, frag_z);
591 
592             nir_ssa_def *new_dest = nir_vector_insert_imm(&b, &intrin->dest.ssa, frag_z, 2);
593             nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa, new_dest, new_dest->parent_instr);
594 
595             progress = true;
596             break;
597          }
598          default:
599             break;
600          }
601       }
602    }
603 
604    if (progress)
605       nir_metadata_preserve(impl, nir_metadata_block_index | nir_metadata_dominance);
606    else
607       nir_metadata_preserve(impl, nir_metadata_all);
608 
609    return progress;
610 }
611 
612 /* Emulates NV_mesh_shader first_task using first_vertex. */
613 static bool
radv_lower_ms_workgroup_id(nir_shader * nir)614 radv_lower_ms_workgroup_id(nir_shader *nir)
615 {
616    nir_function_impl *impl = nir_shader_get_entrypoint(nir);
617    bool progress = false;
618    nir_builder b;
619    nir_builder_init(&b, impl);
620 
621    nir_foreach_block(block, impl) {
622       nir_foreach_instr_safe(instr, block) {
623          if (instr->type != nir_instr_type_intrinsic)
624             continue;
625 
626          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
627          if (intrin->intrinsic != nir_intrinsic_load_workgroup_id)
628             continue;
629 
630          progress = true;
631          b.cursor = nir_after_instr(instr);
632          nir_ssa_def *x = nir_channel(&b, &intrin->dest.ssa, 0);
633          nir_ssa_def *x_full = nir_iadd(&b, x, nir_load_first_vertex(&b));
634          nir_ssa_def *v = nir_vector_insert_imm(&b, &intrin->dest.ssa, x_full, 0);
635          nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa, v, v->parent_instr);
636       }
637    }
638 
639    nir_metadata preserved =
640       progress ? (nir_metadata_block_index | nir_metadata_dominance) : nir_metadata_all;
641    nir_metadata_preserve(impl, preserved);
642    return progress;
643 }
644 
645 static bool
is_sincos(const nir_instr * instr,const void * _)646 is_sincos(const nir_instr *instr, const void *_)
647 {
648    return instr->type == nir_instr_type_alu &&
649           (nir_instr_as_alu(instr)->op == nir_op_fsin || nir_instr_as_alu(instr)->op == nir_op_fcos);
650 }
651 
652 static nir_ssa_def *
lower_sincos(struct nir_builder * b,nir_instr * instr,void * _)653 lower_sincos(struct nir_builder *b, nir_instr *instr, void *_)
654 {
655    nir_alu_instr *sincos = nir_instr_as_alu(instr);
656    nir_ssa_def *src = nir_fmul_imm(b, nir_ssa_for_alu_src(b, sincos, 0), 0.15915493667125702);
657    return sincos->op == nir_op_fsin ? nir_fsin_amd(b, src) : nir_fcos_amd(b, src);
658 }
659 
660 static bool
is_not_xfb_output(nir_variable * var,void * data)661 is_not_xfb_output(nir_variable *var, void *data)
662 {
663    if (var->data.mode != nir_var_shader_out)
664       return true;
665 
666    return !var->data.explicit_xfb_buffer &&
667           !var->data.explicit_xfb_stride;
668 }
669 
670 nir_shader *
radv_shader_spirv_to_nir(struct radv_device * device,const struct radv_pipeline_stage * stage,const struct radv_pipeline_key * key)671 radv_shader_spirv_to_nir(struct radv_device *device, const struct radv_pipeline_stage *stage,
672                          const struct radv_pipeline_key *key)
673 {
674    unsigned subgroup_size = 64, ballot_bit_size = 64;
675    if (key->cs.compute_subgroup_size) {
676       /* Only compute shaders currently support requiring a
677        * specific subgroup size.
678        */
679       assert(stage->stage == MESA_SHADER_COMPUTE);
680       subgroup_size = key->cs.compute_subgroup_size;
681       ballot_bit_size = key->cs.compute_subgroup_size;
682    }
683 
684    nir_shader *nir;
685 
686    if (stage->internal_nir) {
687       /* Some things such as our meta clear/blit code will give us a NIR
688        * shader directly.  In that case, we just ignore the SPIR-V entirely
689        * and just use the NIR shader.  We don't want to alter meta and RT
690        * shaders IR directly, so clone it first. */
691       nir = nir_shader_clone(NULL, stage->internal_nir);
692       nir_validate_shader(nir, "in internal shader");
693 
694       assert(exec_list_length(&nir->functions) == 1);
695    } else {
696       uint32_t *spirv = (uint32_t *)stage->spirv.data;
697       assert(stage->spirv.size % 4 == 0);
698 
699       bool dump_meta = device->instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS;
700       if ((device->instance->debug_flags & RADV_DEBUG_DUMP_SPIRV) &&
701           (!device->app_shaders_internal || dump_meta))
702          radv_print_spirv(stage->spirv.data, stage->spirv.size, stderr);
703 
704       uint32_t num_spec_entries = 0;
705       struct nir_spirv_specialization *spec_entries =
706          vk_spec_info_to_nir_spirv(stage->spec_info, &num_spec_entries);
707       struct radv_shader_debug_data spirv_debug_data = {
708          .device = device,
709          .object = stage->spirv.object,
710       };
711       const struct spirv_to_nir_options spirv_options = {
712          .caps =
713             {
714                .amd_fragment_mask = true,
715                .amd_gcn_shader = true,
716                .amd_image_gather_bias_lod = true,
717                .amd_image_read_write_lod = true,
718                .amd_shader_ballot = true,
719                .amd_shader_explicit_vertex_parameter = true,
720                .amd_trinary_minmax = true,
721                .demote_to_helper_invocation = true,
722                .derivative_group = true,
723                .descriptor_array_dynamic_indexing = true,
724                .descriptor_array_non_uniform_indexing = true,
725                .descriptor_indexing = true,
726                .device_group = true,
727                .draw_parameters = true,
728                .float_controls = true,
729                .float16 = device->physical_device->rad_info.has_packed_math_16bit,
730                .float32_atomic_add = true,
731                .float32_atomic_min_max = true,
732                .float64 = true,
733                .float64_atomic_min_max = true,
734                .geometry_streams = true,
735                .groups = true,
736                .image_atomic_int64 = true,
737                .image_ms_array = true,
738                .image_read_without_format = true,
739                .image_write_without_format = true,
740                .int8 = true,
741                .int16 = true,
742                .int64 = true,
743                .int64_atomics = true,
744                .integer_functions2 = true,
745                .mesh_shading_nv = true,
746                .min_lod = true,
747                .multiview = true,
748                .physical_storage_buffer_address = true,
749                .post_depth_coverage = true,
750                .ray_cull_mask = true,
751                .ray_query = true,
752                .ray_tracing = true,
753                .ray_traversal_primitive_culling = true,
754                .runtime_descriptor_array = true,
755                .shader_clock = true,
756                .shader_viewport_index_layer = true,
757                .sparse_residency = true,
758                .stencil_export = true,
759                .storage_8bit = true,
760                .storage_16bit = true,
761                .storage_image_ms = true,
762                .subgroup_arithmetic = true,
763                .subgroup_ballot = true,
764                .subgroup_basic = true,
765                .subgroup_quad = true,
766                .subgroup_shuffle = true,
767                .subgroup_uniform_control_flow = true,
768                .subgroup_vote = true,
769                .tessellation = true,
770                .transform_feedback = true,
771                .variable_pointers = true,
772                .vk_memory_model = true,
773                .vk_memory_model_device_scope = true,
774                .fragment_shading_rate = device->physical_device->rad_info.gfx_level >= GFX10_3,
775                .workgroup_memory_explicit_layout = true,
776             },
777          .ubo_addr_format = nir_address_format_vec2_index_32bit_offset,
778          .ssbo_addr_format = nir_address_format_vec2_index_32bit_offset,
779          .phys_ssbo_addr_format = nir_address_format_64bit_global,
780          .push_const_addr_format = nir_address_format_logical,
781          .shared_addr_format = nir_address_format_32bit_offset,
782          .constant_addr_format = nir_address_format_64bit_global,
783          .use_deref_buffer_array_length = true,
784          .debug =
785             {
786                .func = radv_spirv_nir_debug,
787                .private_data = &spirv_debug_data,
788             },
789       };
790       nir = spirv_to_nir(spirv, stage->spirv.size / 4, spec_entries, num_spec_entries, stage->stage,
791                          stage->entrypoint, &spirv_options,
792                          &device->physical_device->nir_options[stage->stage]);
793       nir->info.internal |= device->app_shaders_internal;
794       assert(nir->info.stage == stage->stage);
795       nir_validate_shader(nir, "after spirv_to_nir");
796 
797       free(spec_entries);
798 
799       const struct nir_lower_sysvals_to_varyings_options sysvals_to_varyings = {
800          .point_coord = true,
801       };
802       NIR_PASS_V(nir, nir_lower_sysvals_to_varyings, &sysvals_to_varyings);
803 
804       /* We have to lower away local constant initializers right before we
805        * inline functions.  That way they get properly initialized at the top
806        * of the function and not at the top of its caller.
807        */
808       NIR_PASS(_, nir, nir_lower_variable_initializers, nir_var_function_temp);
809       NIR_PASS(_, nir, nir_lower_returns);
810       bool progress = false;
811       NIR_PASS(progress, nir, nir_inline_functions);
812       if (progress) {
813          NIR_PASS(_, nir, nir_opt_copy_prop_vars);
814          NIR_PASS(_, nir, nir_copy_prop);
815       }
816       NIR_PASS(_, nir, nir_opt_deref);
817 
818       /* Pick off the single entrypoint that we want */
819       foreach_list_typed_safe(nir_function, func, node, &nir->functions)
820       {
821          if (func->is_entrypoint)
822             func->name = ralloc_strdup(func, "main");
823          else
824             exec_node_remove(&func->node);
825       }
826       assert(exec_list_length(&nir->functions) == 1);
827 
828       /* Make sure we lower constant initializers on output variables so that
829        * nir_remove_dead_variables below sees the corresponding stores
830        */
831       NIR_PASS(_, nir, nir_lower_variable_initializers, nir_var_shader_out);
832 
833       /* Now that we've deleted all but the main function, we can go ahead and
834        * lower the rest of the constant initializers.
835        */
836       NIR_PASS(_, nir, nir_lower_variable_initializers, ~0);
837 
838       /* Split member structs.  We do this before lower_io_to_temporaries so that
839        * it doesn't lower system values to temporaries by accident.
840        */
841       NIR_PASS(_, nir, nir_split_var_copies);
842       NIR_PASS(_, nir, nir_split_per_member_structs);
843 
844       if (nir->info.stage == MESA_SHADER_FRAGMENT)
845          NIR_PASS(_, nir, nir_lower_io_to_vector, nir_var_shader_out);
846       if (nir->info.stage == MESA_SHADER_FRAGMENT)
847          NIR_PASS(_, nir, nir_lower_input_attachments,
848                   &(nir_input_attachment_options){
849                      .use_fragcoord_sysval = true,
850                      .use_layer_id_sysval = false,
851                   });
852 
853       nir_remove_dead_variables_options dead_vars_opts = {
854          .can_remove_var = is_not_xfb_output,
855       };
856       NIR_PASS(_, nir, nir_remove_dead_variables,
857                nir_var_shader_in | nir_var_shader_out | nir_var_system_value | nir_var_mem_shared,
858                &dead_vars_opts);
859 
860       /* Variables can make nir_propagate_invariant more conservative
861        * than it needs to be.
862        */
863       NIR_PASS(_, nir, nir_lower_global_vars_to_local);
864       NIR_PASS(_, nir, nir_lower_vars_to_ssa);
865 
866       NIR_PASS(_, nir, nir_propagate_invariant, key->invariant_geom);
867 
868       NIR_PASS(_, nir, nir_lower_clip_cull_distance_arrays);
869 
870       if (nir->info.stage == MESA_SHADER_VERTEX ||
871           nir->info.stage == MESA_SHADER_TESS_EVAL ||
872           nir->info.stage == MESA_SHADER_GEOMETRY)
873          NIR_PASS_V(nir, nir_shader_gather_xfb_info);
874 
875       NIR_PASS(_, nir, nir_lower_discard_or_demote, key->ps.lower_discard_to_demote);
876 
877       nir_lower_doubles_options lower_doubles = nir->options->lower_doubles_options;
878 
879       if (device->physical_device->rad_info.gfx_level == GFX6) {
880          /* GFX6 doesn't support v_floor_f64 and the precision
881           * of v_fract_f64 which is used to implement 64-bit
882           * floor is less than what Vulkan requires.
883           */
884          lower_doubles |= nir_lower_dfloor;
885       }
886 
887       NIR_PASS(_, nir, nir_lower_doubles, NULL, lower_doubles);
888 
889       NIR_PASS(_, nir, nir_shader_lower_instructions, &is_sincos, &lower_sincos, NULL);
890    }
891 
892    NIR_PASS(_, nir, nir_lower_system_values);
893    nir_lower_compute_system_values_options csv_options = {
894       /* Mesh shaders run as NGG which can implement local_invocation_index from
895        * the wave ID in merged_wave_info, but they don't have local_invocation_ids.
896        */
897       .lower_cs_local_id_to_index = nir->info.stage == MESA_SHADER_MESH,
898       .lower_local_invocation_index = nir->info.stage == MESA_SHADER_COMPUTE &&
899                                       ((nir->info.workgroup_size[0] == 1) +
900                                        (nir->info.workgroup_size[1] == 1) +
901                                        (nir->info.workgroup_size[2] == 1)) == 2,
902    };
903    NIR_PASS(_, nir, nir_lower_compute_system_values, &csv_options);
904 
905    if (nir->info.stage == MESA_SHADER_MESH) {
906       /* NV_mesh_shader: include first_task (aka. first_vertex) in workgroup ID. */
907       NIR_PASS(_, nir, radv_lower_ms_workgroup_id);
908 
909       /* Mesh shaders only have a 1D "vertex index" which we use
910        * as "workgroup index" to emulate the 3D workgroup ID.
911        */
912       nir_lower_compute_system_values_options o = {
913          .lower_workgroup_id_to_index = true,
914       };
915       NIR_PASS(_, nir, nir_lower_compute_system_values, &o);
916    }
917 
918    /* Vulkan uses the separate-shader linking model */
919    nir->info.separate_shader = true;
920 
921    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
922 
923    if (nir->info.ray_queries > 0) {
924       NIR_PASS(_, nir, nir_opt_ray_queries);
925       NIR_PASS(_, nir, radv_nir_lower_ray_queries, device);
926    }
927 
928    static const nir_lower_tex_options tex_options = {
929       .lower_txp = ~0,
930       .lower_txf_offset = true,
931       .lower_tg4_offsets = true,
932       .lower_txs_cube_array = true,
933       .lower_to_fragment_fetch_amd = true,
934       .lower_lod_zero_width = true,
935       .lower_invalid_implicit_lod = true,
936       .lower_array_layer_round_even = true,
937    };
938 
939    NIR_PASS(_, nir, nir_lower_tex, &tex_options);
940 
941    static const nir_lower_image_options image_options = {
942       .lower_cube_size = true,
943    };
944 
945    NIR_PASS(_, nir, nir_lower_image, &image_options);
946 
947    NIR_PASS(_, nir, nir_lower_vars_to_ssa);
948 
949    if (nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_GEOMETRY ||
950        nir->info.stage == MESA_SHADER_FRAGMENT) {
951       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, true);
952    } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
953       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, false);
954    }
955 
956    NIR_PASS(_, nir, nir_split_var_copies);
957 
958    NIR_PASS(_, nir, nir_lower_global_vars_to_local);
959    NIR_PASS(_, nir, nir_remove_dead_variables, nir_var_function_temp, NULL);
960    bool gfx7minus = device->physical_device->rad_info.gfx_level <= GFX7;
961    NIR_PASS(_, nir, nir_lower_subgroups,
962             &(struct nir_lower_subgroups_options){
963                .subgroup_size = subgroup_size,
964                .ballot_bit_size = ballot_bit_size,
965                .ballot_components = 1,
966                .lower_to_scalar = 1,
967                .lower_subgroup_masks = 1,
968                .lower_relative_shuffle = 1,
969                .lower_shuffle_to_32bit = 1,
970                .lower_vote_eq = 1,
971                .lower_quad_broadcast_dynamic = 1,
972                .lower_quad_broadcast_dynamic_to_const = gfx7minus,
973                .lower_shuffle_to_swizzle_amd = 1,
974             });
975 
976    NIR_PASS(_, nir, nir_lower_load_const_to_scalar);
977    NIR_PASS(_, nir, nir_opt_shrink_stores, !device->instance->disable_shrink_image_store);
978 
979    if (!key->optimisations_disabled)
980       radv_optimize_nir(nir, false, true);
981 
982    /* We call nir_lower_var_copies() after the first radv_optimize_nir()
983     * to remove any copies introduced by nir_opt_find_array_copies().
984     */
985    NIR_PASS(_, nir, nir_lower_var_copies);
986 
987    unsigned lower_flrp = (nir->options->lower_flrp16 ? 16 : 0) |
988                          (nir->options->lower_flrp32 ? 32 : 0) |
989                          (nir->options->lower_flrp64 ? 64 : 0);
990    if (lower_flrp != 0) {
991       bool progress = false;
992       NIR_PASS(progress, nir, nir_lower_flrp, lower_flrp, false /* always precise */);
993       if (progress)
994          NIR_PASS(_, nir, nir_opt_constant_folding);
995    }
996 
997    const nir_opt_access_options opt_access_options = {
998       .is_vulkan = true,
999       .infer_non_readable = true,
1000    };
1001    NIR_PASS(_, nir, nir_opt_access, &opt_access_options);
1002 
1003    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_push_const, nir_address_format_32bit_offset);
1004 
1005    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ubo | nir_var_mem_ssbo,
1006             nir_address_format_vec2_index_32bit_offset);
1007 
1008    NIR_PASS(_, nir, lower_intrinsics, key);
1009 
1010    /* Lower deref operations for compute shared memory. */
1011    if (nir->info.stage == MESA_SHADER_COMPUTE ||
1012        nir->info.stage == MESA_SHADER_TASK ||
1013        nir->info.stage == MESA_SHADER_MESH) {
1014       nir_variable_mode var_modes = nir_var_mem_shared;
1015 
1016       if (nir->info.stage == MESA_SHADER_TASK ||
1017           nir->info.stage == MESA_SHADER_MESH)
1018          var_modes |= nir_var_mem_task_payload;
1019 
1020       if (!nir->info.shared_memory_explicit_layout) {
1021          NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, var_modes, shared_var_info);
1022       }
1023       NIR_PASS(_, nir, nir_lower_explicit_io, var_modes, nir_address_format_32bit_offset);
1024 
1025       if (nir->info.zero_initialize_shared_memory && nir->info.shared_size > 0) {
1026          const unsigned chunk_size = 16; /* max single store size */
1027          const unsigned shared_size = ALIGN(nir->info.shared_size, chunk_size);
1028          NIR_PASS(_, nir, nir_zero_initialize_shared_memory, shared_size, chunk_size);
1029       }
1030    }
1031 
1032    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_global | nir_var_mem_constant,
1033             nir_address_format_64bit_global);
1034 
1035    /* Lower large variables that are always constant with load_constant
1036     * intrinsics, which get turned into PC-relative loads from a data
1037     * section next to the shader.
1038     */
1039    NIR_PASS(_, nir, nir_opt_large_constants, glsl_get_natural_size_align_bytes, 16);
1040 
1041    /* Lower primitive shading rate to match HW requirements. */
1042    if ((nir->info.stage == MESA_SHADER_VERTEX ||
1043         nir->info.stage == MESA_SHADER_GEOMETRY ||
1044         nir->info.stage == MESA_SHADER_MESH) &&
1045        nir->info.outputs_written & BITFIELD64_BIT(VARYING_SLOT_PRIMITIVE_SHADING_RATE)) {
1046       /* Lower primitive shading rate to match HW requirements. */
1047       NIR_PASS(_, nir, radv_lower_primitive_shading_rate,
1048                device->physical_device->rad_info.gfx_level);
1049    }
1050 
1051    /* Indirect lowering must be called after the radv_optimize_nir() loop
1052     * has been called at least once. Otherwise indirect lowering can
1053     * bloat the instruction count of the loop and cause it to be
1054     * considered too large for unrolling.
1055     */
1056    if (ac_nir_lower_indirect_derefs(nir, device->physical_device->rad_info.gfx_level) &&
1057        !key->optimisations_disabled && nir->info.stage != MESA_SHADER_COMPUTE) {
1058       /* Optimize the lowered code before the linking optimizations. */
1059       radv_optimize_nir(nir, false, false);
1060    }
1061 
1062 
1063    return nir;
1064 }
1065 
1066 static int
type_size_vec4(const struct glsl_type * type,bool bindless)1067 type_size_vec4(const struct glsl_type *type, bool bindless)
1068 {
1069    return glsl_count_attribute_slots(type, false);
1070 }
1071 
1072 static nir_variable *
find_layer_in_var(nir_shader * nir)1073 find_layer_in_var(nir_shader *nir)
1074 {
1075    nir_variable *var = nir_find_variable_with_location(nir, nir_var_shader_in, VARYING_SLOT_LAYER);
1076    if (var != NULL)
1077       return var;
1078 
1079    var = nir_variable_create(nir, nir_var_shader_in, glsl_int_type(), "layer id");
1080    var->data.location = VARYING_SLOT_LAYER;
1081    var->data.interpolation = INTERP_MODE_FLAT;
1082    return var;
1083 }
1084 
1085 /* We use layered rendering to implement multiview, which means we need to map
1086  * view_index to gl_Layer. The code generates a load from the layer_id sysval,
1087  * but since we don't have a way to get at this information from the fragment
1088  * shader, we also need to lower this to the gl_Layer varying.  This pass
1089  * lowers both to a varying load from the LAYER slot, before lowering io, so
1090  * that nir_assign_var_locations() will give the LAYER varying the correct
1091  * driver_location.
1092  */
1093 
1094 static bool
lower_view_index(nir_shader * nir,bool per_primitive)1095 lower_view_index(nir_shader *nir, bool per_primitive)
1096 {
1097    bool progress = false;
1098    nir_function_impl *entry = nir_shader_get_entrypoint(nir);
1099    nir_builder b;
1100    nir_builder_init(&b, entry);
1101 
1102    nir_variable *layer = NULL;
1103    nir_foreach_block (block, entry) {
1104       nir_foreach_instr_safe (instr, block) {
1105          if (instr->type != nir_instr_type_intrinsic)
1106             continue;
1107 
1108          nir_intrinsic_instr *load = nir_instr_as_intrinsic(instr);
1109          if (load->intrinsic != nir_intrinsic_load_view_index)
1110             continue;
1111 
1112          if (!layer)
1113             layer = find_layer_in_var(nir);
1114 
1115          layer->data.per_primitive = per_primitive;
1116          b.cursor = nir_before_instr(instr);
1117          nir_ssa_def *def = nir_load_var(&b, layer);
1118          nir_ssa_def_rewrite_uses(&load->dest.ssa, def);
1119 
1120          /* Update inputs_read to reflect that the pass added a new input. */
1121          nir->info.inputs_read |= VARYING_BIT_LAYER;
1122          if (per_primitive)
1123             nir->info.per_primitive_inputs |= VARYING_BIT_LAYER;
1124 
1125          nir_instr_remove(instr);
1126          progress = true;
1127       }
1128    }
1129 
1130    if (progress)
1131       nir_metadata_preserve(entry, nir_metadata_block_index | nir_metadata_dominance);
1132    else
1133       nir_metadata_preserve(entry, nir_metadata_all);
1134 
1135    return progress;
1136 }
1137 
1138 void
radv_lower_io(struct radv_device * device,nir_shader * nir,bool is_mesh_shading)1139 radv_lower_io(struct radv_device *device, nir_shader *nir, bool is_mesh_shading)
1140 {
1141    if (nir->info.stage == MESA_SHADER_COMPUTE)
1142       return;
1143 
1144    if (nir->info.stage == MESA_SHADER_FRAGMENT) {
1145       NIR_PASS(_, nir, lower_view_index, is_mesh_shading);
1146       nir_assign_io_var_locations(nir, nir_var_shader_in, &nir->num_inputs, MESA_SHADER_FRAGMENT);
1147    }
1148 
1149    NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out, type_size_vec4,
1150             nir_lower_io_lower_64bit_to_32);
1151 
1152    /* This pass needs actual constants */
1153    NIR_PASS(_, nir, nir_opt_constant_folding);
1154 
1155    NIR_PASS(_, nir, nir_io_add_const_offset_to_base, nir_var_shader_in | nir_var_shader_out);
1156 }
1157 
1158 bool
radv_lower_io_to_mem(struct radv_device * device,struct radv_pipeline_stage * stage,const struct radv_pipeline_key * pl_key)1159 radv_lower_io_to_mem(struct radv_device *device, struct radv_pipeline_stage *stage,
1160                      const struct radv_pipeline_key *pl_key)
1161 {
1162    const struct radv_shader_info *info = &stage->info;
1163    nir_shader *nir = stage->nir;
1164 
1165    if (nir->info.stage == MESA_SHADER_VERTEX) {
1166       if (info->vs.as_ls) {
1167          NIR_PASS_V(nir, ac_nir_lower_ls_outputs_to_mem, NULL, info->vs.tcs_in_out_eq,
1168                     info->vs.tcs_temp_only_input_mask);
1169          return true;
1170       } else if (info->vs.as_es) {
1171          NIR_PASS_V(nir, ac_nir_lower_es_outputs_to_mem, NULL,
1172                     device->physical_device->rad_info.gfx_level,
1173                     info->vs.num_linked_outputs * 16u);
1174          return true;
1175       }
1176    } else if (nir->info.stage == MESA_SHADER_TESS_CTRL) {
1177       NIR_PASS_V(nir, ac_nir_lower_hs_inputs_to_mem, NULL, info->vs.tcs_in_out_eq);
1178       NIR_PASS_V(nir, ac_nir_lower_hs_outputs_to_mem, NULL,
1179                  device->physical_device->rad_info.gfx_level,
1180                  info->tcs.tes_reads_tess_factors, info->tcs.tes_inputs_read,
1181                  info->tcs.tes_patch_inputs_read, info->tcs.num_linked_outputs,
1182                  info->tcs.num_linked_patch_outputs, info->wave_size,
1183                  false, false, true);
1184 
1185       return true;
1186    } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
1187       NIR_PASS_V(nir, ac_nir_lower_tes_inputs_to_mem, NULL);
1188 
1189       if (info->tes.as_es) {
1190          NIR_PASS_V(nir, ac_nir_lower_es_outputs_to_mem, NULL,
1191                     device->physical_device->rad_info.gfx_level,
1192                     info->tes.num_linked_outputs * 16u);
1193       }
1194 
1195       return true;
1196    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
1197       NIR_PASS_V(nir, ac_nir_lower_gs_inputs_to_mem, NULL,
1198                  device->physical_device->rad_info.gfx_level, false);
1199       return true;
1200    } else if (nir->info.stage == MESA_SHADER_TASK) {
1201       ac_nir_apply_first_task_to_task_shader(nir);
1202       ac_nir_lower_task_outputs_to_mem(nir, AC_TASK_PAYLOAD_ENTRY_BYTES,
1203                                        device->physical_device->task_info.num_entries);
1204       return true;
1205    } else if (nir->info.stage == MESA_SHADER_MESH) {
1206       ac_nir_lower_mesh_inputs_to_mem(nir, AC_TASK_PAYLOAD_ENTRY_BYTES,
1207                                       device->physical_device->task_info.num_entries);
1208       return true;
1209    }
1210 
1211    return false;
1212 }
1213 
1214 bool
radv_consider_culling(const struct radv_physical_device * pdevice,struct nir_shader * nir,uint64_t ps_inputs_read,unsigned num_vertices_per_primitive,const struct radv_shader_info * info)1215 radv_consider_culling(const struct radv_physical_device *pdevice, struct nir_shader *nir, uint64_t ps_inputs_read,
1216                       unsigned num_vertices_per_primitive, const struct radv_shader_info *info)
1217 {
1218    /* Culling doesn't make sense for meta shaders. */
1219    if (is_meta_shader(nir))
1220       return false;
1221 
1222    /* We don't support culling with multiple viewports yet. */
1223    if (nir->info.outputs_written & (VARYING_BIT_VIEWPORT | VARYING_BIT_VIEWPORT_MASK))
1224       return false;
1225 
1226    /* We don't support culling with vertex shader prologs. */
1227    if (info->vs.has_prolog)
1228       return false;
1229 
1230    if (!pdevice->use_ngg_culling)
1231       return false;
1232 
1233    /* Shader based culling efficiency can depend on PS throughput.
1234     * Estimate an upper limit for PS input param count based on GPU info.
1235     */
1236    unsigned max_ps_params;
1237    unsigned max_render_backends = pdevice->rad_info.max_render_backends;
1238    unsigned max_se = pdevice->rad_info.max_se;
1239 
1240    if (max_render_backends / max_se == 4)
1241       max_ps_params = 6; /* Navi21 and other GFX10.3 dGPUs. */
1242    else
1243       max_ps_params = 4; /* Navi 1x. */
1244 
1245    /* TODO: consider other heuristics here, such as PS execution time */
1246    if (util_bitcount64(ps_inputs_read & ~VARYING_BIT_POS) > max_ps_params)
1247       return false;
1248 
1249    /* Only triangle culling is supported. */
1250    if (num_vertices_per_primitive != 3)
1251       return false;
1252 
1253    /* When the shader writes memory, it is difficult to guarantee correctness.
1254     * Future work:
1255     * - if only write-only SSBOs are used
1256     * - if we can prove that non-position outputs don't rely on memory stores
1257     * then may be okay to keep the memory stores in the 1st shader part, and delete them from the 2nd.
1258     */
1259    if (nir->info.writes_memory)
1260       return false;
1261 
1262    /* When the shader relies on the subgroup invocation ID, we'd break it, because the ID changes after the culling.
1263     * Future work: try to save this to LDS and reload, but it can still be broken in subtle ways.
1264     */
1265    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_SUBGROUP_INVOCATION))
1266       return false;
1267 
1268    return true;
1269 }
1270 
radv_lower_ngg(struct radv_device * device,struct radv_pipeline_stage * ngg_stage,const struct radv_pipeline_key * pl_key)1271 void radv_lower_ngg(struct radv_device *device, struct radv_pipeline_stage *ngg_stage,
1272                     const struct radv_pipeline_key *pl_key)
1273 {
1274    const struct radv_shader_info *info = &ngg_stage->info;
1275    nir_shader *nir = ngg_stage->nir;
1276 
1277    assert(nir->info.stage == MESA_SHADER_VERTEX ||
1278           nir->info.stage == MESA_SHADER_TESS_EVAL ||
1279           nir->info.stage == MESA_SHADER_GEOMETRY ||
1280           nir->info.stage == MESA_SHADER_MESH);
1281 
1282    const struct gfx10_ngg_info *ngg_info = &info->ngg_info;
1283    unsigned num_vertices_per_prim = 3;
1284 
1285    /* Get the number of vertices per input primitive */
1286    if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
1287       if (nir->info.tess.point_mode)
1288          num_vertices_per_prim = 1;
1289       else if (nir->info.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES)
1290          num_vertices_per_prim = 2;
1291 
1292       /* Manually mark the primitive ID used, so the shader can repack it. */
1293       if (info->tes.outinfo.export_prim_id)
1294          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_PRIMITIVE_ID);
1295 
1296    } else if (nir->info.stage == MESA_SHADER_VERTEX) {
1297       /* Need to add 1, because: V_028A6C_POINTLIST=0, V_028A6C_LINESTRIP=1, V_028A6C_TRISTRIP=2, etc. */
1298       num_vertices_per_prim = si_conv_prim_to_gs_out(pl_key->vs.topology) + 1;
1299 
1300       /* Manually mark the instance ID used, so the shader can repack it. */
1301       if (pl_key->vs.instance_rate_inputs)
1302          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID);
1303 
1304    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
1305       num_vertices_per_prim = nir->info.gs.vertices_in;
1306    } else if (nir->info.stage == MESA_SHADER_MESH) {
1307       if (nir->info.mesh.primitive_type == SHADER_PRIM_POINTS)
1308          num_vertices_per_prim = 1;
1309       else if (nir->info.mesh.primitive_type == SHADER_PRIM_LINES)
1310          num_vertices_per_prim = 2;
1311       else
1312          assert(nir->info.mesh.primitive_type == SHADER_PRIM_TRIANGLES);
1313    } else {
1314       unreachable("NGG needs to be VS, TES or GS.");
1315    }
1316 
1317    /* Invocations that process an input vertex */
1318    unsigned max_vtx_in = MIN2(256, ngg_info->enable_vertex_grouping ? ngg_info->hw_max_esverts : num_vertices_per_prim * ngg_info->max_gsprims);
1319 
1320    if (nir->info.stage == MESA_SHADER_VERTEX ||
1321        nir->info.stage == MESA_SHADER_TESS_EVAL) {
1322       bool export_prim_id;
1323 
1324       assert(info->is_ngg);
1325 
1326       if (info->has_ngg_culling)
1327          radv_optimize_nir_algebraic(nir, false);
1328 
1329       if (nir->info.stage == MESA_SHADER_VERTEX) {
1330          export_prim_id = info->vs.outinfo.export_prim_id;
1331       } else {
1332          export_prim_id = info->tes.outinfo.export_prim_id;
1333       }
1334 
1335       NIR_PASS_V(nir, ac_nir_lower_ngg_nogs,
1336                  device->physical_device->rad_info.family,
1337                  max_vtx_in, num_vertices_per_prim,
1338                  info->workgroup_size, info->wave_size, info->has_ngg_culling,
1339                  info->has_ngg_early_prim_export, info->is_ngg_passthrough, export_prim_id,
1340                  pl_key->vs.provoking_vtx_last, false, pl_key->primitives_generated_query,
1341                  pl_key->vs.instance_rate_inputs);
1342 
1343       /* Increase ESGS ring size so the LLVM binary contains the correct LDS size. */
1344       ngg_stage->info.ngg_info.esgs_ring_size = nir->info.shared_size;
1345    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
1346       assert(info->is_ngg);
1347       NIR_PASS_V(nir, ac_nir_lower_ngg_gs, info->wave_size, info->workgroup_size,
1348                  info->ngg_info.esgs_ring_size, info->gs.gsvs_vertex_size,
1349                  info->ngg_info.ngg_emit_size * 4u, pl_key->vs.provoking_vtx_last);
1350    } else if (nir->info.stage == MESA_SHADER_MESH) {
1351       bool scratch_ring = false;
1352       NIR_PASS_V(nir, ac_nir_lower_ngg_ms, &scratch_ring, info->wave_size, pl_key->has_multiview_view_index);
1353       ngg_stage->info.ms.needs_ms_scratch_ring = scratch_ring;
1354    } else {
1355       unreachable("invalid SW stage passed to radv_lower_ngg");
1356    }
1357 }
1358 
1359 static unsigned
get_size_class(unsigned size,bool round_up)1360 get_size_class(unsigned size, bool round_up)
1361 {
1362    size = round_up ? util_logbase2_ceil(size) : util_logbase2(size);
1363    unsigned size_class =
1364       MAX2(size, RADV_SHADER_ALLOC_MIN_SIZE_CLASS) - RADV_SHADER_ALLOC_MIN_SIZE_CLASS;
1365    return MIN2(size_class, RADV_SHADER_ALLOC_NUM_FREE_LISTS - 1);
1366 }
1367 
1368 static void
remove_hole(struct radv_device * device,union radv_shader_arena_block * hole)1369 remove_hole(struct radv_device *device, union radv_shader_arena_block *hole)
1370 {
1371    unsigned size_class = get_size_class(hole->size, false);
1372    list_del(&hole->freelist);
1373    if (list_is_empty(&device->shader_free_lists[size_class]))
1374       device->shader_free_list_mask &= ~(1u << size_class);
1375 }
1376 
1377 static void
add_hole(struct radv_device * device,union radv_shader_arena_block * hole)1378 add_hole(struct radv_device *device, union radv_shader_arena_block *hole)
1379 {
1380    unsigned size_class = get_size_class(hole->size, false);
1381    list_addtail(&hole->freelist, &device->shader_free_lists[size_class]);
1382    device->shader_free_list_mask |= 1u << size_class;
1383 }
1384 
1385 static union radv_shader_arena_block *
alloc_block_obj(struct radv_device * device)1386 alloc_block_obj(struct radv_device *device)
1387 {
1388    if (!list_is_empty(&device->shader_block_obj_pool)) {
1389       union radv_shader_arena_block *block =
1390          list_first_entry(&device->shader_block_obj_pool, union radv_shader_arena_block, pool);
1391       list_del(&block->pool);
1392       return block;
1393    }
1394 
1395    return malloc(sizeof(union radv_shader_arena_block));
1396 }
1397 
1398 static void
free_block_obj(struct radv_device * device,union radv_shader_arena_block * block)1399 free_block_obj(struct radv_device *device, union radv_shader_arena_block *block)
1400 {
1401    list_add(&block->pool, &device->shader_block_obj_pool);
1402 }
1403 
1404 /* Segregated fit allocator, implementing a good-fit allocation policy.
1405  *
1406  * This is an variation of sequential fit allocation with several lists of free blocks ("holes")
1407  * instead of one. Each list of holes only contains holes of a certain range of sizes, so holes that
1408  * are too small can easily be ignored while allocating. Because this also ignores holes that are
1409  * larger than necessary (approximating best-fit allocation), this could be described as a
1410  * "good-fit" allocator.
1411  *
1412  * Typically, shaders are allocated and only free'd when the device is destroyed. For this pattern,
1413  * this should allocate blocks for shaders fast and with no fragmentation, while still allowing
1414  * free'd memory to be re-used.
1415  */
1416 union radv_shader_arena_block *
radv_alloc_shader_memory(struct radv_device * device,uint32_t size,void * ptr)1417 radv_alloc_shader_memory(struct radv_device *device, uint32_t size, void *ptr)
1418 {
1419    size = align(size, RADV_SHADER_ALLOC_ALIGNMENT);
1420 
1421    mtx_lock(&device->shader_arena_mutex);
1422 
1423    /* Try to use an existing hole. Unless the shader is very large, this should only have to look
1424     * at the first one available.
1425     */
1426    unsigned free_list_mask = BITFIELD_MASK(RADV_SHADER_ALLOC_NUM_FREE_LISTS);
1427    unsigned size_class =
1428       ffs(device->shader_free_list_mask & (free_list_mask << get_size_class(size, true)));
1429    if (size_class) {
1430       size_class--;
1431 
1432       list_for_each_entry(union radv_shader_arena_block, hole,
1433                           &device->shader_free_lists[size_class], freelist)
1434       {
1435          if (hole->size < size)
1436             continue;
1437 
1438          assert(hole->offset % RADV_SHADER_ALLOC_ALIGNMENT == 0);
1439 
1440          if (size == hole->size) {
1441             remove_hole(device, hole);
1442             hole->freelist.next = ptr;
1443             mtx_unlock(&device->shader_arena_mutex);
1444             return hole;
1445          } else {
1446             union radv_shader_arena_block *alloc = alloc_block_obj(device);
1447             if (!alloc) {
1448                mtx_unlock(&device->shader_arena_mutex);
1449                return NULL;
1450             }
1451             list_addtail(&alloc->list, &hole->list);
1452             alloc->freelist.prev = NULL;
1453             alloc->freelist.next = ptr;
1454             alloc->arena = hole->arena;
1455             alloc->offset = hole->offset;
1456             alloc->size = size;
1457 
1458             remove_hole(device, hole);
1459             hole->offset += size;
1460             hole->size -= size;
1461             add_hole(device, hole);
1462 
1463             mtx_unlock(&device->shader_arena_mutex);
1464             return alloc;
1465          }
1466       }
1467    }
1468 
1469    /* Allocate a new shader arena. */
1470    struct radv_shader_arena *arena = calloc(1, sizeof(struct radv_shader_arena));
1471    union radv_shader_arena_block *alloc = NULL, *hole = NULL;
1472    if (!arena)
1473       goto fail;
1474 
1475    unsigned arena_size =
1476       MAX2(RADV_SHADER_ALLOC_MIN_ARENA_SIZE
1477               << MIN2(RADV_SHADER_ALLOC_MAX_ARENA_SIZE_SHIFT, device->shader_arena_shift),
1478            size);
1479    VkResult result = device->ws->buffer_create(
1480       device->ws, arena_size, RADV_SHADER_ALLOC_ALIGNMENT, RADEON_DOMAIN_VRAM,
1481       RADEON_FLAG_NO_INTERPROCESS_SHARING | RADEON_FLAG_32BIT |
1482          (device->physical_device->rad_info.cpdma_prefetch_writes_memory ? 0
1483                                                                          : RADEON_FLAG_READ_ONLY),
1484       RADV_BO_PRIORITY_SHADER, 0, &arena->bo);
1485    if (result != VK_SUCCESS)
1486       goto fail;
1487 
1488    list_inithead(&arena->entries);
1489 
1490    arena->ptr = (char *)device->ws->buffer_map(arena->bo);
1491    if (!arena->ptr)
1492       goto fail;
1493 
1494    alloc = alloc_block_obj(device);
1495    hole = arena_size - size > 0 ? alloc_block_obj(device) : alloc;
1496    if (!alloc || !hole)
1497       goto fail;
1498    list_addtail(&alloc->list, &arena->entries);
1499    alloc->freelist.prev = NULL;
1500    alloc->freelist.next = ptr;
1501    alloc->arena = arena;
1502    alloc->offset = 0;
1503    alloc->size = size;
1504 
1505    if (hole != alloc) {
1506       hole->arena = arena;
1507       hole->offset = size;
1508       hole->size = arena_size - size;
1509 
1510       list_addtail(&hole->list, &arena->entries);
1511       add_hole(device, hole);
1512    }
1513 
1514    ++device->shader_arena_shift;
1515    list_addtail(&arena->list, &device->shader_arenas);
1516 
1517    mtx_unlock(&device->shader_arena_mutex);
1518    return alloc;
1519 
1520 fail:
1521    mtx_unlock(&device->shader_arena_mutex);
1522    free(alloc);
1523    free(hole);
1524    if (arena && arena->bo)
1525       device->ws->buffer_destroy(device->ws, arena->bo);
1526    free(arena);
1527    return NULL;
1528 }
1529 
1530 static union radv_shader_arena_block *
get_hole(struct radv_shader_arena * arena,struct list_head * head)1531 get_hole(struct radv_shader_arena *arena, struct list_head *head)
1532 {
1533    if (head == &arena->entries)
1534       return NULL;
1535 
1536    union radv_shader_arena_block *hole = list_entry(head, union radv_shader_arena_block, list);
1537    return hole->freelist.prev ? hole : NULL;
1538 }
1539 
1540 void
radv_free_shader_memory(struct radv_device * device,union radv_shader_arena_block * alloc)1541 radv_free_shader_memory(struct radv_device *device, union radv_shader_arena_block *alloc)
1542 {
1543    mtx_lock(&device->shader_arena_mutex);
1544 
1545    union radv_shader_arena_block *hole_prev = get_hole(alloc->arena, alloc->list.prev);
1546    union radv_shader_arena_block *hole_next = get_hole(alloc->arena, alloc->list.next);
1547 
1548    union radv_shader_arena_block *hole = alloc;
1549 
1550    /* merge with previous hole */
1551    if (hole_prev) {
1552       remove_hole(device, hole_prev);
1553 
1554       hole_prev->size += hole->size;
1555       list_del(&hole->list);
1556       free_block_obj(device, hole);
1557 
1558       hole = hole_prev;
1559    }
1560 
1561    /* merge with next hole */
1562    if (hole_next) {
1563       remove_hole(device, hole_next);
1564 
1565       hole_next->offset -= hole->size;
1566       hole_next->size += hole->size;
1567       list_del(&hole->list);
1568       free_block_obj(device, hole);
1569 
1570       hole = hole_next;
1571    }
1572 
1573    if (list_is_singular(&hole->list)) {
1574       struct radv_shader_arena *arena = hole->arena;
1575       free_block_obj(device, hole);
1576 
1577       device->ws->buffer_destroy(device->ws, arena->bo);
1578       list_del(&arena->list);
1579       free(arena);
1580    } else {
1581       add_hole(device, hole);
1582    }
1583 
1584    mtx_unlock(&device->shader_arena_mutex);
1585 }
1586 
1587 void
radv_init_shader_arenas(struct radv_device * device)1588 radv_init_shader_arenas(struct radv_device *device)
1589 {
1590    mtx_init(&device->shader_arena_mutex, mtx_plain);
1591 
1592    device->shader_free_list_mask = 0;
1593 
1594    list_inithead(&device->shader_arenas);
1595    list_inithead(&device->shader_block_obj_pool);
1596    for (unsigned i = 0; i < RADV_SHADER_ALLOC_NUM_FREE_LISTS; i++)
1597       list_inithead(&device->shader_free_lists[i]);
1598 }
1599 
1600 void
radv_destroy_shader_arenas(struct radv_device * device)1601 radv_destroy_shader_arenas(struct radv_device *device)
1602 {
1603    list_for_each_entry_safe(union radv_shader_arena_block, block, &device->shader_block_obj_pool,
1604                             pool) free(block);
1605 
1606    list_for_each_entry_safe(struct radv_shader_arena, arena, &device->shader_arenas, list)
1607    {
1608       device->ws->buffer_destroy(device->ws, arena->bo);
1609       free(arena);
1610    }
1611    mtx_destroy(&device->shader_arena_mutex);
1612 }
1613 
1614 /* For the UMR disassembler. */
1615 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
1616 #define DEBUGGER_NUM_MARKERS        5
1617 
1618 static unsigned
radv_get_shader_binary_size(size_t code_size)1619 radv_get_shader_binary_size(size_t code_size)
1620 {
1621    return code_size + DEBUGGER_NUM_MARKERS * 4;
1622 }
1623 
1624 static bool
radv_should_use_wgp_mode(const struct radv_device * device,gl_shader_stage stage,const struct radv_shader_info * info)1625 radv_should_use_wgp_mode(const struct radv_device *device, gl_shader_stage stage,
1626                          const struct radv_shader_info *info)
1627 {
1628    enum amd_gfx_level chip = device->physical_device->rad_info.gfx_level;
1629    switch (stage) {
1630    case MESA_SHADER_COMPUTE:
1631    case MESA_SHADER_TESS_CTRL:
1632       return chip >= GFX10;
1633    case MESA_SHADER_GEOMETRY:
1634       return chip == GFX10 || (chip >= GFX10_3 && !info->is_ngg);
1635    case MESA_SHADER_VERTEX:
1636    case MESA_SHADER_TESS_EVAL:
1637       return chip == GFX10 && info->is_ngg;
1638    default:
1639       return false;
1640    }
1641 }
1642 
1643 static void
radv_postprocess_config(const struct radv_device * device,const struct ac_shader_config * config_in,const struct radv_shader_info * info,gl_shader_stage stage,const struct radv_shader_args * args,struct ac_shader_config * config_out)1644 radv_postprocess_config(const struct radv_device *device, const struct ac_shader_config *config_in,
1645                         const struct radv_shader_info *info, gl_shader_stage stage,
1646                         const struct radv_shader_args *args,
1647                         struct ac_shader_config *config_out)
1648 {
1649    const struct radv_physical_device *pdevice = device->physical_device;
1650    bool scratch_enabled = config_in->scratch_bytes_per_wave > 0;
1651    bool trap_enabled = !!device->trap_handler_shader;
1652    unsigned vgpr_comp_cnt = 0;
1653    unsigned num_input_vgprs = args->ac.num_vgprs_used;
1654 
1655    if (stage == MESA_SHADER_FRAGMENT) {
1656       num_input_vgprs = ac_get_fs_input_vgpr_cnt(config_in, NULL, NULL, NULL);
1657    }
1658 
1659    unsigned num_vgprs = MAX2(config_in->num_vgprs, num_input_vgprs);
1660    /* +2 for the ring offsets, +3 for scratch wave offset and VCC */
1661    unsigned num_sgprs = MAX2(config_in->num_sgprs, args->ac.num_sgprs_used + 2 + 3);
1662    unsigned num_shared_vgprs = config_in->num_shared_vgprs;
1663    /* shared VGPRs are introduced in Navi and are allocated in blocks of 8 (RDNA ref 3.6.5) */
1664    assert((pdevice->rad_info.gfx_level >= GFX10 && num_shared_vgprs % 8 == 0) ||
1665           (pdevice->rad_info.gfx_level < GFX10 && num_shared_vgprs == 0));
1666    unsigned num_shared_vgpr_blocks = num_shared_vgprs / 8;
1667    unsigned excp_en = 0;
1668 
1669    *config_out = *config_in;
1670    config_out->num_vgprs = num_vgprs;
1671    config_out->num_sgprs = num_sgprs;
1672    config_out->num_shared_vgprs = num_shared_vgprs;
1673 
1674    config_out->rsrc2 = S_00B12C_USER_SGPR(args->num_user_sgprs) |
1675                        S_00B12C_SCRATCH_EN(scratch_enabled) | S_00B12C_TRAP_PRESENT(trap_enabled);
1676 
1677    if (trap_enabled) {
1678       /* Configure the shader exceptions like memory violation, etc.
1679        * TODO: Enable (and validate) more exceptions.
1680        */
1681       excp_en = 1 << 8; /* mem_viol */
1682    }
1683 
1684    if (!pdevice->use_ngg_streamout) {
1685       config_out->rsrc2 |=
1686          S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) | S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
1687          S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) | S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
1688          S_00B12C_SO_EN(!!info->so.num_outputs);
1689    }
1690 
1691    config_out->rsrc1 = S_00B848_VGPRS((num_vgprs - 1) / (info->wave_size == 32 ? 8 : 4)) |
1692                        S_00B848_DX10_CLAMP(1) | S_00B848_FLOAT_MODE(config_out->float_mode);
1693 
1694    if (pdevice->rad_info.gfx_level >= GFX10) {
1695       config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(args->num_user_sgprs >> 5);
1696    } else {
1697       config_out->rsrc1 |= S_00B228_SGPRS((num_sgprs - 1) / 8);
1698       config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(args->num_user_sgprs >> 5);
1699    }
1700 
1701    bool wgp_mode = radv_should_use_wgp_mode(device, stage, info);
1702 
1703    switch (stage) {
1704    case MESA_SHADER_TESS_EVAL:
1705       if (info->is_ngg) {
1706          config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1707          config_out->rsrc2 |= S_00B22C_OC_LDS_EN(1) | S_00B22C_EXCP_EN(excp_en);
1708       } else if (info->tes.as_es) {
1709          assert(pdevice->rad_info.gfx_level <= GFX8);
1710          vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
1711 
1712          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1713       } else {
1714          bool enable_prim_id = info->tes.outinfo.export_prim_id || info->uses_prim_id;
1715          vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1716 
1717          config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1718          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1719       }
1720       config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1721       break;
1722    case MESA_SHADER_TESS_CTRL:
1723       if (pdevice->rad_info.gfx_level >= GFX9) {
1724          /* We need at least 2 components for LS.
1725           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
1726           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1727           */
1728          if (pdevice->rad_info.gfx_level >= GFX10) {
1729             if (info->vs.needs_instance_id) {
1730                vgpr_comp_cnt = 3;
1731             } else if (pdevice->rad_info.gfx_level <= GFX10_3) {
1732                vgpr_comp_cnt = 1;
1733             }
1734             config_out->rsrc2 |=
1735                S_00B42C_LDS_SIZE_GFX10(info->tcs.num_lds_blocks) | S_00B42C_EXCP_EN_GFX6(excp_en);
1736          } else {
1737             vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
1738             config_out->rsrc2 |=
1739                S_00B42C_LDS_SIZE_GFX9(info->tcs.num_lds_blocks) | S_00B42C_EXCP_EN_GFX9(excp_en);
1740          }
1741       } else {
1742          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1743       }
1744       config_out->rsrc1 |=
1745          S_00B428_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10) | S_00B428_WGP_MODE(wgp_mode);
1746       config_out->rsrc2 |= S_00B42C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1747       break;
1748    case MESA_SHADER_VERTEX:
1749       if (info->is_ngg) {
1750          config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1751       } else if (info->vs.as_ls) {
1752          assert(pdevice->rad_info.gfx_level <= GFX8);
1753          /* We need at least 2 components for LS.
1754           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
1755           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1756           */
1757          vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
1758       } else if (info->vs.as_es) {
1759          assert(pdevice->rad_info.gfx_level <= GFX8);
1760          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
1761          vgpr_comp_cnt = info->vs.needs_instance_id ? 1 : 0;
1762       } else {
1763          /* VGPR0-3: (VertexID, InstanceID / StepRate0, PrimID, InstanceID)
1764           * If PrimID is disabled. InstanceID / StepRate1 is loaded instead.
1765           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1766           */
1767          if (info->vs.needs_instance_id && pdevice->rad_info.gfx_level >= GFX10) {
1768             vgpr_comp_cnt = 3;
1769          } else if (info->vs.outinfo.export_prim_id) {
1770             vgpr_comp_cnt = 2;
1771          } else if (info->vs.needs_instance_id) {
1772             vgpr_comp_cnt = 1;
1773          } else {
1774             vgpr_comp_cnt = 0;
1775          }
1776 
1777          config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1778       }
1779       config_out->rsrc2 |=
1780          S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B12C_EXCP_EN(excp_en);
1781       break;
1782    case MESA_SHADER_MESH:
1783       config_out->rsrc1 |= S_00B228_MEM_ORDERED(1);
1784       config_out->rsrc2 |=
1785          S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B12C_EXCP_EN(excp_en);
1786       break;
1787    case MESA_SHADER_FRAGMENT:
1788       config_out->rsrc1 |= S_00B028_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1789       config_out->rsrc2 |= S_00B02C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) |
1790                            S_00B02C_EXCP_EN(excp_en);
1791       break;
1792    case MESA_SHADER_GEOMETRY:
1793       config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10);
1794       config_out->rsrc2 |=
1795          S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B22C_EXCP_EN(excp_en);
1796       break;
1797    case MESA_SHADER_COMPUTE:
1798    case MESA_SHADER_TASK:
1799       config_out->rsrc1 |=
1800          S_00B848_MEM_ORDERED(pdevice->rad_info.gfx_level >= GFX10) | S_00B848_WGP_MODE(wgp_mode);
1801       config_out->rsrc2 |= S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) |
1802                            S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
1803                            S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
1804                            S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2]   ? 2
1805                                                    : info->cs.uses_thread_id[1] ? 1
1806                                                                                 : 0) |
1807                            S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) |
1808                            S_00B84C_LDS_SIZE(config_in->lds_size) | S_00B84C_EXCP_EN(excp_en);
1809       config_out->rsrc3 |= S_00B8A0_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1810 
1811       break;
1812    default:
1813       unreachable("unsupported shader type");
1814       break;
1815    }
1816 
1817    if (pdevice->rad_info.gfx_level >= GFX10 && info->is_ngg &&
1818        (stage == MESA_SHADER_VERTEX || stage == MESA_SHADER_TESS_EVAL ||
1819         stage == MESA_SHADER_GEOMETRY || stage == MESA_SHADER_MESH)) {
1820       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
1821       gl_shader_stage es_stage = stage;
1822       if (stage == MESA_SHADER_GEOMETRY)
1823          es_stage = info->gs.es_type;
1824 
1825       /* VGPR5-8: (VertexID, UserVGPR0, UserVGPR1, UserVGPR2 / InstanceID) */
1826       if (es_stage == MESA_SHADER_VERTEX) {
1827          es_vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 0;
1828       } else if (es_stage == MESA_SHADER_TESS_EVAL) {
1829          bool enable_prim_id = info->tes.outinfo.export_prim_id || info->uses_prim_id;
1830          es_vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1831       } else if (es_stage == MESA_SHADER_MESH) {
1832          es_vgpr_comp_cnt = 0;
1833       } else {
1834          unreachable("Unexpected ES shader stage");
1835       }
1836 
1837       /* GS vertex offsets in NGG:
1838        * - in passthrough mode, they are all packed into VGPR0
1839        * - in the default mode: VGPR0: offsets 0, 1; VGPR1: offsets 2, 3
1840        *
1841        * The vertex offset 2 is always needed when NGG isn't in passthrough mode
1842        * and uses triangle input primitives, including with NGG culling.
1843        */
1844       bool need_gs_vtx_offset2 = !info->is_ngg_passthrough || info->gs.vertices_in >= 3;
1845 
1846       /* TES only needs vertex offset 2 for triangles or quads. */
1847       if (stage == MESA_SHADER_TESS_EVAL)
1848          need_gs_vtx_offset2 &= info->tes._primitive_mode == TESS_PRIMITIVE_TRIANGLES ||
1849                                 info->tes._primitive_mode == TESS_PRIMITIVE_QUADS;
1850 
1851       if (info->uses_invocation_id) {
1852          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
1853       } else if (info->uses_prim_id || (es_stage == MESA_SHADER_VERTEX &&
1854                                         info->vs.outinfo.export_prim_id)) {
1855          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1856       } else if (need_gs_vtx_offset2) {
1857          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1858       } else {
1859          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 (or passthrough prim) */
1860       }
1861 
1862       /* Disable the WGP mode on gfx10.3 because it can hang. (it
1863        * happened on VanGogh) Let's disable it on all chips that
1864        * disable exactly 1 CU per SA for GS.
1865        */
1866       config_out->rsrc1 |=
1867          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
1868       config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1869                            S_00B22C_LDS_SIZE(config_in->lds_size) |
1870                            S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
1871    } else if (pdevice->rad_info.gfx_level >= GFX9 && stage == MESA_SHADER_GEOMETRY) {
1872       unsigned es_type = info->gs.es_type;
1873       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
1874 
1875       if (es_type == MESA_SHADER_VERTEX) {
1876          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
1877          if (info->vs.needs_instance_id) {
1878             es_vgpr_comp_cnt = pdevice->rad_info.gfx_level >= GFX10 ? 3 : 1;
1879          } else {
1880             es_vgpr_comp_cnt = 0;
1881          }
1882       } else if (es_type == MESA_SHADER_TESS_EVAL) {
1883          es_vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
1884       } else {
1885          unreachable("invalid shader ES type");
1886       }
1887 
1888       /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
1889        * VGPR[0:4] are always loaded.
1890        */
1891       if (info->uses_invocation_id) {
1892          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
1893       } else if (info->uses_prim_id) {
1894          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1895       } else if (info->gs.vertices_in >= 3) {
1896          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1897       } else {
1898          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1899       }
1900 
1901       config_out->rsrc1 |=
1902          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
1903       config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1904                            S_00B22C_OC_LDS_EN(es_type == MESA_SHADER_TESS_EVAL);
1905    } else if (pdevice->rad_info.gfx_level >= GFX9 && stage == MESA_SHADER_TESS_CTRL) {
1906       config_out->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
1907    } else {
1908       config_out->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
1909    }
1910 }
1911 
1912 #ifndef _WIN32
1913 static bool
radv_open_rtld_binary(struct radv_device * device,const struct radv_shader * shader,const struct radv_shader_binary * binary,struct ac_rtld_binary * rtld_binary)1914 radv_open_rtld_binary(struct radv_device *device, const struct radv_shader *shader,
1915                       const struct radv_shader_binary *binary, struct ac_rtld_binary *rtld_binary)
1916 {
1917    const char *elf_data = (const char *)((struct radv_shader_binary_rtld *)binary)->data;
1918    size_t elf_size = ((struct radv_shader_binary_rtld *)binary)->elf_size;
1919    struct ac_rtld_symbol lds_symbols[3];
1920    unsigned num_lds_symbols = 0;
1921 
1922    if (device->physical_device->rad_info.gfx_level >= GFX9 &&
1923        (binary->stage == MESA_SHADER_GEOMETRY || binary->info.is_ngg) &&
1924        !binary->is_gs_copy_shader) {
1925       struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1926       sym->name = "esgs_ring";
1927       sym->size = binary->info.ngg_info.esgs_ring_size;
1928       sym->align = 64 * 1024;
1929    }
1930 
1931    if (binary->info.is_ngg && binary->stage == MESA_SHADER_GEOMETRY) {
1932       struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1933       sym->name = "ngg_emit";
1934       sym->size = binary->info.ngg_info.ngg_emit_size * 4;
1935       sym->align = 4;
1936 
1937       sym = &lds_symbols[num_lds_symbols++];
1938       sym->name = "ngg_scratch";
1939       sym->size = 8;
1940       sym->align = 4;
1941    }
1942 
1943    struct ac_rtld_open_info open_info = {
1944       .info = &device->physical_device->rad_info,
1945       .shader_type = binary->stage,
1946       .wave_size = binary->info.wave_size,
1947       .num_parts = 1,
1948       .elf_ptrs = &elf_data,
1949       .elf_sizes = &elf_size,
1950       .num_shared_lds_symbols = num_lds_symbols,
1951       .shared_lds_symbols = lds_symbols,
1952    };
1953 
1954    return ac_rtld_open(rtld_binary, open_info);
1955 }
1956 #endif
1957 
1958 bool
radv_shader_binary_upload(struct radv_device * device,const struct radv_shader_binary * binary,struct radv_shader * shader,void * dest_ptr)1959 radv_shader_binary_upload(struct radv_device *device, const struct radv_shader_binary *binary,
1960                           struct radv_shader *shader, void *dest_ptr)
1961 {
1962    if (binary->type == RADV_BINARY_TYPE_RTLD) {
1963 #ifdef _WIN32
1964       return false;
1965 #else
1966       struct ac_rtld_binary rtld_binary = {0};
1967 
1968       if (!radv_open_rtld_binary(device, shader, binary, &rtld_binary)) {
1969          free(shader);
1970          return false;
1971       }
1972 
1973       struct ac_rtld_upload_info info = {
1974          .binary = &rtld_binary,
1975          .rx_va = radv_shader_get_va(shader),
1976          .rx_ptr = dest_ptr,
1977       };
1978 
1979       if (!ac_rtld_upload(&info)) {
1980          radv_shader_destroy(device, shader);
1981          ac_rtld_close(&rtld_binary);
1982          return false;
1983       }
1984 
1985       shader->code_ptr = dest_ptr;
1986       ac_rtld_close(&rtld_binary);
1987 #endif
1988    } else {
1989       struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
1990       memcpy(dest_ptr, bin->data + bin->stats_size, bin->code_size);
1991 
1992       /* Add end-of-code markers for the UMR disassembler. */
1993       uint32_t *ptr32 = (uint32_t *)dest_ptr + bin->code_size / 4;
1994       for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
1995          ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
1996 
1997       shader->code_ptr = dest_ptr;
1998    }
1999 
2000    return true;
2001 }
2002 
2003 struct radv_shader *
radv_shader_create(struct radv_device * device,const struct radv_shader_binary * binary,bool keep_shader_info,bool from_cache,const struct radv_shader_args * args)2004 radv_shader_create(struct radv_device *device, const struct radv_shader_binary *binary,
2005                    bool keep_shader_info, bool from_cache, const struct radv_shader_args *args)
2006 {
2007    struct ac_shader_config config = {0};
2008    struct radv_shader *shader = calloc(1, sizeof(struct radv_shader));
2009    if (!shader)
2010       return NULL;
2011 
2012    shader->ref_count = 1;
2013 
2014    if (binary->type == RADV_BINARY_TYPE_RTLD) {
2015 #ifdef _WIN32
2016       free(shader);
2017       return NULL;
2018 #else
2019       struct ac_rtld_binary rtld_binary = {0};
2020 
2021       if (!radv_open_rtld_binary(device, shader, binary, &rtld_binary)) {
2022          free(shader);
2023          return NULL;
2024       }
2025 
2026       if (!ac_rtld_read_config(&device->physical_device->rad_info, &rtld_binary, &config)) {
2027          ac_rtld_close(&rtld_binary);
2028          free(shader);
2029          return NULL;
2030       }
2031 
2032       if (rtld_binary.lds_size > 0) {
2033          unsigned encode_granularity = device->physical_device->rad_info.lds_encode_granularity;
2034          config.lds_size = DIV_ROUND_UP(rtld_binary.lds_size, encode_granularity);
2035       }
2036       if (!config.lds_size && binary->stage == MESA_SHADER_TESS_CTRL) {
2037          /* This is used for reporting LDS statistics */
2038          config.lds_size = binary->info.tcs.num_lds_blocks;
2039       }
2040 
2041       assert(!binary->info.has_ngg_culling || config.lds_size);
2042 
2043       shader->code_size = rtld_binary.rx_size;
2044       shader->exec_size = rtld_binary.exec_size;
2045       ac_rtld_close(&rtld_binary);
2046 #endif
2047    } else {
2048       assert(binary->type == RADV_BINARY_TYPE_LEGACY);
2049       config = ((struct radv_shader_binary_legacy *)binary)->base.config;
2050       shader->code_size =
2051          radv_get_shader_binary_size(((struct radv_shader_binary_legacy *)binary)->code_size);
2052       shader->exec_size = ((struct radv_shader_binary_legacy *)binary)->exec_size;
2053    }
2054 
2055    shader->info = binary->info;
2056 
2057    if (from_cache) {
2058       /* Copy the shader binary configuration from the cache. */
2059       memcpy(&shader->config, &binary->config, sizeof(shader->config));
2060    } else {
2061       assert(args);
2062       radv_postprocess_config(device, &config, &binary->info, binary->stage, args, &shader->config);
2063    }
2064 
2065    if (binary->type == RADV_BINARY_TYPE_RTLD) {
2066 #ifdef _WIN32
2067       free(shader);
2068       return NULL;
2069 #else
2070       struct radv_shader_binary_rtld *bin = (struct radv_shader_binary_rtld *)binary;
2071       struct ac_rtld_binary rtld_binary = {0};
2072 
2073       if (!radv_open_rtld_binary(device, shader, binary, &rtld_binary)) {
2074          free(shader);
2075          return NULL;
2076       }
2077 
2078       if (keep_shader_info || (device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS)) {
2079          const char *disasm_data;
2080          size_t disasm_size;
2081          if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm_data,
2082                                           &disasm_size)) {
2083             radv_shader_destroy(device, shader);
2084             ac_rtld_close(&rtld_binary);
2085             return NULL;
2086          }
2087 
2088          shader->ir_string =
2089             bin->llvm_ir_size ? strdup((const char *)(bin->data + bin->elf_size)) : NULL;
2090          shader->disasm_string = malloc(disasm_size + 1);
2091          memcpy(shader->disasm_string, disasm_data, disasm_size);
2092          shader->disasm_string[disasm_size] = 0;
2093       }
2094       ac_rtld_close(&rtld_binary);
2095 #endif
2096    } else {
2097       struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
2098 
2099       shader->ir_string =
2100          bin->ir_size ? strdup((const char *)(bin->data + bin->stats_size + bin->code_size)) : NULL;
2101       shader->disasm_string =
2102          bin->disasm_size
2103             ? strdup((const char *)(bin->data + bin->stats_size + bin->code_size + bin->ir_size))
2104             : NULL;
2105 
2106       if (bin->stats_size) {
2107          shader->statistics = calloc(bin->stats_size, 1);
2108          memcpy(shader->statistics, bin->data, bin->stats_size);
2109       }
2110    }
2111    return shader;
2112 }
2113 
2114 static char *
radv_dump_nir_shaders(struct nir_shader * const * shaders,int shader_count)2115 radv_dump_nir_shaders(struct nir_shader *const *shaders, int shader_count)
2116 {
2117    char *data = NULL;
2118    char *ret = NULL;
2119    size_t size = 0;
2120    struct u_memstream mem;
2121    if (u_memstream_open(&mem, &data, &size)) {
2122       FILE *const memf = u_memstream_get(&mem);
2123       for (int i = 0; i < shader_count; ++i)
2124          nir_print_shader(shaders[i], memf);
2125       u_memstream_close(&mem);
2126    }
2127 
2128    ret = malloc(size + 1);
2129    if (ret) {
2130       memcpy(ret, data, size);
2131       ret[size] = 0;
2132    }
2133    free(data);
2134    return ret;
2135 }
2136 
2137 static void
radv_aco_build_shader_binary(void ** bin,gl_shader_stage stage,bool is_gs_copy_shader,const struct ac_shader_config * config,const char * llvm_ir_str,unsigned llvm_ir_size,const char * disasm_str,unsigned disasm_size,uint32_t * statistics,uint32_t stats_size,uint32_t exec_size,const uint32_t * code,uint32_t code_dw)2138 radv_aco_build_shader_binary(void **bin,
2139                              gl_shader_stage stage,
2140                              bool is_gs_copy_shader,
2141                              const struct ac_shader_config *config,
2142                              const char *llvm_ir_str,
2143                              unsigned llvm_ir_size,
2144                              const char *disasm_str,
2145                              unsigned disasm_size,
2146                              uint32_t *statistics,
2147                              uint32_t stats_size,
2148                              uint32_t exec_size,
2149                              const uint32_t *code,
2150                              uint32_t code_dw)
2151 {
2152    struct radv_shader_binary **binary = (struct radv_shader_binary **)bin;
2153    size_t size = llvm_ir_size;
2154 
2155    size += disasm_size;
2156    size += stats_size;
2157 
2158    size += code_dw * sizeof(uint32_t) + sizeof(struct radv_shader_binary_legacy);
2159 
2160    /* We need to calloc to prevent unintialized data because this will be used
2161     * directly for the disk cache. Uninitialized data can appear because of
2162     * padding in the struct or because legacy_binary->data can be at an offset
2163     * from the start less than sizeof(radv_shader_binary_legacy). */
2164    struct radv_shader_binary_legacy *legacy_binary = (struct radv_shader_binary_legacy *)calloc(size, 1);
2165    legacy_binary->base.type = RADV_BINARY_TYPE_LEGACY;
2166    legacy_binary->base.stage = stage;
2167    legacy_binary->base.is_gs_copy_shader = is_gs_copy_shader;
2168    legacy_binary->base.total_size = size;
2169    legacy_binary->base.config = *config;
2170 
2171    if (stats_size)
2172       memcpy(legacy_binary->data, statistics, stats_size);
2173    legacy_binary->stats_size = stats_size;
2174 
2175    memcpy(legacy_binary->data + legacy_binary->stats_size, code,
2176           code_dw * sizeof(uint32_t));
2177    legacy_binary->exec_size = exec_size;
2178    legacy_binary->code_size = code_dw * sizeof(uint32_t);
2179 
2180    legacy_binary->disasm_size = 0;
2181    legacy_binary->ir_size = llvm_ir_size;
2182 
2183    memcpy((char*)legacy_binary->data + legacy_binary->stats_size + legacy_binary->code_size,
2184           llvm_ir_str, llvm_ir_size);
2185 
2186    legacy_binary->disasm_size = disasm_size;
2187    if (disasm_size) {
2188       memcpy((char*)legacy_binary->data + legacy_binary->stats_size +
2189              legacy_binary->code_size + llvm_ir_size, disasm_str,
2190              disasm_size);
2191    }
2192    *binary = (struct radv_shader_binary*)legacy_binary;
2193 }
2194 
2195 static struct radv_shader *
shader_compile(struct radv_device * device,struct nir_shader * const * shaders,int shader_count,gl_shader_stage stage,struct radv_shader_info * info,const struct radv_shader_args * args,struct radv_nir_compiler_options * options,bool gs_copy_shader,bool trap_handler_shader,bool keep_shader_info,bool keep_statistic_info,struct radv_shader_binary ** binary_out)2196 shader_compile(struct radv_device *device, struct nir_shader *const *shaders, int shader_count, gl_shader_stage stage,
2197                struct radv_shader_info *info, const struct radv_shader_args *args,
2198                struct radv_nir_compiler_options *options, bool gs_copy_shader,
2199                bool trap_handler_shader, bool keep_shader_info, bool keep_statistic_info,
2200                struct radv_shader_binary **binary_out)
2201 {
2202    enum radeon_family chip_family = device->physical_device->rad_info.family;
2203    struct radv_shader_binary *binary = NULL;
2204 
2205    struct radv_shader_debug_data debug_data = {
2206       .device = device,
2207       .object = NULL,
2208    };
2209 
2210    options->family = chip_family;
2211    options->gfx_level = device->physical_device->rad_info.gfx_level;
2212    options->has_3d_cube_border_color_mipmap = device->physical_device->rad_info.has_3d_cube_border_color_mipmap;
2213    options->dump_shader = radv_can_dump_shader(device, shaders[0], gs_copy_shader || trap_handler_shader);
2214    options->dump_preoptir =
2215       options->dump_shader && device->instance->debug_flags & RADV_DEBUG_PREOPTIR;
2216    options->record_ir = keep_shader_info;
2217    options->record_stats = keep_statistic_info;
2218    options->check_ir = device->instance->debug_flags & RADV_DEBUG_CHECKIR;
2219    options->address32_hi = device->physical_device->rad_info.address32_hi;
2220    options->has_ls_vgpr_init_bug = device->physical_device->rad_info.has_ls_vgpr_init_bug;
2221    options->enable_mrt_output_nan_fixup =
2222       !is_meta_shader(shaders[0]) && options->key.ps.enable_mrt_output_nan_fixup;
2223    options->debug.func = radv_compiler_debug;
2224    options->debug.private_data = &debug_data;
2225 
2226 #ifdef LLVM_AVAILABLE
2227    if (radv_use_llvm_for_stage(device, stage) || options->dump_shader || options->record_ir)
2228       ac_init_llvm_once();
2229 
2230    if (radv_use_llvm_for_stage(device, stage)) {
2231       llvm_compile_shader(options, info, shader_count, shaders, &binary, args);
2232 #else
2233    if (false) {
2234 #endif
2235    } else {
2236       struct aco_shader_info ac_info;
2237       struct aco_compiler_options ac_opts;
2238       radv_aco_convert_opts(&ac_opts, options);
2239       radv_aco_convert_shader_info(&ac_info, info);
2240       aco_compile_shader(&ac_opts, &ac_info, shader_count, shaders, args, &radv_aco_build_shader_binary, (void **)&binary);
2241    }
2242 
2243    binary->info = *info;
2244 
2245    struct radv_shader *shader = radv_shader_create(device, binary, keep_shader_info, false, args);
2246    if (!shader) {
2247       free(binary);
2248       return NULL;
2249    }
2250 
2251    if (options->dump_shader) {
2252       fprintf(stderr, "%s", radv_get_shader_name(info, shaders[0]->info.stage));
2253       for (int i = 1; i < shader_count; ++i)
2254          fprintf(stderr, " + %s", radv_get_shader_name(info, shaders[i]->info.stage));
2255 
2256       fprintf(stderr, "\ndisasm:\n%s\n", shader->disasm_string);
2257    }
2258 
2259    if (keep_shader_info) {
2260       shader->nir_string = radv_dump_nir_shaders(shaders, shader_count);
2261    }
2262 
2263    /* Copy the shader binary configuration to store it in the cache. */
2264    memcpy(&binary->config, &shader->config, sizeof(binary->config));
2265 
2266    *binary_out = binary;
2267    return shader;
2268 }
2269 
2270 struct radv_shader *
2271 radv_shader_nir_to_asm(struct radv_device *device, struct radv_pipeline_stage *pl_stage,
2272                        struct nir_shader *const *shaders, int shader_count,
2273                        const struct radv_pipeline_key *key, bool keep_shader_info,
2274                        bool keep_statistic_info, struct radv_shader_binary **binary_out)
2275 {
2276    gl_shader_stage stage = shaders[shader_count - 1]->info.stage;
2277    struct radv_nir_compiler_options options = {0};
2278 
2279    if (key)
2280       options.key = *key;
2281 
2282    options.robust_buffer_access = device->robust_buffer_access;
2283    options.wgp_mode = radv_should_use_wgp_mode(device, stage, &pl_stage->info);
2284 
2285    return shader_compile(device, shaders, shader_count, stage, &pl_stage->info,
2286                          &pl_stage->args, &options, false, false, keep_shader_info,
2287                          keep_statistic_info, binary_out);
2288 }
2289 
2290 struct radv_shader *
2291 radv_create_gs_copy_shader(struct radv_device *device, struct nir_shader *shader,
2292                            struct radv_shader_info *info, const struct radv_shader_args *args,
2293                            struct radv_shader_binary **binary_out, bool keep_shader_info,
2294                            bool keep_statistic_info, bool disable_optimizations)
2295 {
2296    struct radv_nir_compiler_options options = {0};
2297    gl_shader_stage stage = MESA_SHADER_VERTEX;
2298 
2299    options.key.optimisations_disabled = disable_optimizations;
2300 
2301    return shader_compile(device, &shader, 1, stage, info, args, &options, true, false,
2302                          keep_shader_info, keep_statistic_info, binary_out);
2303 }
2304 
2305 struct radv_trap_handler_shader *
2306 radv_create_trap_handler_shader(struct radv_device *device)
2307 {
2308    struct radv_nir_compiler_options options = {0};
2309    struct radv_shader *shader = NULL;
2310    struct radv_shader_binary *binary = NULL;
2311    struct radv_shader_info info = {0};
2312    struct radv_pipeline_key key = {0};
2313    struct radv_trap_handler_shader *trap;
2314 
2315    trap = malloc(sizeof(struct radv_trap_handler_shader));
2316    if (!trap)
2317       return NULL;
2318 
2319    nir_builder b = radv_meta_init_shader(device, MESA_SHADER_COMPUTE, "meta_trap_handler");
2320 
2321    options.wgp_mode = radv_should_use_wgp_mode(device, MESA_SHADER_COMPUTE, &info);
2322    info.wave_size = 64;
2323 
2324    struct radv_shader_args args;
2325    args.explicit_scratch_args = true;
2326    args.is_trap_handler_shader = true;
2327    radv_declare_shader_args(device->physical_device->rad_info.gfx_level, &key, &info,
2328                             MESA_SHADER_COMPUTE, false, MESA_SHADER_VERTEX, &args);
2329 
2330    shader = shader_compile(device, &b.shader, 1, MESA_SHADER_COMPUTE, &info, &args, &options,
2331                            false, true, false, false, &binary);
2332 
2333    trap->alloc = radv_alloc_shader_memory(device, shader->code_size, NULL);
2334 
2335    trap->bo = trap->alloc->arena->bo;
2336    char *dest_ptr = trap->alloc->arena->ptr + trap->alloc->offset;
2337 
2338    struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
2339    memcpy(dest_ptr, bin->data, bin->code_size);
2340 
2341    ralloc_free(b.shader);
2342    free(shader);
2343    free(binary);
2344 
2345    return trap;
2346 }
2347 
2348 uint64_t radv_trap_handler_shader_get_va(const struct radv_trap_handler_shader *trap)
2349 {
2350    return radv_buffer_get_va(trap->alloc->arena->bo) + trap->alloc->offset;
2351 }
2352 
2353 void
2354 radv_trap_handler_shader_destroy(struct radv_device *device, struct radv_trap_handler_shader *trap)
2355 {
2356    if (!trap)
2357       return;
2358 
2359    radv_free_shader_memory(device, trap->alloc);
2360    free(trap);
2361 }
2362 
2363 static struct radv_shader_part *
2364 upload_shader_part(struct radv_device *device, struct radv_shader_part_binary *bin, unsigned wave_size)
2365 {
2366    uint32_t code_size = radv_get_shader_binary_size(bin->code_size);
2367    struct radv_shader_part *shader_part = malloc(sizeof(struct radv_shader_part));
2368    if (!shader_part)
2369       return NULL;
2370 
2371    shader_part->alloc = radv_alloc_shader_memory(device, code_size, NULL);
2372    if (!shader_part->alloc) {
2373       free(shader_part);
2374       return NULL;
2375    }
2376 
2377    shader_part->bo = shader_part->alloc->arena->bo;
2378    char *dest_ptr = shader_part->alloc->arena->ptr + shader_part->alloc->offset;
2379 
2380    memcpy(dest_ptr, bin->data, bin->code_size);
2381 
2382    /* Add end-of-code markers for the UMR disassembler. */
2383    uint32_t *ptr32 = (uint32_t *)dest_ptr + bin->code_size / 4;
2384    for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
2385       ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
2386 
2387    shader_part->rsrc1 = S_00B848_VGPRS((bin->num_vgprs - 1) / (wave_size == 32 ? 8 : 4)) |
2388                    S_00B228_SGPRS((bin->num_sgprs - 1) / 8);
2389    shader_part->num_preserved_sgprs = bin->num_preserved_sgprs;
2390    shader_part->disasm_string = NULL;
2391 
2392    return shader_part;
2393 }
2394 
2395 static void radv_aco_build_shader_part(void **bin,
2396                                        uint32_t num_sgprs,
2397                                        uint32_t num_vgprs,
2398                                        uint32_t num_preserved_sgprs,
2399                                        const uint32_t *code,
2400                                        uint32_t code_size,
2401                                        const char *disasm_str,
2402                                        uint32_t disasm_size)
2403 {
2404    struct radv_shader_part_binary **binary = (struct radv_shader_part_binary **)bin;
2405    size_t size = code_size * sizeof(uint32_t) + sizeof(struct radv_shader_part_binary);
2406 
2407    size += disasm_size;
2408    struct radv_shader_part_binary *part_binary = (struct radv_shader_part_binary *)calloc(size, 1);
2409 
2410    part_binary->num_sgprs = num_sgprs;
2411    part_binary->num_vgprs = num_vgprs;
2412    part_binary->num_preserved_sgprs = num_preserved_sgprs;
2413    part_binary->code_size = code_size * sizeof(uint32_t);
2414    memcpy(part_binary->data, code, part_binary->code_size);
2415    if (disasm_size) {
2416       memcpy((char*)part_binary->data + part_binary->code_size,
2417              disasm_str, disasm_size);
2418       part_binary->disasm_size = disasm_size;
2419    }
2420 
2421    *binary = part_binary;
2422 }
2423 
2424 struct radv_shader_part *
2425 radv_create_vs_prolog(struct radv_device *device, const struct radv_vs_prolog_key *key)
2426 {
2427    struct radv_shader_args args = {0};
2428    struct radv_nir_compiler_options options = {0};
2429    options.family = device->physical_device->rad_info.family;
2430    options.gfx_level = device->physical_device->rad_info.gfx_level;
2431    options.has_3d_cube_border_color_mipmap = device->physical_device->rad_info.has_3d_cube_border_color_mipmap;
2432    options.address32_hi = device->physical_device->rad_info.address32_hi;
2433    options.dump_shader = device->instance->debug_flags & RADV_DEBUG_DUMP_PROLOGS;
2434    options.record_ir = device->instance->debug_flags & RADV_DEBUG_HANG;
2435 
2436    struct radv_shader_info info = {0};
2437    info.wave_size = key->wave32 ? 32 : 64;
2438    info.vs.needs_instance_id = true;
2439    info.vs.needs_base_instance = true;
2440    info.vs.needs_draw_id = true;
2441    info.vs.use_per_attribute_vb_descs = true;
2442    info.vs.vb_desc_usage_mask = BITFIELD_MASK(key->num_attributes);
2443    info.vs.has_prolog = true;
2444    info.vs.as_ls = key->as_ls;
2445    info.is_ngg = key->is_ngg;
2446 
2447    struct radv_pipeline_key pipeline_key = {0};
2448 
2449    args.explicit_scratch_args = true;
2450    radv_declare_shader_args(options.gfx_level, &pipeline_key, &info, key->next_stage,
2451                             key->next_stage != MESA_SHADER_VERTEX, MESA_SHADER_VERTEX, &args);
2452 
2453    info.user_sgprs_locs = args.user_sgprs_locs;
2454    info.inline_push_constant_mask = args.ac.inline_push_const_mask;
2455 
2456 #ifdef LLVM_AVAILABLE
2457    if (options.dump_shader || options.record_ir)
2458       ac_init_llvm_once();
2459 #endif
2460 
2461    struct radv_shader_part_binary *binary = NULL;
2462    struct aco_shader_info ac_info;
2463    struct aco_vs_prolog_key ac_key;
2464    struct aco_compiler_options ac_opts;
2465    radv_aco_convert_shader_info(&ac_info, &info);
2466    radv_aco_convert_opts(&ac_opts, &options);
2467    radv_aco_convert_vs_prolog_key(&ac_key, key);
2468    aco_compile_vs_prolog(&ac_opts, &ac_info, &ac_key, &args, &radv_aco_build_shader_part,
2469                          (void **)&binary);
2470    struct radv_shader_part *prolog = upload_shader_part(device, binary, info.wave_size);
2471    if (prolog) {
2472       prolog->nontrivial_divisors = key->state->nontrivial_divisors;
2473       prolog->disasm_string =
2474          binary->disasm_size ? strdup((const char *)(binary->data + binary->code_size)) : NULL;
2475    }
2476 
2477    free(binary);
2478 
2479    if (prolog && options.dump_shader) {
2480       fprintf(stderr, "Vertex prolog");
2481       fprintf(stderr, "\ndisasm:\n%s\n", prolog->disasm_string);
2482    }
2483 
2484    return prolog;
2485 }
2486 
2487 struct radv_shader_part *
2488 radv_create_ps_epilog(struct radv_device *device, const struct radv_ps_epilog_key *key)
2489 {
2490    struct radv_shader_args args = {0};
2491    struct radv_nir_compiler_options options = {0};
2492    options.family = device->physical_device->rad_info.family;
2493    options.gfx_level = device->physical_device->rad_info.gfx_level;
2494    options.address32_hi = device->physical_device->rad_info.address32_hi;
2495    options.dump_shader = device->instance->debug_flags & RADV_DEBUG_DUMP_EPILOGS;
2496    options.record_ir = device->instance->debug_flags & RADV_DEBUG_HANG;
2497    options.dump_preoptir = device->instance->debug_flags & RADV_DEBUG_DUMP_EPILOGS;
2498    options.dump_shader = device->instance->debug_flags & RADV_DEBUG_DUMP_EPILOGS;
2499 
2500    struct radv_shader_info info = {0};
2501    info.wave_size = key->wave32 ? 32 : 64;
2502    info.workgroup_size = 64;
2503 
2504    radv_declare_ps_epilog_args(device->physical_device->rad_info.gfx_level, key, &args);
2505 
2506 #ifdef LLVM_AVAILABLE
2507    if (options.dump_shader || options.record_ir)
2508       ac_init_llvm_once();
2509 #endif
2510 
2511    struct radv_shader_part_binary *binary = NULL;
2512    struct aco_shader_info ac_info;
2513    struct aco_ps_epilog_key ac_key;
2514    struct aco_compiler_options ac_opts;
2515    radv_aco_convert_shader_info(&ac_info, &info);
2516    radv_aco_convert_opts(&ac_opts, &options);
2517    radv_aco_convert_ps_epilog_key(&ac_key, key);
2518    aco_compile_ps_epilog(&ac_opts, &ac_info, &ac_key, &args, &radv_aco_build_shader_part,
2519                          (void **)&binary);
2520    struct radv_shader_part *epilog = upload_shader_part(device, binary, info.wave_size);
2521    if (epilog) {
2522       epilog->disasm_string =
2523          binary->disasm_size ? strdup((const char *)(binary->data + binary->code_size)) : NULL;
2524    }
2525 
2526    free(binary);
2527 
2528    if (epilog && options.dump_shader) {
2529       fprintf(stderr, "Fragment epilog");
2530       fprintf(stderr, "\ndisasm:\n%s\n", epilog->disasm_string);
2531    }
2532 
2533    return epilog;
2534 }
2535 
2536 void
2537 radv_shader_destroy(struct radv_device *device, struct radv_shader *shader)
2538 {
2539    if (!p_atomic_dec_zero(&shader->ref_count))
2540       return;
2541 
2542    free(shader->spirv);
2543    free(shader->nir_string);
2544    free(shader->disasm_string);
2545    free(shader->ir_string);
2546    free(shader->statistics);
2547    free(shader);
2548 }
2549 
2550 void
2551 radv_shader_part_destroy(struct radv_device *device, struct radv_shader_part *shader_part)
2552 {
2553    if (!shader_part)
2554       return;
2555 
2556    radv_free_shader_memory(device, shader_part->alloc);
2557    free(shader_part->disasm_string);
2558    free(shader_part);
2559 }
2560 
2561 uint64_t
2562 radv_shader_get_va(const struct radv_shader *shader)
2563 {
2564    return shader->va;
2565 }
2566 
2567 struct radv_shader *
2568 radv_find_shader(struct radv_device *device, uint64_t pc)
2569 {
2570    mtx_lock(&device->shader_arena_mutex);
2571    list_for_each_entry(struct radv_shader_arena, arena, &device->shader_arenas, list)
2572    {
2573 #ifdef __GNUC__
2574 #pragma GCC diagnostic push
2575 #pragma GCC diagnostic ignored "-Wshadow"
2576 #endif
2577       list_for_each_entry(union radv_shader_arena_block, block, &arena->entries, list)
2578       {
2579 #ifdef __GNUC__
2580 #pragma GCC diagnostic pop
2581 #endif
2582          uint64_t start = radv_buffer_get_va(block->arena->bo) + block->offset;
2583          if (!block->freelist.prev && pc >= start && pc < start + block->size) {
2584             mtx_unlock(&device->shader_arena_mutex);
2585 
2586             struct radv_pipeline *pipeline = (struct radv_pipeline *)block->freelist.next;
2587             for (uint32_t i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
2588                struct radv_shader *shader = pipeline->shaders[i];
2589                if (!shader)
2590                   continue;
2591 
2592                if (pc >= shader->va &&
2593                    pc < shader->va + align(shader->code_size, RADV_SHADER_ALLOC_ALIGNMENT))
2594                   return shader;
2595             }
2596          }
2597       }
2598    }
2599 
2600    mtx_unlock(&device->shader_arena_mutex);
2601    return NULL;
2602 }
2603 
2604 const char *
2605 radv_get_shader_name(const struct radv_shader_info *info, gl_shader_stage stage)
2606 {
2607    switch (stage) {
2608    case MESA_SHADER_VERTEX:
2609       if (info->vs.as_ls)
2610          return "Vertex Shader as LS";
2611       else if (info->vs.as_es)
2612          return "Vertex Shader as ES";
2613       else if (info->is_ngg)
2614          return "Vertex Shader as ESGS";
2615       else
2616          return "Vertex Shader as VS";
2617    case MESA_SHADER_TESS_CTRL:
2618       return "Tessellation Control Shader";
2619    case MESA_SHADER_TESS_EVAL:
2620       if (info->tes.as_es)
2621          return "Tessellation Evaluation Shader as ES";
2622       else if (info->is_ngg)
2623          return "Tessellation Evaluation Shader as ESGS";
2624       else
2625          return "Tessellation Evaluation Shader as VS";
2626    case MESA_SHADER_GEOMETRY:
2627       return "Geometry Shader";
2628    case MESA_SHADER_FRAGMENT:
2629       return "Pixel Shader";
2630    case MESA_SHADER_COMPUTE:
2631       return "Compute Shader";
2632    case MESA_SHADER_MESH:
2633       return "Mesh Shader as NGG";
2634    case MESA_SHADER_TASK:
2635       return "Task Shader as CS";
2636    default:
2637       return "Unknown shader";
2638    };
2639 }
2640 
2641 unsigned
2642 radv_get_max_waves(const struct radv_device *device, struct radv_shader *shader,
2643                    gl_shader_stage stage)
2644 {
2645    struct radeon_info *info = &device->physical_device->rad_info;
2646    enum amd_gfx_level gfx_level = info->gfx_level;
2647    uint8_t wave_size = shader->info.wave_size;
2648    struct ac_shader_config *conf = &shader->config;
2649    unsigned max_simd_waves;
2650    unsigned lds_per_wave = 0;
2651 
2652    max_simd_waves = info->max_wave64_per_simd * (64 / wave_size);
2653 
2654    if (stage == MESA_SHADER_FRAGMENT) {
2655       lds_per_wave =
2656          conf->lds_size * info->lds_encode_granularity + shader->info.ps.num_interp * 48;
2657       lds_per_wave = align(lds_per_wave, info->lds_alloc_granularity);
2658    } else if (stage == MESA_SHADER_COMPUTE || stage == MESA_SHADER_TASK) {
2659       unsigned max_workgroup_size = shader->info.workgroup_size;
2660       lds_per_wave =
2661          align(conf->lds_size * info->lds_encode_granularity, info->lds_alloc_granularity);
2662       lds_per_wave /= DIV_ROUND_UP(max_workgroup_size, wave_size);
2663    }
2664 
2665    if (conf->num_sgprs && gfx_level < GFX10) {
2666       unsigned sgprs = align(conf->num_sgprs, gfx_level >= GFX8 ? 16 : 8);
2667       max_simd_waves = MIN2(max_simd_waves, info->num_physical_sgprs_per_simd / sgprs);
2668    }
2669 
2670    if (conf->num_vgprs) {
2671       unsigned physical_vgprs = info->num_physical_wave64_vgprs_per_simd * (64 / wave_size);
2672       unsigned vgprs = align(conf->num_vgprs, wave_size == 32 ? 8 : 4);
2673       if (gfx_level == GFX10_3)
2674          vgprs = align(vgprs, wave_size == 32 ? 16 : 8);
2675       max_simd_waves = MIN2(max_simd_waves, physical_vgprs / vgprs);
2676    }
2677 
2678    unsigned simd_per_workgroup = info->num_simd_per_compute_unit;
2679    if (gfx_level >= GFX10)
2680       simd_per_workgroup *= 2; /* like lds_size_per_workgroup, assume WGP on GFX10+ */
2681 
2682    unsigned max_lds_per_simd = info->lds_size_per_workgroup / simd_per_workgroup;
2683    if (lds_per_wave)
2684       max_simd_waves = MIN2(max_simd_waves, DIV_ROUND_UP(max_lds_per_simd, lds_per_wave));
2685 
2686    return gfx_level >= GFX10 ? max_simd_waves * (wave_size / 32) : max_simd_waves;
2687 }
2688 
2689 unsigned
2690 radv_compute_spi_ps_input(const struct radv_pipeline_key *pipeline_key,
2691                           const struct radv_shader_info *info)
2692 {
2693    unsigned spi_ps_input;
2694 
2695    spi_ps_input = S_0286CC_PERSP_CENTER_ENA(info->ps.reads_persp_center) |
2696                   S_0286CC_PERSP_CENTROID_ENA(info->ps.reads_persp_centroid) |
2697                   S_0286CC_PERSP_SAMPLE_ENA(info->ps.reads_persp_sample) |
2698                   S_0286CC_LINEAR_CENTER_ENA(info->ps.reads_linear_center) |
2699                   S_0286CC_LINEAR_CENTROID_ENA(info->ps.reads_linear_centroid) |
2700                   S_0286CC_LINEAR_SAMPLE_ENA(info->ps.reads_linear_sample)|
2701                   S_0286CC_PERSP_PULL_MODEL_ENA(info->ps.reads_barycentric_model) |
2702                   S_0286CC_FRONT_FACE_ENA(info->ps.reads_front_face);
2703 
2704    if (info->ps.reads_frag_coord_mask ||
2705        info->ps.reads_sample_pos_mask) {
2706       uint8_t mask = info->ps.reads_frag_coord_mask | info->ps.reads_sample_pos_mask;
2707 
2708       for (unsigned i = 0; i < 4; i++) {
2709          if (mask & (1 << i))
2710             spi_ps_input |= S_0286CC_POS_X_FLOAT_ENA(1) << i;
2711       }
2712 
2713       if (pipeline_key->adjust_frag_coord_z && info->ps.reads_frag_coord_mask & (1 << 2)) {
2714          spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
2715       }
2716    }
2717 
2718    if (info->ps.reads_sample_id || info->ps.reads_frag_shading_rate || info->ps.reads_sample_mask_in) {
2719       spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
2720    }
2721 
2722    if (info->ps.reads_sample_mask_in) {
2723       spi_ps_input |= S_0286CC_SAMPLE_COVERAGE_ENA(1);
2724    }
2725 
2726    if (G_0286CC_POS_W_FLOAT_ENA(spi_ps_input)) {
2727       /* If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be enabled too */
2728       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
2729    }
2730 
2731    if (!(spi_ps_input & 0x7F)) {
2732       /* At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled */
2733       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
2734    }
2735 
2736    return spi_ps_input;
2737 }
2738 
2739 VkResult
2740 radv_dump_shader_stats(struct radv_device *device, struct radv_pipeline *pipeline,
2741                        gl_shader_stage stage, FILE *output)
2742 {
2743    struct radv_shader *shader = pipeline->shaders[stage];
2744    VkPipelineExecutablePropertiesKHR *props = NULL;
2745    uint32_t prop_count = 0;
2746    VkResult result;
2747 
2748    VkPipelineInfoKHR pipeline_info = {0};
2749    pipeline_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR;
2750    pipeline_info.pipeline = radv_pipeline_to_handle(pipeline);
2751 
2752    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info,
2753                                                     &prop_count, NULL);
2754    if (result != VK_SUCCESS)
2755       return result;
2756 
2757    props = calloc(prop_count, sizeof(*props));
2758    if (!props)
2759       return VK_ERROR_OUT_OF_HOST_MEMORY;
2760 
2761    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info,
2762                                                     &prop_count, props);
2763    if (result != VK_SUCCESS)
2764       goto fail;
2765 
2766    for (unsigned exec_idx = 0; exec_idx < prop_count; exec_idx++) {
2767       if (!(props[exec_idx].stages & mesa_to_vk_shader_stage(stage)))
2768          continue;
2769 
2770       VkPipelineExecutableStatisticKHR *stats = NULL;
2771       uint32_t stat_count = 0;
2772 
2773       VkPipelineExecutableInfoKHR exec_info = {0};
2774       exec_info.pipeline = radv_pipeline_to_handle(pipeline);
2775       exec_info.executableIndex = exec_idx;
2776 
2777       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info,
2778                                                        &stat_count, NULL);
2779       if (result != VK_SUCCESS)
2780          goto fail;
2781 
2782       stats = calloc(stat_count, sizeof(*stats));
2783       if (!stats) {
2784          result = VK_ERROR_OUT_OF_HOST_MEMORY;
2785          goto fail;
2786       }
2787 
2788       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info,
2789                                                        &stat_count, stats);
2790       if (result != VK_SUCCESS) {
2791          free(stats);
2792          goto fail;
2793       }
2794 
2795       fprintf(output, "\n%s:\n", radv_get_shader_name(&shader->info, stage));
2796       fprintf(output, "*** SHADER STATS ***\n");
2797 
2798       for (unsigned i = 0; i < stat_count; i++) {
2799          fprintf(output, "%s: ", stats[i].name);
2800          switch (stats[i].format) {
2801          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR:
2802             fprintf(output, "%s", stats[i].value.b32 == VK_TRUE ? "true" : "false");
2803             break;
2804          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR:
2805             fprintf(output, "%" PRIi64, stats[i].value.i64);
2806             break;
2807          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR:
2808             fprintf(output, "%" PRIu64, stats[i].value.u64);
2809             break;
2810          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR:
2811             fprintf(output, "%f", stats[i].value.f64);
2812             break;
2813          default:
2814             unreachable("Invalid pipeline statistic format");
2815          }
2816          fprintf(output, "\n");
2817       }
2818 
2819       fprintf(output, "********************\n\n\n");
2820 
2821       free(stats);
2822    }
2823 
2824 fail:
2825    free(props);
2826    return result;
2827 }
2828