• 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 "spirv/nir_spirv.h"
32 #include "util/memstream.h"
33 #include "util/mesa-sha1.h"
34 #include "util/u_atomic.h"
35 #include "radv_debug.h"
36 #include "radv_private.h"
37 #include "radv_shader_args.h"
38 
39 #include "util/debug.h"
40 #include "ac_binary.h"
41 #include "ac_exp_param.h"
42 #include "ac_nir.h"
43 #include "ac_rtld.h"
44 #include "aco_interface.h"
45 #include "sid.h"
46 #include "vk_format.h"
47 
48 #ifdef LLVM_AVAILABLE
49 #include "ac_llvm_util.h"
50 #endif
51 
52 void
radv_get_nir_options(struct radv_physical_device * device)53 radv_get_nir_options(struct radv_physical_device *device)
54 {
55    device->nir_options = (nir_shader_compiler_options){
56       .vertex_id_zero_based = true,
57       .lower_scmp = true,
58       .lower_flrp16 = true,
59       .lower_flrp32 = true,
60       .lower_flrp64 = true,
61       .lower_device_index_to_zero = true,
62       .lower_fdiv = true,
63       .lower_fmod = true,
64       .lower_ineg = true,
65       .lower_bitfield_insert_to_bitfield_select = true,
66       .lower_bitfield_extract = true,
67       .lower_pack_snorm_2x16 = true,
68       .lower_pack_snorm_4x8 = true,
69       .lower_pack_unorm_2x16 = true,
70       .lower_pack_unorm_4x8 = true,
71       .lower_pack_half_2x16 = true,
72       .lower_pack_64_2x32 = true,
73       .lower_pack_64_4x16 = true,
74       .lower_pack_32_2x16 = true,
75       .lower_unpack_snorm_2x16 = true,
76       .lower_unpack_snorm_4x8 = true,
77       .lower_unpack_unorm_2x16 = true,
78       .lower_unpack_unorm_4x8 = true,
79       .lower_unpack_half_2x16 = true,
80       .lower_ffma16 = true,
81       .lower_ffma32 = true,
82       .lower_ffma64 = true,
83       .lower_fpow = true,
84       .lower_mul_2x32_64 = true,
85       .lower_rotate = true,
86       .lower_iadd_sat = device->rad_info.chip_class <= GFX8,
87       .has_fsub = true,
88       .has_isub = true,
89       .has_dot_4x8 = device->rad_info.has_accelerated_dot_product,
90       .has_dot_2x16 = device->rad_info.has_accelerated_dot_product,
91       .use_scoped_barrier = true,
92       .max_unroll_iterations = 32,
93       .max_unroll_iterations_aggressive = 128,
94       .use_interpolated_input_intrinsics = true,
95       .vectorize_vec2_16bit = true,
96       /* nir_lower_int64() isn't actually called for the LLVM backend,
97        * but this helps the loop unrolling heuristics. */
98       .lower_int64_options = nir_lower_imul64 | nir_lower_imul_high64 | nir_lower_imul_2x32_64 |
99                              nir_lower_divmod64 | nir_lower_minmax64 | nir_lower_iabs64,
100       .lower_doubles_options = nir_lower_drcp | nir_lower_dsqrt | nir_lower_drsq | nir_lower_ddiv,
101       .divergence_analysis_options = nir_divergence_view_index_uniform,
102    };
103 }
104 
105 bool
radv_can_dump_shader(struct radv_device * device,struct vk_shader_module * module,bool meta_shader)106 radv_can_dump_shader(struct radv_device *device, struct vk_shader_module *module,
107                      bool meta_shader)
108 {
109    if (!(device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS))
110       return false;
111    if (module)
112       return !module->nir || (device->instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS);
113 
114    return meta_shader;
115 }
116 
117 bool
radv_can_dump_shader_stats(struct radv_device * device,struct vk_shader_module * module)118 radv_can_dump_shader_stats(struct radv_device *device, struct vk_shader_module *module)
119 {
120    /* Only dump non-meta shader stats. */
121    return device->instance->debug_flags & RADV_DEBUG_DUMP_SHADER_STATS && module && !module->nir;
122 }
123 
124 void
radv_optimize_nir(const struct radv_device * device,struct nir_shader * shader,bool optimize_conservatively,bool allow_copies)125 radv_optimize_nir(const struct radv_device *device, struct nir_shader *shader,
126                   bool optimize_conservatively, bool allow_copies)
127 {
128    bool progress;
129 
130    do {
131       progress = false;
132 
133       NIR_PASS(progress, shader, nir_split_array_vars, nir_var_function_temp);
134       NIR_PASS(progress, shader, nir_shrink_vec_array_vars, nir_var_function_temp);
135 
136       NIR_PASS_V(shader, nir_lower_vars_to_ssa);
137 
138       if (allow_copies) {
139          /* Only run this pass in the first call to
140           * radv_optimize_nir.  Later calls assume that we've
141           * lowered away any copy_deref instructions and we
142           *  don't want to introduce any more.
143           */
144          NIR_PASS(progress, shader, nir_opt_find_array_copies);
145       }
146 
147       NIR_PASS(progress, shader, nir_opt_copy_prop_vars);
148       NIR_PASS(progress, shader, nir_opt_dead_write_vars);
149       NIR_PASS(progress, shader, nir_remove_dead_variables,
150                nir_var_function_temp | nir_var_shader_in | nir_var_shader_out, NULL);
151 
152       NIR_PASS_V(shader, nir_lower_alu_to_scalar, NULL, NULL);
153       NIR_PASS_V(shader, nir_lower_phis_to_scalar, true);
154 
155       NIR_PASS(progress, shader, nir_copy_prop);
156       NIR_PASS(progress, shader, nir_opt_remove_phis);
157       NIR_PASS(progress, shader, nir_opt_dce);
158       if (nir_opt_trivial_continues(shader)) {
159          progress = true;
160          NIR_PASS(progress, shader, nir_copy_prop);
161          NIR_PASS(progress, shader, nir_opt_remove_phis);
162          NIR_PASS(progress, shader, nir_opt_dce);
163       }
164       NIR_PASS(progress, shader, nir_opt_if, true);
165       NIR_PASS(progress, shader, nir_opt_dead_cf);
166       NIR_PASS(progress, shader, nir_opt_cse);
167       NIR_PASS(progress, shader, nir_opt_peephole_select, 8, true, true);
168       NIR_PASS(progress, shader, nir_opt_constant_folding);
169       NIR_PASS(progress, shader, nir_opt_algebraic);
170 
171       NIR_PASS(progress, shader, nir_opt_undef);
172       NIR_PASS(progress, shader, nir_opt_shrink_vectors,
173                !device->instance->disable_shrink_image_store);
174       if (shader->options->max_unroll_iterations) {
175          NIR_PASS(progress, shader, nir_opt_loop_unroll);
176       }
177    } while (progress && !optimize_conservatively);
178 
179    NIR_PASS(progress, shader, nir_opt_conditional_discard);
180    NIR_PASS(progress, shader, nir_opt_move, nir_move_load_ubo);
181 }
182 
183 void
radv_optimize_nir_algebraic(nir_shader * nir,bool opt_offsets)184 radv_optimize_nir_algebraic(nir_shader *nir, bool opt_offsets)
185 {
186    bool more_algebraic = true;
187    while (more_algebraic) {
188       more_algebraic = false;
189       NIR_PASS_V(nir, nir_copy_prop);
190       NIR_PASS_V(nir, nir_opt_dce);
191       NIR_PASS_V(nir, nir_opt_constant_folding);
192       NIR_PASS_V(nir, nir_opt_cse);
193       NIR_PASS(more_algebraic, nir, nir_opt_algebraic);
194    }
195 
196    if (opt_offsets)
197       NIR_PASS_V(nir, nir_opt_offsets);
198 
199    /* Do late algebraic optimization to turn add(a,
200     * neg(b)) back into subs, then the mandatory cleanup
201     * after algebraic.  Note that it may produce fnegs,
202     * and if so then we need to keep running to squash
203     * fneg(fneg(a)).
204     */
205    bool more_late_algebraic = true;
206    while (more_late_algebraic) {
207       more_late_algebraic = false;
208       NIR_PASS(more_late_algebraic, nir, nir_opt_algebraic_late);
209       NIR_PASS_V(nir, nir_opt_constant_folding);
210       NIR_PASS_V(nir, nir_copy_prop);
211       NIR_PASS_V(nir, nir_opt_dce);
212       NIR_PASS_V(nir, nir_opt_cse);
213    }
214 }
215 
216 static void
shared_var_info(const struct glsl_type * type,unsigned * size,unsigned * align)217 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
218 {
219    assert(glsl_type_is_vector_or_scalar(type));
220 
221    uint32_t comp_size = glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
222    unsigned length = glsl_get_vector_elements(type);
223    *size = comp_size * length, *align = comp_size;
224 }
225 
226 struct radv_shader_debug_data {
227    struct radv_device *device;
228    const struct vk_shader_module *module;
229 };
230 
231 static void
radv_spirv_nir_debug(void * private_data,enum nir_spirv_debug_level level,size_t spirv_offset,const char * message)232 radv_spirv_nir_debug(void *private_data, enum nir_spirv_debug_level level, size_t spirv_offset,
233                      const char *message)
234 {
235    struct radv_shader_debug_data *debug_data = private_data;
236    struct radv_instance *instance = debug_data->device->instance;
237 
238    static const VkDebugReportFlagsEXT vk_flags[] = {
239       [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
240       [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
241       [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
242    };
243    char buffer[256];
244 
245    snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long)spirv_offset, message);
246 
247    vk_debug_report(&instance->vk, vk_flags[level], &debug_data->module->base, 0, 0, "radv", buffer);
248 }
249 
250 static void
radv_compiler_debug(void * private_data,enum radv_compiler_debug_level level,const char * message)251 radv_compiler_debug(void *private_data, enum radv_compiler_debug_level level, const char *message)
252 {
253    struct radv_shader_debug_data *debug_data = private_data;
254    struct radv_instance *instance = debug_data->device->instance;
255 
256    static const VkDebugReportFlagsEXT vk_flags[] = {
257       [RADV_COMPILER_DEBUG_LEVEL_PERFWARN] = VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
258       [RADV_COMPILER_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
259    };
260 
261    /* VK_DEBUG_REPORT_DEBUG_BIT_EXT specifies diagnostic information
262     * from the implementation and layers.
263     */
264    vk_debug_report(&instance->vk, vk_flags[level] | VK_DEBUG_REPORT_DEBUG_BIT_EXT,
265                    &debug_data->module->base, 0, 0, "radv", message);
266 }
267 
268 static nir_ssa_def *
convert_pointer_to_64(nir_builder * b,const struct radv_physical_device * pdev,nir_ssa_def * ptr)269 convert_pointer_to_64(nir_builder *b, const struct radv_physical_device *pdev, nir_ssa_def *ptr)
270 {
271    nir_ssa_def *comp[] = {ptr, nir_imm_int(b, pdev->rad_info.address32_hi)};
272    return nir_pack_64_2x32(b, nir_vec(b, comp, 2));
273 }
274 
275 static bool
lower_intrinsics(nir_shader * nir,const struct radv_pipeline_key * key,const struct radv_pipeline_layout * layout,const struct radv_physical_device * pdev)276 lower_intrinsics(nir_shader *nir, const struct radv_pipeline_key *key,
277                  const struct radv_pipeline_layout *layout, const struct radv_physical_device *pdev)
278 {
279    nir_function_impl *entry = nir_shader_get_entrypoint(nir);
280    bool progress = false;
281    nir_builder b;
282 
283    nir_builder_init(&b, entry);
284 
285    nir_foreach_block (block, entry) {
286       nir_foreach_instr_safe (instr, block) {
287          if (instr->type != nir_instr_type_intrinsic)
288             continue;
289 
290          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
291          b.cursor = nir_before_instr(&intrin->instr);
292 
293          nir_ssa_def *def = NULL;
294          switch (intrin->intrinsic) {
295          case nir_intrinsic_load_vulkan_descriptor:
296             if (nir_intrinsic_desc_type(intrin) == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR) {
297                nir_ssa_def *addr =
298                   convert_pointer_to_64(&b, pdev,
299                                         nir_iadd(&b, nir_channel(&b, intrin->src[0].ssa, 0),
300                                                  nir_channel(&b, intrin->src[0].ssa, 1)));
301 
302                def = nir_build_load_global(&b, 1, 64, addr, .access = ACCESS_NON_WRITEABLE,
303                                            .align_mul = 8, .align_offset = 0);
304             } else {
305                def = nir_vector_insert_imm(&b, intrin->src[0].ssa, nir_imm_int(&b, 0), 2);
306             }
307             break;
308          case nir_intrinsic_vulkan_resource_index: {
309             unsigned desc_set = nir_intrinsic_desc_set(intrin);
310             unsigned binding = nir_intrinsic_binding(intrin);
311             struct radv_descriptor_set_layout *desc_layout = layout->set[desc_set].layout;
312 
313             nir_ssa_def *new_res = nir_vulkan_resource_index(
314                &b, 3, 32, intrin->src[0].ssa, .desc_set = desc_set, .binding = binding,
315                .desc_type = nir_intrinsic_desc_type(intrin));
316 
317             nir_ssa_def *stride;
318             if (desc_layout->binding[binding].type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
319                 desc_layout->binding[binding].type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
320                stride = nir_imm_int(&b, 16);
321             } else {
322                stride = nir_imm_int(&b, desc_layout->binding[binding].size);
323             }
324             def = nir_vector_insert_imm(&b, new_res, stride, 2);
325             break;
326          }
327          case nir_intrinsic_vulkan_resource_reindex: {
328             nir_ssa_def *binding_ptr = nir_channel(&b, intrin->src[0].ssa, 1);
329             nir_ssa_def *stride = nir_channel(&b, intrin->src[0].ssa, 2);
330             binding_ptr = nir_iadd(&b, binding_ptr, nir_imul(&b, intrin->src[1].ssa, stride));
331             def = nir_vector_insert_imm(&b, intrin->src[0].ssa, binding_ptr, 1);
332             break;
333          }
334          case nir_intrinsic_is_sparse_texels_resident:
335             def = nir_ieq_imm(&b, intrin->src[0].ssa, 0);
336             break;
337          case nir_intrinsic_sparse_residency_code_and:
338             def = nir_ior(&b, intrin->src[0].ssa, intrin->src[1].ssa);
339             break;
340          case nir_intrinsic_load_view_index:
341             if (key->has_multiview_view_index)
342                continue;
343             def = nir_imm_zero(&b, 1, 32);
344             break;
345          default:
346             continue;
347          }
348 
349          nir_ssa_def_rewrite_uses(&intrin->dest.ssa, def);
350 
351          nir_instr_remove(instr);
352          progress = true;
353       }
354    }
355 
356    return progress;
357 }
358 
359 static bool
radv_lower_primitive_shading_rate(nir_shader * nir)360 radv_lower_primitive_shading_rate(nir_shader *nir)
361 {
362    nir_function_impl *impl = nir_shader_get_entrypoint(nir);
363    bool progress = false;
364 
365    nir_builder b;
366    nir_builder_init(&b, impl);
367 
368    /* Iterate in reverse order since there should be only one deref store to PRIMITIVE_SHADING_RATE
369     * after lower_io_to_temporaries for vertex shaders.
370     */
371    nir_foreach_block_reverse(block, impl) {
372       nir_foreach_instr_reverse(instr, block) {
373          if (instr->type != nir_instr_type_intrinsic)
374             continue;
375 
376          nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
377          if (intr->intrinsic != nir_intrinsic_store_deref)
378             continue;
379 
380          nir_variable *var = nir_intrinsic_get_var(intr, 0);
381          if (var->data.mode != nir_var_shader_out ||
382              var->data.location != VARYING_SLOT_PRIMITIVE_SHADING_RATE)
383             continue;
384 
385          b.cursor = nir_before_instr(instr);
386 
387          nir_ssa_def *val = nir_ssa_for_src(&b, intr->src[1], 1);
388 
389          /* x_rate = (shadingRate & (Horizontal2Pixels | Horizontal4Pixels)) ? 0x1 : 0x0; */
390          nir_ssa_def *x_rate = nir_iand(&b, val, nir_imm_int(&b, 12));
391          x_rate = nir_b2i32(&b, nir_ine(&b, x_rate, nir_imm_int(&b, 0)));
392 
393          /* y_rate = (shadingRate & (Vertical2Pixels | Vertical4Pixels)) ? 0x1 : 0x0; */
394          nir_ssa_def *y_rate = nir_iand(&b, val, nir_imm_int(&b, 3));
395          y_rate = nir_b2i32(&b, nir_ine(&b, y_rate, nir_imm_int(&b, 0)));
396 
397          /* Bits [2:3] = VRS rate X
398           * Bits [4:5] = VRS rate Y
399           * HW shading rate = (xRate << 2) | (yRate << 4)
400           */
401          nir_ssa_def *out = nir_ior(&b, nir_ishl(&b, x_rate, nir_imm_int(&b, 2)),
402                                         nir_ishl(&b, y_rate, nir_imm_int(&b, 4)));
403 
404          nir_instr_rewrite_src(&intr->instr, &intr->src[1], nir_src_for_ssa(out));
405 
406          progress = true;
407          if (nir->info.stage == MESA_SHADER_VERTEX)
408             return progress;
409       }
410    }
411 
412    return progress;
413 }
414 
415 nir_shader *
radv_shader_compile_to_nir(struct radv_device * device,struct vk_shader_module * module,const char * entrypoint_name,gl_shader_stage stage,const VkSpecializationInfo * spec_info,const struct radv_pipeline_layout * layout,const struct radv_pipeline_key * key)416 radv_shader_compile_to_nir(struct radv_device *device, struct vk_shader_module *module,
417                            const char *entrypoint_name, gl_shader_stage stage,
418                            const VkSpecializationInfo *spec_info,
419                            const struct radv_pipeline_layout *layout,
420                            const struct radv_pipeline_key *key)
421 {
422    unsigned subgroup_size = 64, ballot_bit_size = 64;
423    if (key->cs.compute_subgroup_size) {
424       /* Only compute shaders currently support requiring a
425        * specific subgroup size.
426        */
427       assert(stage == MESA_SHADER_COMPUTE);
428       subgroup_size = key->cs.compute_subgroup_size;
429       ballot_bit_size = key->cs.compute_subgroup_size;
430    }
431 
432    nir_shader *nir;
433 
434    if (module->nir) {
435       /* Some things such as our meta clear/blit code will give us a NIR
436        * shader directly.  In that case, we just ignore the SPIR-V entirely
437        * and just use the NIR shader */
438       nir = module->nir;
439       nir->options = &device->physical_device->nir_options;
440       nir_validate_shader(nir, "in internal shader");
441 
442       assert(exec_list_length(&nir->functions) == 1);
443    } else {
444       uint32_t *spirv = (uint32_t *)module->data;
445       assert(module->size % 4 == 0);
446 
447       if (device->instance->debug_flags & RADV_DEBUG_DUMP_SPIRV)
448          radv_print_spirv(module->data, module->size, stderr);
449 
450       uint32_t num_spec_entries = 0;
451       struct nir_spirv_specialization *spec_entries =
452          vk_spec_info_to_nir_spirv(spec_info, &num_spec_entries);
453       struct radv_shader_debug_data spirv_debug_data = {
454          .device = device,
455          .module = module,
456       };
457       const struct spirv_to_nir_options spirv_options = {
458          .caps =
459             {
460                .amd_fragment_mask = true,
461                .amd_gcn_shader = true,
462                .amd_image_gather_bias_lod = true,
463                .amd_image_read_write_lod = true,
464                .amd_shader_ballot = true,
465                .amd_shader_explicit_vertex_parameter = true,
466                .amd_trinary_minmax = true,
467                .demote_to_helper_invocation = true,
468                .derivative_group = true,
469                .descriptor_array_dynamic_indexing = true,
470                .descriptor_array_non_uniform_indexing = true,
471                .descriptor_indexing = true,
472                .device_group = true,
473                .draw_parameters = true,
474                .float_controls = true,
475                .float16 = device->physical_device->rad_info.has_packed_math_16bit,
476                .float32_atomic_add = true,
477                .float32_atomic_min_max = true,
478                .float64 = true,
479                .float64_atomic_min_max = true,
480                .geometry_streams = true,
481                .groups = true,
482                .image_atomic_int64 = true,
483                .image_ms_array = true,
484                .image_read_without_format = true,
485                .image_write_without_format = true,
486                .int8 = true,
487                .int16 = true,
488                .int64 = true,
489                .int64_atomics = true,
490                .min_lod = true,
491                .multiview = true,
492                .physical_storage_buffer_address = true,
493                .post_depth_coverage = true,
494                .ray_tracing = true,
495                .runtime_descriptor_array = true,
496                .shader_clock = true,
497                .shader_viewport_index_layer = true,
498                .sparse_residency = true,
499                .stencil_export = true,
500                .storage_8bit = true,
501                .storage_16bit = true,
502                .storage_image_ms = true,
503                .subgroup_arithmetic = true,
504                .subgroup_ballot = true,
505                .subgroup_basic = true,
506                .subgroup_quad = true,
507                .subgroup_shuffle = true,
508                .subgroup_uniform_control_flow = true,
509                .subgroup_vote = true,
510                .tessellation = true,
511                .transform_feedback = true,
512                .variable_pointers = true,
513                .vk_memory_model = true,
514                .vk_memory_model_device_scope = true,
515                .fragment_shading_rate = device->physical_device->rad_info.chip_class >= GFX10_3,
516                .workgroup_memory_explicit_layout = true,
517             },
518          .ubo_addr_format = nir_address_format_vec2_index_32bit_offset,
519          .ssbo_addr_format = nir_address_format_vec2_index_32bit_offset,
520          .phys_ssbo_addr_format = nir_address_format_64bit_global,
521          .push_const_addr_format = nir_address_format_logical,
522          .shared_addr_format = nir_address_format_32bit_offset,
523          .constant_addr_format = nir_address_format_64bit_global,
524          .use_deref_buffer_array_length = true,
525          .debug =
526             {
527                .func = radv_spirv_nir_debug,
528                .private_data = &spirv_debug_data,
529             },
530       };
531       nir = spirv_to_nir(spirv, module->size / 4, spec_entries, num_spec_entries, stage,
532                          entrypoint_name, &spirv_options, &device->physical_device->nir_options);
533       assert(nir->info.stage == stage);
534       nir_validate_shader(nir, "after spirv_to_nir");
535 
536       free(spec_entries);
537 
538       const struct nir_lower_sysvals_to_varyings_options sysvals_to_varyings = {
539          .point_coord = true,
540       };
541       NIR_PASS_V(nir, nir_lower_sysvals_to_varyings, &sysvals_to_varyings);
542 
543       /* We have to lower away local constant initializers right before we
544        * inline functions.  That way they get properly initialized at the top
545        * of the function and not at the top of its caller.
546        */
547       NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_function_temp);
548       NIR_PASS_V(nir, nir_lower_returns);
549       NIR_PASS_V(nir, nir_inline_functions);
550       NIR_PASS_V(nir, nir_copy_prop);
551       NIR_PASS_V(nir, nir_opt_deref);
552 
553       /* Pick off the single entrypoint that we want */
554       foreach_list_typed_safe(nir_function, func, node, &nir->functions)
555       {
556          if (func->is_entrypoint)
557             func->name = ralloc_strdup(func, "main");
558          else
559             exec_node_remove(&func->node);
560       }
561       assert(exec_list_length(&nir->functions) == 1);
562 
563       /* Make sure we lower constant initializers on output variables so that
564        * nir_remove_dead_variables below sees the corresponding stores
565        */
566       NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_shader_out);
567 
568       /* Now that we've deleted all but the main function, we can go ahead and
569        * lower the rest of the constant initializers.
570        */
571       NIR_PASS_V(nir, nir_lower_variable_initializers, ~0);
572 
573       /* Split member structs.  We do this before lower_io_to_temporaries so that
574        * it doesn't lower system values to temporaries by accident.
575        */
576       NIR_PASS_V(nir, nir_split_var_copies);
577       NIR_PASS_V(nir, nir_split_per_member_structs);
578 
579       if (nir->info.stage == MESA_SHADER_FRAGMENT)
580          NIR_PASS_V(nir, nir_lower_io_to_vector, nir_var_shader_out);
581       if (nir->info.stage == MESA_SHADER_FRAGMENT)
582          NIR_PASS_V(nir, nir_lower_input_attachments,
583                     &(nir_input_attachment_options){
584                        .use_fragcoord_sysval = true,
585                        .use_layer_id_sysval = false,
586                     });
587 
588       NIR_PASS_V(nir, nir_remove_dead_variables,
589                  nir_var_shader_in | nir_var_shader_out | nir_var_system_value | nir_var_mem_shared,
590                  NULL);
591 
592       /* Variables can make nir_propagate_invariant more conservative
593        * than it needs to be.
594        */
595       NIR_PASS_V(nir, nir_lower_global_vars_to_local);
596       NIR_PASS_V(nir, nir_lower_vars_to_ssa);
597 
598       NIR_PASS_V(nir, nir_propagate_invariant, key->invariant_geom);
599 
600       NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
601 
602       NIR_PASS_V(nir, nir_lower_discard_or_demote, key->ps.lower_discard_to_demote);
603 
604       nir_lower_doubles_options lower_doubles = nir->options->lower_doubles_options;
605 
606       if (device->physical_device->rad_info.chip_class == GFX6) {
607          /* GFX6 doesn't support v_floor_f64 and the precision
608           * of v_fract_f64 which is used to implement 64-bit
609           * floor is less than what Vulkan requires.
610           */
611          lower_doubles |= nir_lower_dfloor;
612       }
613 
614       NIR_PASS_V(nir, nir_lower_doubles, NULL, lower_doubles);
615    }
616 
617    NIR_PASS_V(nir, nir_lower_system_values);
618    NIR_PASS_V(nir, nir_lower_compute_system_values, NULL);
619 
620    /* Vulkan uses the separate-shader linking model */
621    nir->info.separate_shader = true;
622 
623    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
624 
625    if (nir->info.stage == MESA_SHADER_GEOMETRY) {
626       unsigned nir_gs_flags = nir_lower_gs_intrinsics_per_stream;
627 
628       if (key->use_ngg && !radv_use_llvm_for_stage(device, stage)) {
629          /* ACO needs NIR to do some of the hard lifting */
630          nir_gs_flags |= nir_lower_gs_intrinsics_count_primitives |
631                          nir_lower_gs_intrinsics_count_vertices_per_primitive |
632                          nir_lower_gs_intrinsics_overwrite_incomplete;
633       }
634 
635       nir_lower_gs_intrinsics(nir, nir_gs_flags);
636    }
637 
638    static const nir_lower_tex_options tex_options = {
639       .lower_txp = ~0,
640       .lower_tg4_offsets = true,
641       .lower_txs_cube_array = true,
642       .lower_to_fragment_fetch_amd = true,
643    };
644 
645    nir_lower_tex(nir, &tex_options);
646 
647    static const nir_lower_image_options image_options = {
648       .lower_cube_size = true,
649    };
650 
651    nir_lower_image(nir, &image_options);
652 
653    nir_lower_vars_to_ssa(nir);
654 
655    if (nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_GEOMETRY ||
656        nir->info.stage == MESA_SHADER_FRAGMENT) {
657       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, true);
658    } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
659       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, false);
660    }
661 
662    nir_split_var_copies(nir);
663 
664    nir_lower_global_vars_to_local(nir);
665    nir_remove_dead_variables(nir, nir_var_function_temp, NULL);
666    bool gfx7minus = device->physical_device->rad_info.chip_class <= GFX7;
667    nir_lower_subgroups(nir, &(struct nir_lower_subgroups_options){
668                                .subgroup_size = subgroup_size,
669                                .ballot_bit_size = ballot_bit_size,
670                                .ballot_components = 1,
671                                .lower_to_scalar = 1,
672                                .lower_subgroup_masks = 1,
673                                .lower_shuffle = 1,
674                                .lower_shuffle_to_32bit = 1,
675                                .lower_vote_eq = 1,
676                                .lower_quad_broadcast_dynamic = 1,
677                                .lower_quad_broadcast_dynamic_to_const = gfx7minus,
678                                .lower_shuffle_to_swizzle_amd = 1,
679                             });
680 
681    nir_lower_load_const_to_scalar(nir);
682 
683    if (!key->optimisations_disabled)
684       radv_optimize_nir(device, nir, false, true);
685 
686    /* call radv_nir_lower_ycbcr_textures() late as there might still be
687     * tex with undef texture/sampler before first optimization */
688    NIR_PASS_V(nir, radv_nir_lower_ycbcr_textures, layout);
689 
690    /* We call nir_lower_var_copies() after the first radv_optimize_nir()
691     * to remove any copies introduced by nir_opt_find_array_copies().
692     */
693    nir_lower_var_copies(nir);
694 
695    unsigned lower_flrp = (nir->options->lower_flrp16 ? 16 : 0) |
696                          (nir->options->lower_flrp32 ? 32 : 0) |
697                          (nir->options->lower_flrp64 ? 64 : 0);
698    if (lower_flrp != 0) {
699       if (nir_lower_flrp(nir, lower_flrp, false /* always_precise */))
700          NIR_PASS_V(nir, nir_opt_constant_folding);
701    }
702 
703    const nir_opt_access_options opt_access_options = {
704       .is_vulkan = true,
705       .infer_non_readable = true,
706    };
707    NIR_PASS_V(nir, nir_opt_access, &opt_access_options);
708 
709    NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_push_const, nir_address_format_32bit_offset);
710 
711    NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ubo | nir_var_mem_ssbo,
712               nir_address_format_vec2_index_32bit_offset);
713 
714    NIR_PASS_V(nir, lower_intrinsics, key, layout, device->physical_device);
715 
716    /* Lower deref operations for compute shared memory. */
717    if (nir->info.stage == MESA_SHADER_COMPUTE) {
718       if (!nir->info.shared_memory_explicit_layout) {
719          NIR_PASS_V(nir, nir_lower_vars_to_explicit_types, nir_var_mem_shared, shared_var_info);
720       }
721       NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_shared, nir_address_format_32bit_offset);
722 
723       if (nir->info.zero_initialize_shared_memory && nir->info.shared_size > 0) {
724          const unsigned chunk_size = 16; /* max single store size */
725          const unsigned shared_size = ALIGN(nir->info.shared_size, chunk_size);
726          NIR_PASS_V(nir, nir_zero_initialize_shared_memory, shared_size, chunk_size);
727       }
728    }
729 
730    nir_lower_explicit_io(nir, nir_var_mem_global | nir_var_mem_constant,
731                          nir_address_format_64bit_global);
732 
733    /* Lower large variables that are always constant with load_constant
734     * intrinsics, which get turned into PC-relative loads from a data
735     * section next to the shader.
736     */
737    NIR_PASS_V(nir, nir_opt_large_constants, glsl_get_natural_size_align_bytes, 16);
738 
739    /* Lower primitive shading rate to match HW requirements. */
740    if ((nir->info.stage == MESA_SHADER_VERTEX ||
741         nir->info.stage == MESA_SHADER_GEOMETRY) &&
742        nir->info.outputs_written & BITFIELD64_BIT(VARYING_SLOT_PRIMITIVE_SHADING_RATE)) {
743       NIR_PASS_V(nir, radv_lower_primitive_shading_rate);
744    }
745 
746    /* Indirect lowering must be called after the radv_optimize_nir() loop
747     * has been called at least once. Otherwise indirect lowering can
748     * bloat the instruction count of the loop and cause it to be
749     * considered too large for unrolling.
750     */
751    if (ac_nir_lower_indirect_derefs(nir, device->physical_device->rad_info.chip_class) &&
752        !key->optimisations_disabled && nir->info.stage != MESA_SHADER_COMPUTE) {
753       /* Optimize the lowered code before the linking optimizations. */
754       radv_optimize_nir(device, nir, false, false);
755    }
756 
757    return nir;
758 }
759 
760 static int
type_size_vec4(const struct glsl_type * type,bool bindless)761 type_size_vec4(const struct glsl_type *type, bool bindless)
762 {
763    return glsl_count_attribute_slots(type, false);
764 }
765 
766 static nir_variable *
find_layer_in_var(nir_shader * nir)767 find_layer_in_var(nir_shader *nir)
768 {
769    nir_variable *var = nir_find_variable_with_location(nir, nir_var_shader_in, VARYING_SLOT_LAYER);
770    if (var != NULL)
771       return var;
772 
773    var = nir_variable_create(nir, nir_var_shader_in, glsl_int_type(), "layer id");
774    var->data.location = VARYING_SLOT_LAYER;
775    var->data.interpolation = INTERP_MODE_FLAT;
776    return var;
777 }
778 
779 /* We use layered rendering to implement multiview, which means we need to map
780  * view_index to gl_Layer. The code generates a load from the layer_id sysval,
781  * but since we don't have a way to get at this information from the fragment
782  * shader, we also need to lower this to the gl_Layer varying.  This pass
783  * lowers both to a varying load from the LAYER slot, before lowering io, so
784  * that nir_assign_var_locations() will give the LAYER varying the correct
785  * driver_location.
786  */
787 
788 static bool
lower_view_index(nir_shader * nir)789 lower_view_index(nir_shader *nir)
790 {
791    bool progress = false;
792    nir_function_impl *entry = nir_shader_get_entrypoint(nir);
793    nir_builder b;
794    nir_builder_init(&b, entry);
795 
796    nir_variable *layer = NULL;
797    nir_foreach_block (block, entry) {
798       nir_foreach_instr_safe (instr, block) {
799          if (instr->type != nir_instr_type_intrinsic)
800             continue;
801 
802          nir_intrinsic_instr *load = nir_instr_as_intrinsic(instr);
803          if (load->intrinsic != nir_intrinsic_load_view_index)
804             continue;
805 
806          if (!layer)
807             layer = find_layer_in_var(nir);
808 
809          b.cursor = nir_before_instr(instr);
810          nir_ssa_def *def = nir_load_var(&b, layer);
811          nir_ssa_def_rewrite_uses(&load->dest.ssa, def);
812 
813          nir_instr_remove(instr);
814          progress = true;
815       }
816    }
817 
818    return progress;
819 }
820 
821 void
radv_lower_io(struct radv_device * device,nir_shader * nir)822 radv_lower_io(struct radv_device *device, nir_shader *nir)
823 {
824    if (nir->info.stage == MESA_SHADER_COMPUTE)
825       return;
826 
827    if (nir->info.stage == MESA_SHADER_FRAGMENT) {
828       NIR_PASS_V(nir, lower_view_index);
829       nir_assign_io_var_locations(nir, nir_var_shader_in, &nir->num_inputs, MESA_SHADER_FRAGMENT);
830    }
831 
832    /* The RADV/LLVM backend expects 64-bit IO to be lowered. */
833    nir_lower_io_options options =
834       radv_use_llvm_for_stage(device, nir->info.stage) ? nir_lower_io_lower_64bit_to_32 : 0;
835 
836    NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out, type_size_vec4, options);
837 
838    /* This pass needs actual constants */
839    nir_opt_constant_folding(nir);
840 
841    NIR_PASS_V(nir, nir_io_add_const_offset_to_base, nir_var_shader_in | nir_var_shader_out);
842 }
843 
844 bool
radv_lower_io_to_mem(struct radv_device * device,struct nir_shader * nir,const struct radv_shader_info * info,const struct radv_pipeline_key * pl_key)845 radv_lower_io_to_mem(struct radv_device *device, struct nir_shader *nir,
846                      const struct radv_shader_info *info, const struct radv_pipeline_key *pl_key)
847 {
848    if (nir->info.stage == MESA_SHADER_VERTEX) {
849       if (info->vs.as_ls) {
850          ac_nir_lower_ls_outputs_to_mem(nir, info->vs.tcs_in_out_eq,
851                                         info->vs.tcs_temp_only_input_mask,
852                                         info->vs.num_linked_outputs);
853          return true;
854       } else if (info->vs.as_es) {
855          ac_nir_lower_es_outputs_to_mem(nir, device->physical_device->rad_info.chip_class,
856                                         info->vs.num_linked_outputs);
857          return true;
858       }
859    } else if (nir->info.stage == MESA_SHADER_TESS_CTRL) {
860       ac_nir_lower_hs_inputs_to_mem(nir, info->vs.tcs_in_out_eq, info->tcs.num_linked_inputs);
861       ac_nir_lower_hs_outputs_to_mem(
862          nir, device->physical_device->rad_info.chip_class, info->tcs.tes_reads_tess_factors,
863          info->tcs.tes_inputs_read, info->tcs.tes_patch_inputs_read, info->tcs.num_linked_inputs,
864          info->tcs.num_linked_outputs, info->tcs.num_linked_patch_outputs, true);
865       ac_nir_lower_tess_to_const(nir, pl_key->tcs.tess_input_vertices, info->num_tess_patches,
866                                  ac_nir_lower_patch_vtx_in | ac_nir_lower_num_patches);
867 
868       return true;
869    } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
870       ac_nir_lower_tes_inputs_to_mem(nir, info->tes.num_linked_inputs,
871                                      info->tes.num_linked_patch_inputs);
872       ac_nir_lower_tess_to_const(nir, nir->info.tess.tcs_vertices_out, info->num_tess_patches,
873                                  ac_nir_lower_patch_vtx_in | ac_nir_lower_num_patches);
874 
875       if (info->tes.as_es) {
876          ac_nir_lower_es_outputs_to_mem(nir, device->physical_device->rad_info.chip_class,
877                                         info->tes.num_linked_outputs);
878       }
879 
880       return true;
881    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
882       ac_nir_lower_gs_inputs_to_mem(nir, device->physical_device->rad_info.chip_class,
883                                     info->gs.num_linked_inputs);
884       return true;
885    }
886 
887    return false;
888 }
889 
890 bool
radv_consider_culling(struct radv_device * device,struct nir_shader * nir,uint64_t ps_inputs_read,unsigned num_vertices_per_primitive,const struct radv_shader_info * info)891 radv_consider_culling(struct radv_device *device, struct nir_shader *nir, uint64_t ps_inputs_read,
892                       unsigned num_vertices_per_primitive, const struct radv_shader_info *info)
893 {
894    /* Culling doesn't make sense for meta shaders. */
895    if (!!nir->info.name)
896       return false;
897 
898    /* We don't support culling with multiple viewports yet. */
899    if (nir->info.outputs_written & (VARYING_BIT_VIEWPORT | VARYING_BIT_VIEWPORT_MASK))
900       return false;
901 
902    /* We don't support culling with vertex shader prologs. */
903    if (info->vs.has_prolog)
904       return false;
905 
906    if (!device->physical_device->use_ngg_culling)
907       return false;
908 
909    /* Shader based culling efficiency can depend on PS throughput.
910     * Estimate an upper limit for PS input param count based on GPU info.
911     */
912    unsigned max_ps_params;
913    unsigned max_render_backends = device->physical_device->rad_info.max_render_backends;
914    unsigned max_se = device->physical_device->rad_info.max_se;
915 
916    if (max_render_backends / max_se == 4)
917       max_ps_params = 6; /* Sienna Cichlid and other GFX10.3 dGPUs. */
918    else
919       max_ps_params = 4; /* Navi 1x. */
920 
921    /* TODO: consider other heuristics here, such as PS execution time */
922    if (util_bitcount64(ps_inputs_read & ~VARYING_BIT_POS) > max_ps_params)
923       return false;
924 
925    /* Only triangle culling is supported. */
926    if (num_vertices_per_primitive != 3)
927       return false;
928 
929    /* When the shader writes memory, it is difficult to guarantee correctness.
930     * Future work:
931     * - if only write-only SSBOs are used
932     * - if we can prove that non-position outputs don't rely on memory stores
933     * then may be okay to keep the memory stores in the 1st shader part, and delete them from the 2nd.
934     */
935    if (nir->info.writes_memory)
936       return false;
937 
938    /* When the shader relies on the subgroup invocation ID, we'd break it, because the ID changes after the culling.
939     * Future work: try to save this to LDS and reload, but it can still be broken in subtle ways.
940     */
941    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_SUBGROUP_INVOCATION))
942       return false;
943 
944    return true;
945 }
946 
radv_lower_ngg(struct radv_device * device,struct nir_shader * nir,const struct radv_shader_info * info,const struct radv_pipeline_key * pl_key)947 void radv_lower_ngg(struct radv_device *device, struct nir_shader *nir,
948                     const struct radv_shader_info *info,
949                     const struct radv_pipeline_key *pl_key)
950 {
951    /* TODO: support the LLVM backend with the NIR lowering */
952    assert(!radv_use_llvm_for_stage(device, nir->info.stage));
953 
954    assert(nir->info.stage == MESA_SHADER_VERTEX ||
955           nir->info.stage == MESA_SHADER_TESS_EVAL ||
956           nir->info.stage == MESA_SHADER_GEOMETRY);
957 
958    const struct gfx10_ngg_info *ngg_info = &info->ngg_info;
959    unsigned num_vertices_per_prim = 3;
960 
961    /* Get the number of vertices per input primitive */
962    if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
963       if (nir->info.tess.point_mode)
964          num_vertices_per_prim = 1;
965       else if (nir->info.tess.primitive_mode == GL_ISOLINES)
966          num_vertices_per_prim = 2;
967 
968       /* Manually mark the primitive ID used, so the shader can repack it. */
969       if (info->tes.outinfo.export_prim_id)
970          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_PRIMITIVE_ID);
971 
972    } else if (nir->info.stage == MESA_SHADER_VERTEX) {
973       /* Need to add 1, because: V_028A6C_POINTLIST=0, V_028A6C_LINESTRIP=1, V_028A6C_TRISTRIP=2, etc. */
974       num_vertices_per_prim = si_conv_prim_to_gs_out(pl_key->vs.topology) + 1;
975 
976       /* Manually mark the instance ID used, so the shader can repack it. */
977       if (pl_key->vs.instance_rate_inputs)
978          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID);
979 
980    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
981       num_vertices_per_prim = nir->info.gs.vertices_in;
982    } else {
983       unreachable("NGG needs to be VS, TES or GS.");
984    }
985 
986    /* Invocations that process an input vertex */
987    unsigned max_vtx_in = MIN2(256, ngg_info->enable_vertex_grouping ? ngg_info->hw_max_esverts : num_vertices_per_prim * ngg_info->max_gsprims);
988 
989    if (nir->info.stage == MESA_SHADER_VERTEX ||
990        nir->info.stage == MESA_SHADER_TESS_EVAL) {
991       bool export_prim_id;
992 
993       assert(info->is_ngg);
994 
995       if (info->has_ngg_culling)
996          radv_optimize_nir_algebraic(nir, false);
997 
998       if (nir->info.stage == MESA_SHADER_VERTEX) {
999          export_prim_id = info->vs.outinfo.export_prim_id;
1000       } else {
1001          export_prim_id = info->tes.outinfo.export_prim_id;
1002       }
1003 
1004       ac_nir_lower_ngg_nogs(
1005          nir,
1006          max_vtx_in,
1007          num_vertices_per_prim,
1008          info->workgroup_size,
1009          info->wave_size,
1010          info->has_ngg_culling,
1011          info->has_ngg_early_prim_export,
1012          info->is_ngg_passthrough,
1013          export_prim_id,
1014          pl_key->vs.provoking_vtx_last,
1015          false,
1016          pl_key->vs.instance_rate_inputs);
1017    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
1018       assert(info->is_ngg);
1019       ac_nir_lower_ngg_gs(
1020          nir, info->wave_size, info->workgroup_size,
1021          info->ngg_info.esgs_ring_size,
1022          info->gs.gsvs_vertex_size,
1023          info->ngg_info.ngg_emit_size * 4u,
1024          pl_key->vs.provoking_vtx_last);
1025    } else {
1026       unreachable("invalid SW stage passed to radv_lower_ngg");
1027    }
1028 }
1029 
1030 static unsigned
get_size_class(unsigned size,bool round_up)1031 get_size_class(unsigned size, bool round_up)
1032 {
1033    size = round_up ? util_logbase2_ceil(size) : util_logbase2(size);
1034    unsigned size_class =
1035       MAX2(size, RADV_SHADER_ALLOC_MIN_SIZE_CLASS) - RADV_SHADER_ALLOC_MIN_SIZE_CLASS;
1036    return MIN2(size_class, RADV_SHADER_ALLOC_NUM_FREE_LISTS - 1);
1037 }
1038 
1039 static void
remove_hole(struct radv_device * device,union radv_shader_arena_block * hole)1040 remove_hole(struct radv_device *device, union radv_shader_arena_block *hole)
1041 {
1042    unsigned size_class = get_size_class(hole->size, false);
1043    list_del(&hole->freelist);
1044    if (list_is_empty(&device->shader_free_lists[size_class]))
1045       device->shader_free_list_mask &= ~(1u << size_class);
1046 }
1047 
1048 static void
add_hole(struct radv_device * device,union radv_shader_arena_block * hole)1049 add_hole(struct radv_device *device, union radv_shader_arena_block *hole)
1050 {
1051    unsigned size_class = get_size_class(hole->size, false);
1052    list_addtail(&hole->freelist, &device->shader_free_lists[size_class]);
1053    device->shader_free_list_mask |= 1u << size_class;
1054 }
1055 
1056 static union radv_shader_arena_block *
alloc_block_obj(struct radv_device * device)1057 alloc_block_obj(struct radv_device *device)
1058 {
1059    if (!list_is_empty(&device->shader_block_obj_pool)) {
1060       union radv_shader_arena_block *block =
1061          list_first_entry(&device->shader_block_obj_pool, union radv_shader_arena_block, pool);
1062       list_del(&block->pool);
1063       return block;
1064    }
1065 
1066    return malloc(sizeof(union radv_shader_arena_block));
1067 }
1068 
1069 static void
free_block_obj(struct radv_device * device,union radv_shader_arena_block * block)1070 free_block_obj(struct radv_device *device, union radv_shader_arena_block *block)
1071 {
1072    list_add(&block->pool, &device->shader_block_obj_pool);
1073 }
1074 
1075 /* Segregated fit allocator, implementing a good-fit allocation policy.
1076  *
1077  * This is an variation of sequential fit allocation with several lists of free blocks ("holes")
1078  * instead of one. Each list of holes only contains holes of a certain range of sizes, so holes that
1079  * are too small can easily be ignored while allocating. Because this also ignores holes that are
1080  * larger than necessary (approximating best-fit allocation), this could be described as a
1081  * "good-fit" allocator.
1082  *
1083  * Typically, shaders are allocated and only free'd when the device is destroyed. For this pattern,
1084  * this should allocate blocks for shaders fast and with no fragmentation, while still allowing
1085  * free'd memory to be re-used.
1086  */
1087 static union radv_shader_arena_block *
alloc_shader_memory(struct radv_device * device,uint32_t size,void * ptr)1088 alloc_shader_memory(struct radv_device *device, uint32_t size, void *ptr)
1089 {
1090    size = align(size, RADV_SHADER_ALLOC_ALIGNMENT);
1091 
1092    mtx_lock(&device->shader_arena_mutex);
1093 
1094    /* Try to use an existing hole. Unless the shader is very large, this should only have to look
1095     * at the first one available.
1096     */
1097    unsigned free_list_mask = BITFIELD_MASK(RADV_SHADER_ALLOC_NUM_FREE_LISTS);
1098    unsigned size_class =
1099       ffs(device->shader_free_list_mask & (free_list_mask << get_size_class(size, true)));
1100    if (size_class) {
1101       size_class--;
1102 
1103       list_for_each_entry(union radv_shader_arena_block, hole,
1104                           &device->shader_free_lists[size_class], freelist)
1105       {
1106          if (hole->size < size)
1107             continue;
1108 
1109          assert(hole->offset % RADV_SHADER_ALLOC_ALIGNMENT == 0);
1110 
1111          if (size == hole->size) {
1112             remove_hole(device, hole);
1113             hole->freelist.next = ptr;
1114             mtx_unlock(&device->shader_arena_mutex);
1115             return hole;
1116          } else {
1117             union radv_shader_arena_block *alloc = alloc_block_obj(device);
1118             if (!alloc) {
1119                mtx_unlock(&device->shader_arena_mutex);
1120                return NULL;
1121             }
1122             list_addtail(&alloc->list, &hole->list);
1123             alloc->freelist.prev = NULL;
1124             alloc->freelist.next = ptr;
1125             alloc->arena = hole->arena;
1126             alloc->offset = hole->offset;
1127             alloc->size = size;
1128 
1129             remove_hole(device, hole);
1130             hole->offset += size;
1131             hole->size -= size;
1132             add_hole(device, hole);
1133 
1134             mtx_unlock(&device->shader_arena_mutex);
1135             return alloc;
1136          }
1137       }
1138    }
1139 
1140    /* Allocate a new shader arena. */
1141    struct radv_shader_arena *arena = calloc(1, sizeof(struct radv_shader_arena));
1142    union radv_shader_arena_block *alloc = NULL, *hole = NULL;
1143    if (!arena)
1144       goto fail;
1145 
1146    unsigned arena_size = MAX2(RADV_SHADER_ALLOC_MIN_ARENA_SIZE, size);
1147    VkResult result = device->ws->buffer_create(
1148       device->ws, arena_size, RADV_SHADER_ALLOC_ALIGNMENT, RADEON_DOMAIN_VRAM,
1149       RADEON_FLAG_NO_INTERPROCESS_SHARING | RADEON_FLAG_32BIT |
1150          (device->physical_device->rad_info.cpdma_prefetch_writes_memory ? 0
1151                                                                          : RADEON_FLAG_READ_ONLY),
1152       RADV_BO_PRIORITY_SHADER, 0, &arena->bo);
1153    if (result != VK_SUCCESS)
1154       goto fail;
1155 
1156    list_inithead(&arena->entries);
1157 
1158    arena->ptr = (char *)device->ws->buffer_map(arena->bo);
1159    if (!arena->ptr)
1160       goto fail;
1161 
1162    alloc = alloc_block_obj(device);
1163    hole = arena_size - size > 0 ? alloc_block_obj(device) : alloc;
1164    if (!alloc || !hole)
1165       goto fail;
1166    list_addtail(&alloc->list, &arena->entries);
1167    alloc->freelist.prev = NULL;
1168    alloc->freelist.next = ptr;
1169    alloc->arena = arena;
1170    alloc->offset = 0;
1171    alloc->size = size;
1172 
1173    if (hole != alloc) {
1174       hole->arena = arena;
1175       hole->offset = size;
1176       hole->size = arena_size - size;
1177 
1178       list_addtail(&hole->list, &arena->entries);
1179       add_hole(device, hole);
1180    }
1181 
1182    list_addtail(&arena->list, &device->shader_arenas);
1183 
1184    mtx_unlock(&device->shader_arena_mutex);
1185    return alloc;
1186 
1187 fail:
1188    mtx_unlock(&device->shader_arena_mutex);
1189    free(alloc);
1190    free(hole);
1191    if (arena && arena->bo)
1192       device->ws->buffer_destroy(device->ws, arena->bo);
1193    free(arena);
1194    return NULL;
1195 }
1196 
1197 static union radv_shader_arena_block *
get_hole(struct radv_shader_arena * arena,struct list_head * head)1198 get_hole(struct radv_shader_arena *arena, struct list_head *head)
1199 {
1200    if (head == &arena->entries)
1201       return NULL;
1202 
1203    union radv_shader_arena_block *hole = LIST_ENTRY(union radv_shader_arena_block, head, list);
1204    return hole->freelist.prev ? hole : NULL;
1205 }
1206 
1207 static void
free_shader_memory(struct radv_device * device,union radv_shader_arena_block * alloc)1208 free_shader_memory(struct radv_device *device, union radv_shader_arena_block *alloc)
1209 {
1210    mtx_lock(&device->shader_arena_mutex);
1211 
1212    union radv_shader_arena_block *hole_prev = get_hole(alloc->arena, alloc->list.prev);
1213    union radv_shader_arena_block *hole_next = get_hole(alloc->arena, alloc->list.next);
1214 
1215    union radv_shader_arena_block *hole = alloc;
1216 
1217    /* merge with previous hole */
1218    if (hole_prev) {
1219       remove_hole(device, hole_prev);
1220 
1221       hole_prev->size += hole->size;
1222       list_del(&hole->list);
1223       free_block_obj(device, hole);
1224 
1225       hole = hole_prev;
1226    }
1227 
1228    /* merge with next hole */
1229    if (hole_next) {
1230       remove_hole(device, hole_next);
1231 
1232       hole_next->offset -= hole->size;
1233       hole_next->size += hole->size;
1234       list_del(&hole->list);
1235       free_block_obj(device, hole);
1236 
1237       hole = hole_next;
1238    }
1239 
1240    if (list_is_singular(&hole->list)) {
1241       struct radv_shader_arena *arena = hole->arena;
1242       free_block_obj(device, hole);
1243 
1244       device->ws->buffer_destroy(device->ws, arena->bo);
1245       list_del(&arena->list);
1246       free(arena);
1247    } else {
1248       add_hole(device, hole);
1249    }
1250 
1251    mtx_unlock(&device->shader_arena_mutex);
1252 }
1253 
1254 static void *
radv_alloc_shader_memory(struct radv_device * device,struct radv_shader_variant * shader)1255 radv_alloc_shader_memory(struct radv_device *device, struct radv_shader_variant *shader)
1256 {
1257    shader->alloc = alloc_shader_memory(device, shader->code_size, shader);
1258    if (!shader->alloc)
1259       return NULL;
1260    shader->bo = shader->alloc->arena->bo;
1261    return shader->alloc->arena->ptr + shader->alloc->offset;
1262 }
1263 
1264 void
radv_init_shader_arenas(struct radv_device * device)1265 radv_init_shader_arenas(struct radv_device *device)
1266 {
1267    mtx_init(&device->shader_arena_mutex, mtx_plain);
1268 
1269    device->shader_free_list_mask = 0;
1270 
1271    list_inithead(&device->shader_arenas);
1272    list_inithead(&device->shader_block_obj_pool);
1273    for (unsigned i = 0; i < RADV_SHADER_ALLOC_NUM_FREE_LISTS; i++)
1274       list_inithead(&device->shader_free_lists[i]);
1275 }
1276 
1277 void
radv_destroy_shader_arenas(struct radv_device * device)1278 radv_destroy_shader_arenas(struct radv_device *device)
1279 {
1280    list_for_each_entry_safe(union radv_shader_arena_block, block, &device->shader_block_obj_pool,
1281                             pool) free(block);
1282 
1283    list_for_each_entry_safe(struct radv_shader_arena, arena, &device->shader_arenas, list)
1284    {
1285       device->ws->buffer_destroy(device->ws, arena->bo);
1286       free(arena);
1287    }
1288    mtx_destroy(&device->shader_arena_mutex);
1289 }
1290 
1291 /* For the UMR disassembler. */
1292 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
1293 #define DEBUGGER_NUM_MARKERS        5
1294 
1295 static unsigned
radv_get_shader_binary_size(size_t code_size)1296 radv_get_shader_binary_size(size_t code_size)
1297 {
1298    return code_size + DEBUGGER_NUM_MARKERS * 4;
1299 }
1300 
1301 static bool
radv_should_use_wgp_mode(const struct radv_device * device,gl_shader_stage stage,const struct radv_shader_info * info)1302 radv_should_use_wgp_mode(const struct radv_device *device, gl_shader_stage stage,
1303                          const struct radv_shader_info *info)
1304 {
1305    enum chip_class chip = device->physical_device->rad_info.chip_class;
1306    switch (stage) {
1307    case MESA_SHADER_COMPUTE:
1308    case MESA_SHADER_TESS_CTRL:
1309       return chip >= GFX10;
1310    case MESA_SHADER_GEOMETRY:
1311       return chip == GFX10 || (chip >= GFX10_3 && !info->is_ngg);
1312    case MESA_SHADER_VERTEX:
1313    case MESA_SHADER_TESS_EVAL:
1314       return chip == GFX10 && info->is_ngg;
1315    default:
1316       return false;
1317    }
1318 }
1319 
1320 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,struct ac_shader_config * config_out)1321 radv_postprocess_config(const struct radv_device *device, const struct ac_shader_config *config_in,
1322                         const struct radv_shader_info *info, gl_shader_stage stage,
1323                         struct ac_shader_config *config_out)
1324 {
1325    const struct radv_physical_device *pdevice = device->physical_device;
1326    bool scratch_enabled = config_in->scratch_bytes_per_wave > 0;
1327    bool trap_enabled = !!device->trap_handler_shader;
1328    unsigned vgpr_comp_cnt = 0;
1329    unsigned num_input_vgprs = info->num_input_vgprs;
1330 
1331    if (stage == MESA_SHADER_FRAGMENT) {
1332       num_input_vgprs = ac_get_fs_input_vgpr_cnt(config_in, NULL, NULL);
1333    }
1334 
1335    unsigned num_vgprs = MAX2(config_in->num_vgprs, num_input_vgprs);
1336    /* +3 for scratch wave offset and VCC */
1337    unsigned num_sgprs = MAX2(config_in->num_sgprs, info->num_input_sgprs + 3);
1338    unsigned num_shared_vgprs = config_in->num_shared_vgprs;
1339    /* shared VGPRs are introduced in Navi and are allocated in blocks of 8 (RDNA ref 3.6.5) */
1340    assert((pdevice->rad_info.chip_class >= GFX10 && num_shared_vgprs % 8 == 0) ||
1341           (pdevice->rad_info.chip_class < GFX10 && num_shared_vgprs == 0));
1342    unsigned num_shared_vgpr_blocks = num_shared_vgprs / 8;
1343    unsigned excp_en = 0;
1344 
1345    *config_out = *config_in;
1346    config_out->num_vgprs = num_vgprs;
1347    config_out->num_sgprs = num_sgprs;
1348    config_out->num_shared_vgprs = num_shared_vgprs;
1349 
1350    config_out->rsrc2 = S_00B12C_USER_SGPR(info->num_user_sgprs) |
1351                        S_00B12C_SCRATCH_EN(scratch_enabled) | S_00B12C_TRAP_PRESENT(trap_enabled);
1352 
1353    if (trap_enabled) {
1354       /* Configure the shader exceptions like memory violation, etc.
1355        * TODO: Enable (and validate) more exceptions.
1356        */
1357       excp_en = 1 << 8; /* mem_viol */
1358    }
1359 
1360    if (!pdevice->use_ngg_streamout) {
1361       config_out->rsrc2 |=
1362          S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) | S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
1363          S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) | S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
1364          S_00B12C_SO_EN(!!info->so.num_outputs);
1365    }
1366 
1367    config_out->rsrc1 = S_00B848_VGPRS((num_vgprs - 1) / (info->wave_size == 32 ? 8 : 4)) |
1368                        S_00B848_DX10_CLAMP(1) | S_00B848_FLOAT_MODE(config_out->float_mode);
1369 
1370    if (pdevice->rad_info.chip_class >= GFX10) {
1371       config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(info->num_user_sgprs >> 5);
1372    } else {
1373       config_out->rsrc1 |= S_00B228_SGPRS((num_sgprs - 1) / 8);
1374       config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(info->num_user_sgprs >> 5);
1375    }
1376 
1377    bool wgp_mode = radv_should_use_wgp_mode(device, stage, info);
1378 
1379    switch (stage) {
1380    case MESA_SHADER_TESS_EVAL:
1381       if (info->is_ngg) {
1382          config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1383          config_out->rsrc2 |= S_00B22C_OC_LDS_EN(1) | S_00B22C_EXCP_EN(excp_en);
1384       } else if (info->tes.as_es) {
1385          assert(pdevice->rad_info.chip_class <= GFX8);
1386          vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
1387 
1388          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1389       } else {
1390          bool enable_prim_id = info->tes.outinfo.export_prim_id || info->uses_prim_id;
1391          vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1392 
1393          config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1394          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1395       }
1396       config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1397       break;
1398    case MESA_SHADER_TESS_CTRL:
1399       if (pdevice->rad_info.chip_class >= GFX9) {
1400          /* We need at least 2 components for LS.
1401           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
1402           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1403           */
1404          if (pdevice->rad_info.chip_class >= GFX10) {
1405             vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 1;
1406             config_out->rsrc2 |=
1407                S_00B42C_LDS_SIZE_GFX10(info->tcs.num_lds_blocks) | S_00B42C_EXCP_EN_GFX6(excp_en);
1408          } else {
1409             vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
1410             config_out->rsrc2 |=
1411                S_00B42C_LDS_SIZE_GFX9(info->tcs.num_lds_blocks) | S_00B42C_EXCP_EN_GFX9(excp_en);
1412          }
1413       } else {
1414          config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
1415       }
1416       config_out->rsrc1 |=
1417          S_00B428_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) | S_00B428_WGP_MODE(wgp_mode);
1418       config_out->rsrc2 |= S_00B42C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1419       break;
1420    case MESA_SHADER_VERTEX:
1421       if (info->is_ngg) {
1422          config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1423       } else if (info->vs.as_ls) {
1424          assert(pdevice->rad_info.chip_class <= GFX8);
1425          /* We need at least 2 components for LS.
1426           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
1427           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1428           */
1429          vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
1430       } else if (info->vs.as_es) {
1431          assert(pdevice->rad_info.chip_class <= GFX8);
1432          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
1433          vgpr_comp_cnt = info->vs.needs_instance_id ? 1 : 0;
1434       } else {
1435          /* VGPR0-3: (VertexID, InstanceID / StepRate0, PrimID, InstanceID)
1436           * If PrimID is disabled. InstanceID / StepRate1 is loaded instead.
1437           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
1438           */
1439          if (info->vs.needs_instance_id && pdevice->rad_info.chip_class >= GFX10) {
1440             vgpr_comp_cnt = 3;
1441          } else if (info->vs.outinfo.export_prim_id) {
1442             vgpr_comp_cnt = 2;
1443          } else if (info->vs.needs_instance_id) {
1444             vgpr_comp_cnt = 1;
1445          } else {
1446             vgpr_comp_cnt = 0;
1447          }
1448 
1449          config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1450       }
1451       config_out->rsrc2 |=
1452          S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B12C_EXCP_EN(excp_en);
1453       break;
1454    case MESA_SHADER_FRAGMENT:
1455       config_out->rsrc1 |= S_00B028_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1456       config_out->rsrc2 |= S_00B02C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) |
1457                            S_00B02C_EXCP_EN(excp_en);
1458       break;
1459    case MESA_SHADER_GEOMETRY:
1460       config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
1461       config_out->rsrc2 |=
1462          S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B22C_EXCP_EN(excp_en);
1463       break;
1464    case MESA_SHADER_COMPUTE:
1465       config_out->rsrc1 |=
1466          S_00B848_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) | S_00B848_WGP_MODE(wgp_mode);
1467       config_out->rsrc2 |= S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) |
1468                            S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
1469                            S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
1470                            S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2]   ? 2
1471                                                    : info->cs.uses_thread_id[1] ? 1
1472                                                                                 : 0) |
1473                            S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) |
1474                            S_00B84C_LDS_SIZE(config_in->lds_size) | S_00B84C_EXCP_EN(excp_en);
1475       config_out->rsrc3 |= S_00B8A0_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
1476 
1477       break;
1478    default:
1479       unreachable("unsupported shader type");
1480       break;
1481    }
1482 
1483    if (pdevice->rad_info.chip_class >= GFX10 && info->is_ngg &&
1484        (stage == MESA_SHADER_VERTEX || stage == MESA_SHADER_TESS_EVAL ||
1485         stage == MESA_SHADER_GEOMETRY)) {
1486       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
1487       gl_shader_stage es_stage = stage;
1488       if (stage == MESA_SHADER_GEOMETRY)
1489          es_stage = info->gs.es_type;
1490 
1491       /* VGPR5-8: (VertexID, UserVGPR0, UserVGPR1, UserVGPR2 / InstanceID) */
1492       if (es_stage == MESA_SHADER_VERTEX) {
1493          es_vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 0;
1494       } else if (es_stage == MESA_SHADER_TESS_EVAL) {
1495          bool enable_prim_id = info->tes.outinfo.export_prim_id || info->uses_prim_id;
1496          es_vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1497       } else
1498          unreachable("Unexpected ES shader stage");
1499 
1500       bool nggc = info->has_ngg_culling; /* Culling uses GS vertex offsets 0, 1, 2. */
1501       bool tes_triangles =
1502          stage == MESA_SHADER_TESS_EVAL && info->tes.primitive_mode >= 4; /* GL_TRIANGLES */
1503       if (info->uses_invocation_id) {
1504          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
1505       } else if (info->uses_prim_id || (es_stage == MESA_SHADER_VERTEX &&
1506                                         info->vs.outinfo.export_prim_id)) {
1507          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1508       } else if (info->gs.vertices_in >= 3 || tes_triangles || nggc) {
1509          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1510       } else {
1511          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1512       }
1513 
1514       /* Disable the WGP mode on gfx10.3 because it can hang. (it
1515        * happened on VanGogh) Let's disable it on all chips that
1516        * disable exactly 1 CU per SA for GS.
1517        */
1518       config_out->rsrc1 |=
1519          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
1520       config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1521                            S_00B22C_LDS_SIZE(config_in->lds_size) |
1522                            S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
1523    } else if (pdevice->rad_info.chip_class >= GFX9 && stage == MESA_SHADER_GEOMETRY) {
1524       unsigned es_type = info->gs.es_type;
1525       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
1526 
1527       if (es_type == MESA_SHADER_VERTEX) {
1528          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
1529          if (info->vs.needs_instance_id) {
1530             es_vgpr_comp_cnt = pdevice->rad_info.chip_class >= GFX10 ? 3 : 1;
1531          } else {
1532             es_vgpr_comp_cnt = 0;
1533          }
1534       } else if (es_type == MESA_SHADER_TESS_EVAL) {
1535          es_vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
1536       } else {
1537          unreachable("invalid shader ES type");
1538       }
1539 
1540       /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
1541        * VGPR[0:4] are always loaded.
1542        */
1543       if (info->uses_invocation_id) {
1544          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
1545       } else if (info->uses_prim_id) {
1546          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1547       } else if (info->gs.vertices_in >= 3) {
1548          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1549       } else {
1550          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1551       }
1552 
1553       config_out->rsrc1 |=
1554          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
1555       config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1556                            S_00B22C_OC_LDS_EN(es_type == MESA_SHADER_TESS_EVAL);
1557    } else if (pdevice->rad_info.chip_class >= GFX9 && stage == MESA_SHADER_TESS_CTRL) {
1558       config_out->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
1559    } else {
1560       config_out->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
1561    }
1562 }
1563 
1564 struct radv_shader_variant *
radv_shader_variant_create(struct radv_device * device,const struct radv_shader_binary * binary,bool keep_shader_info,bool from_cache)1565 radv_shader_variant_create(struct radv_device *device, const struct radv_shader_binary *binary,
1566                            bool keep_shader_info, bool from_cache)
1567 {
1568    struct ac_shader_config config = {0};
1569    struct ac_rtld_binary rtld_binary = {0};
1570    struct radv_shader_variant *variant = calloc(1, sizeof(struct radv_shader_variant));
1571    if (!variant)
1572       return NULL;
1573 
1574    variant->ref_count = 1;
1575 
1576    if (binary->type == RADV_BINARY_TYPE_RTLD) {
1577       struct ac_rtld_symbol lds_symbols[2];
1578       unsigned num_lds_symbols = 0;
1579       const char *elf_data = (const char *)((struct radv_shader_binary_rtld *)binary)->data;
1580       size_t elf_size = ((struct radv_shader_binary_rtld *)binary)->elf_size;
1581 
1582       if (device->physical_device->rad_info.chip_class >= GFX9 &&
1583           (binary->stage == MESA_SHADER_GEOMETRY || binary->info.is_ngg) &&
1584           !binary->is_gs_copy_shader) {
1585          struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1586          sym->name = "esgs_ring";
1587          sym->size = binary->info.ngg_info.esgs_ring_size;
1588          sym->align = 64 * 1024;
1589       }
1590 
1591       if (binary->info.is_ngg && binary->stage == MESA_SHADER_GEOMETRY) {
1592          struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1593          sym->name = "ngg_emit";
1594          sym->size = binary->info.ngg_info.ngg_emit_size * 4;
1595          sym->align = 4;
1596       }
1597 
1598       struct ac_rtld_open_info open_info = {
1599          .info = &device->physical_device->rad_info,
1600          .shader_type = binary->stage,
1601          .wave_size = binary->info.wave_size,
1602          .num_parts = 1,
1603          .elf_ptrs = &elf_data,
1604          .elf_sizes = &elf_size,
1605          .num_shared_lds_symbols = num_lds_symbols,
1606          .shared_lds_symbols = lds_symbols,
1607       };
1608 
1609       if (!ac_rtld_open(&rtld_binary, open_info)) {
1610          free(variant);
1611          return NULL;
1612       }
1613 
1614       if (!ac_rtld_read_config(&device->physical_device->rad_info, &rtld_binary, &config)) {
1615          ac_rtld_close(&rtld_binary);
1616          free(variant);
1617          return NULL;
1618       }
1619 
1620       if (rtld_binary.lds_size > 0) {
1621          unsigned encode_granularity = device->physical_device->rad_info.lds_encode_granularity;
1622          config.lds_size = align(rtld_binary.lds_size, encode_granularity) / encode_granularity;
1623       }
1624       if (!config.lds_size && binary->stage == MESA_SHADER_TESS_CTRL) {
1625          /* This is used for reporting LDS statistics */
1626          config.lds_size = binary->info.tcs.num_lds_blocks;
1627       }
1628 
1629       variant->code_size = rtld_binary.rx_size;
1630       variant->exec_size = rtld_binary.exec_size;
1631    } else {
1632       assert(binary->type == RADV_BINARY_TYPE_LEGACY);
1633       config = ((struct radv_shader_binary_legacy *)binary)->base.config;
1634       variant->code_size =
1635          radv_get_shader_binary_size(((struct radv_shader_binary_legacy *)binary)->code_size);
1636       variant->exec_size = ((struct radv_shader_binary_legacy *)binary)->exec_size;
1637    }
1638 
1639    variant->info = binary->info;
1640 
1641    if (from_cache) {
1642       /* Copy the shader binary configuration from the cache. */
1643       memcpy(&variant->config, &binary->config, sizeof(variant->config));
1644    } else {
1645       radv_postprocess_config(device, &config, &binary->info, binary->stage, &variant->config);
1646    }
1647 
1648    void *dest_ptr = radv_alloc_shader_memory(device, variant);
1649    if (!dest_ptr) {
1650       if (binary->type == RADV_BINARY_TYPE_RTLD)
1651          ac_rtld_close(&rtld_binary);
1652       free(variant);
1653       return NULL;
1654    }
1655 
1656    if (binary->type == RADV_BINARY_TYPE_RTLD) {
1657       struct radv_shader_binary_rtld *bin = (struct radv_shader_binary_rtld *)binary;
1658       struct ac_rtld_upload_info info = {
1659          .binary = &rtld_binary,
1660          .rx_va = radv_shader_variant_get_va(variant),
1661          .rx_ptr = dest_ptr,
1662       };
1663 
1664       if (!ac_rtld_upload(&info)) {
1665          radv_shader_variant_destroy(device, variant);
1666          ac_rtld_close(&rtld_binary);
1667          return NULL;
1668       }
1669 
1670       if (keep_shader_info || (device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS)) {
1671          const char *disasm_data;
1672          size_t disasm_size;
1673          if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm_data,
1674                                           &disasm_size)) {
1675             radv_shader_variant_destroy(device, variant);
1676             ac_rtld_close(&rtld_binary);
1677             return NULL;
1678          }
1679 
1680          variant->ir_string =
1681             bin->llvm_ir_size ? strdup((const char *)(bin->data + bin->elf_size)) : NULL;
1682          variant->disasm_string = malloc(disasm_size + 1);
1683          memcpy(variant->disasm_string, disasm_data, disasm_size);
1684          variant->disasm_string[disasm_size] = 0;
1685       }
1686 
1687       variant->code_ptr = dest_ptr;
1688       ac_rtld_close(&rtld_binary);
1689    } else {
1690       struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
1691       memcpy(dest_ptr, bin->data + bin->stats_size, bin->code_size);
1692 
1693       /* Add end-of-code markers for the UMR disassembler. */
1694       uint32_t *ptr32 = (uint32_t *)dest_ptr + bin->code_size / 4;
1695       for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
1696          ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
1697 
1698       variant->code_ptr = dest_ptr;
1699       variant->ir_string =
1700          bin->ir_size ? strdup((const char *)(bin->data + bin->stats_size + bin->code_size)) : NULL;
1701       variant->disasm_string =
1702          bin->disasm_size
1703             ? strdup((const char *)(bin->data + bin->stats_size + bin->code_size + bin->ir_size))
1704             : NULL;
1705 
1706       if (bin->stats_size) {
1707          variant->statistics = calloc(bin->stats_size, 1);
1708          memcpy(variant->statistics, bin->data, bin->stats_size);
1709       }
1710    }
1711    return variant;
1712 }
1713 
1714 static char *
radv_dump_nir_shaders(struct nir_shader * const * shaders,int shader_count)1715 radv_dump_nir_shaders(struct nir_shader *const *shaders, int shader_count)
1716 {
1717    char *data = NULL;
1718    char *ret = NULL;
1719    size_t size = 0;
1720    struct u_memstream mem;
1721    if (u_memstream_open(&mem, &data, &size)) {
1722       FILE *const memf = u_memstream_get(&mem);
1723       for (int i = 0; i < shader_count; ++i)
1724          nir_print_shader(shaders[i], memf);
1725       u_memstream_close(&mem);
1726    }
1727 
1728    ret = malloc(size + 1);
1729    if (ret) {
1730       memcpy(ret, data, size);
1731       ret[size] = 0;
1732    }
1733    free(data);
1734    return ret;
1735 }
1736 
1737 static struct radv_shader_variant *
shader_variant_compile(struct radv_device * device,struct vk_shader_module * module,struct nir_shader * const * shaders,int shader_count,gl_shader_stage stage,struct radv_shader_info * info,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)1738 shader_variant_compile(struct radv_device *device, struct vk_shader_module *module,
1739                        struct nir_shader *const *shaders, int shader_count, gl_shader_stage stage,
1740                        struct radv_shader_info *info, struct radv_nir_compiler_options *options,
1741                        bool gs_copy_shader, bool trap_handler_shader, bool keep_shader_info,
1742                        bool keep_statistic_info, struct radv_shader_binary **binary_out)
1743 {
1744    enum radeon_family chip_family = device->physical_device->rad_info.family;
1745    struct radv_shader_binary *binary = NULL;
1746 
1747    struct radv_shader_debug_data debug_data = {
1748       .device = device,
1749       .module = module,
1750    };
1751 
1752    options->family = chip_family;
1753    options->chip_class = device->physical_device->rad_info.chip_class;
1754    options->info = &device->physical_device->rad_info;
1755    options->dump_shader = radv_can_dump_shader(device, module, gs_copy_shader || trap_handler_shader);
1756    options->dump_preoptir =
1757       options->dump_shader && device->instance->debug_flags & RADV_DEBUG_PREOPTIR;
1758    options->record_ir = keep_shader_info;
1759    options->record_stats = keep_statistic_info;
1760    options->check_ir = device->instance->debug_flags & RADV_DEBUG_CHECKIR;
1761    options->address32_hi = device->physical_device->rad_info.address32_hi;
1762    options->has_ls_vgpr_init_bug = device->physical_device->rad_info.has_ls_vgpr_init_bug;
1763    options->enable_mrt_output_nan_fixup =
1764       module && !module->nir && options->key.ps.enable_mrt_output_nan_fixup;
1765    options->adjust_frag_coord_z = device->adjust_frag_coord_z;
1766    options->has_image_load_dcc_bug = device->physical_device->rad_info.has_image_load_dcc_bug;
1767    options->debug.func = radv_compiler_debug;
1768    options->debug.private_data = &debug_data;
1769 
1770    switch (options->key.ps.force_vrs) {
1771    case RADV_FORCE_VRS_2x2:
1772       options->force_vrs_rates = (1u << 2) | (1u << 4);
1773       break;
1774    case RADV_FORCE_VRS_2x1:
1775       options->force_vrs_rates = (1u << 2) | (0u << 4);
1776       break;
1777    case RADV_FORCE_VRS_1x2:
1778       options->force_vrs_rates = (0u << 2) | (1u << 4);
1779       break;
1780    default:
1781       break;
1782    }
1783 
1784    struct radv_shader_args args = {0};
1785    args.options = options;
1786    args.shader_info = info;
1787    args.is_gs_copy_shader = gs_copy_shader;
1788    args.is_trap_handler_shader = trap_handler_shader;
1789 
1790    radv_declare_shader_args(
1791       &args, gs_copy_shader ? MESA_SHADER_VERTEX : shaders[shader_count - 1]->info.stage,
1792       shader_count >= 2,
1793       shader_count >= 2 ? shaders[shader_count - 2]->info.stage : MESA_SHADER_VERTEX);
1794 
1795 #ifdef LLVM_AVAILABLE
1796    if (radv_use_llvm_for_stage(device, stage) || options->dump_shader || options->record_ir)
1797       ac_init_llvm_once();
1798 
1799    if (radv_use_llvm_for_stage(device, stage)) {
1800       llvm_compile_shader(device, shader_count, shaders, &binary, &args);
1801 #else
1802    if (false) {
1803 #endif
1804    } else {
1805       aco_compile_shader(shader_count, shaders, &binary, &args);
1806    }
1807 
1808    binary->info = *info;
1809 
1810    struct radv_shader_variant *variant =
1811       radv_shader_variant_create(device, binary, keep_shader_info, false);
1812    if (!variant) {
1813       free(binary);
1814       return NULL;
1815    }
1816 
1817    if (options->dump_shader) {
1818       fprintf(stderr, "%s", radv_get_shader_name(info, shaders[0]->info.stage));
1819       for (int i = 1; i < shader_count; ++i)
1820          fprintf(stderr, " + %s", radv_get_shader_name(info, shaders[i]->info.stage));
1821 
1822       fprintf(stderr, "\ndisasm:\n%s\n", variant->disasm_string);
1823    }
1824 
1825    if (keep_shader_info) {
1826       variant->nir_string = radv_dump_nir_shaders(shaders, shader_count);
1827       if (!gs_copy_shader && !trap_handler_shader && !module->nir) {
1828          variant->spirv = malloc(module->size);
1829          if (!variant->spirv) {
1830             free(variant);
1831             free(binary);
1832             return NULL;
1833          }
1834 
1835          memcpy(variant->spirv, module->data, module->size);
1836          variant->spirv_size = module->size;
1837       }
1838    }
1839 
1840    /* Copy the shader binary configuration to store it in the cache. */
1841    memcpy(&binary->config, &variant->config, sizeof(binary->config));
1842 
1843    if (binary_out)
1844       *binary_out = binary;
1845    else
1846       free(binary);
1847 
1848    return variant;
1849 }
1850 
1851 struct radv_shader_variant *
1852 radv_shader_variant_compile(struct radv_device *device, struct vk_shader_module *module,
1853                             struct nir_shader *const *shaders, int shader_count,
1854                             struct radv_pipeline_layout *layout,
1855                             const struct radv_pipeline_key *key,
1856                             struct radv_shader_info *info, bool keep_shader_info,
1857                             bool keep_statistic_info,
1858                             struct radv_shader_binary **binary_out)
1859 {
1860    gl_shader_stage stage = shaders[shader_count - 1]->info.stage;
1861    struct radv_nir_compiler_options options = {0};
1862 
1863    options.layout = layout;
1864    if (key)
1865       options.key = *key;
1866 
1867    options.explicit_scratch_args = !radv_use_llvm_for_stage(device, stage);
1868    options.remap_spi_ps_input = !radv_use_llvm_for_stage(device, stage);
1869    options.robust_buffer_access = device->robust_buffer_access;
1870    options.wgp_mode = radv_should_use_wgp_mode(device, stage, info);
1871 
1872    return shader_variant_compile(device, module, shaders, shader_count, stage, info, &options,
1873                                  false, false, keep_shader_info, keep_statistic_info, binary_out);
1874 }
1875 
1876 struct radv_shader_variant *
1877 radv_create_gs_copy_shader(struct radv_device *device, struct nir_shader *shader,
1878                            struct radv_shader_info *info, struct radv_shader_binary **binary_out,
1879                            bool keep_shader_info, bool keep_statistic_info, bool multiview,
1880                            bool disable_optimizations)
1881 {
1882    struct radv_nir_compiler_options options = {0};
1883    gl_shader_stage stage = MESA_SHADER_VERTEX;
1884 
1885    options.explicit_scratch_args = !radv_use_llvm_for_stage(device, stage);
1886    options.remap_spi_ps_input = !radv_use_llvm_for_stage(device, stage);
1887    options.key.has_multiview_view_index = multiview;
1888    options.key.optimisations_disabled = disable_optimizations;
1889 
1890    return shader_variant_compile(device, NULL, &shader, 1, stage, info, &options, true, false,
1891                                  keep_shader_info, keep_statistic_info, binary_out);
1892 }
1893 
1894 struct radv_shader_variant *
1895 radv_create_trap_handler_shader(struct radv_device *device)
1896 {
1897    struct radv_nir_compiler_options options = {0};
1898    struct radv_shader_variant *shader = NULL;
1899    struct radv_shader_binary *binary = NULL;
1900    struct radv_shader_info info = {0};
1901 
1902    nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, NULL, "meta_trap_handler");
1903 
1904    options.explicit_scratch_args = true;
1905    options.wgp_mode = radv_should_use_wgp_mode(device, MESA_SHADER_COMPUTE, &info);
1906    info.wave_size = 64;
1907 
1908    shader = shader_variant_compile(device, NULL, &b.shader, 1, MESA_SHADER_COMPUTE, &info, &options,
1909                                    false, true, true, false, &binary);
1910 
1911    ralloc_free(b.shader);
1912    free(binary);
1913 
1914    return shader;
1915 }
1916 
1917 static struct radv_shader_prolog *
1918 upload_vs_prolog(struct radv_device *device, struct radv_prolog_binary *bin, unsigned wave_size)
1919 {
1920    struct radv_shader_prolog *prolog = malloc(sizeof(struct radv_shader_prolog));
1921    if (!prolog)
1922       return NULL;
1923 
1924    prolog->alloc = alloc_shader_memory(device, bin->code_size, NULL);
1925    if (!prolog->alloc) {
1926       free(prolog);
1927       return NULL;
1928    }
1929 
1930    prolog->bo = prolog->alloc->arena->bo;
1931    char *dest_ptr = prolog->alloc->arena->ptr + prolog->alloc->offset;
1932 
1933    memcpy(dest_ptr, bin->data, bin->code_size);
1934 
1935    prolog->rsrc1 = S_00B848_VGPRS((bin->num_vgprs - 1) / (wave_size == 32 ? 8 : 4)) |
1936                    S_00B228_SGPRS((bin->num_sgprs - 1) / 8);
1937    prolog->num_preserved_sgprs = bin->num_preserved_sgprs;
1938 
1939    return prolog;
1940 }
1941 
1942 struct radv_shader_prolog *
1943 radv_create_vs_prolog(struct radv_device *device, const struct radv_vs_prolog_key *key)
1944 {
1945    struct radv_nir_compiler_options options = {0};
1946    options.explicit_scratch_args = true;
1947    options.family = device->physical_device->rad_info.family;
1948    options.chip_class = device->physical_device->rad_info.chip_class;
1949    options.info = &device->physical_device->rad_info;
1950    options.address32_hi = device->physical_device->rad_info.address32_hi;
1951    options.dump_shader = device->instance->debug_flags & RADV_DEBUG_DUMP_PROLOGS;
1952 
1953    struct radv_shader_info info = {0};
1954    info.wave_size = key->wave32 ? 32 : 64;
1955    info.vs.needs_instance_id = true;
1956    info.vs.needs_base_instance = true;
1957    info.vs.needs_draw_id = true;
1958    info.vs.use_per_attribute_vb_descs = true;
1959    info.vs.vb_desc_usage_mask = BITFIELD_MASK(key->num_attributes);
1960    info.vs.has_prolog = true;
1961    info.vs.as_ls = key->as_ls;
1962    info.is_ngg = key->is_ngg;
1963 
1964    struct radv_shader_args args = {0};
1965    args.options = &options;
1966    args.shader_info = &info;
1967    radv_declare_shader_args(&args, key->next_stage, key->next_stage != MESA_SHADER_VERTEX,
1968                             MESA_SHADER_VERTEX);
1969 
1970 #ifdef LLVM_AVAILABLE
1971    if (options.dump_shader)
1972       ac_init_llvm_once();
1973 #endif
1974 
1975    struct radv_prolog_binary *binary = NULL;
1976    aco_compile_vs_prolog(key, &binary, &args);
1977    struct radv_shader_prolog *prolog = upload_vs_prolog(device, binary, info.wave_size);
1978    if (prolog) {
1979       prolog->nontrivial_divisors = key->state->nontrivial_divisors;
1980    }
1981    free(binary);
1982 
1983    return prolog;
1984 }
1985 
1986 void
1987 radv_shader_variant_destroy(struct radv_device *device, struct radv_shader_variant *variant)
1988 {
1989    if (!p_atomic_dec_zero(&variant->ref_count))
1990       return;
1991 
1992    free_shader_memory(device, variant->alloc);
1993 
1994    free(variant->spirv);
1995    free(variant->nir_string);
1996    free(variant->disasm_string);
1997    free(variant->ir_string);
1998    free(variant->statistics);
1999    free(variant);
2000 }
2001 
2002 void
2003 radv_prolog_destroy(struct radv_device *device, struct radv_shader_prolog *prolog)
2004 {
2005    if (!prolog)
2006       return;
2007 
2008    free_shader_memory(device, prolog->alloc);
2009    free(prolog);
2010 }
2011 
2012 uint64_t
2013 radv_shader_variant_get_va(const struct radv_shader_variant *variant)
2014 {
2015    return radv_buffer_get_va(variant->bo) + variant->alloc->offset;
2016 }
2017 
2018 struct radv_shader_variant *
2019 radv_find_shader_variant(struct radv_device *device, uint64_t pc)
2020 {
2021    mtx_lock(&device->shader_arena_mutex);
2022    list_for_each_entry(struct radv_shader_arena, arena, &device->shader_arenas, list)
2023    {
2024 #ifdef __GNUC__
2025 #pragma GCC diagnostic push
2026 #pragma GCC diagnostic ignored "-Wshadow"
2027 #endif
2028       list_for_each_entry(union radv_shader_arena_block, block, &arena->entries, list)
2029       {
2030 #ifdef __GNUC__
2031 #pragma GCC diagnostic pop
2032 #endif
2033          uint64_t start = radv_buffer_get_va(block->arena->bo) + block->offset;
2034          if (!block->freelist.prev && pc >= start && pc < start + block->size) {
2035             mtx_unlock(&device->shader_arena_mutex);
2036             return (struct radv_shader_variant *)block->freelist.next;
2037          }
2038       }
2039    }
2040 
2041    mtx_unlock(&device->shader_arena_mutex);
2042    return NULL;
2043 }
2044 
2045 const char *
2046 radv_get_shader_name(struct radv_shader_info *info, gl_shader_stage stage)
2047 {
2048    switch (stage) {
2049    case MESA_SHADER_VERTEX:
2050       if (info->vs.as_ls)
2051          return "Vertex Shader as LS";
2052       else if (info->vs.as_es)
2053          return "Vertex Shader as ES";
2054       else if (info->is_ngg)
2055          return "Vertex Shader as ESGS";
2056       else
2057          return "Vertex Shader as VS";
2058    case MESA_SHADER_TESS_CTRL:
2059       return "Tessellation Control Shader";
2060    case MESA_SHADER_TESS_EVAL:
2061       if (info->tes.as_es)
2062          return "Tessellation Evaluation Shader as ES";
2063       else if (info->is_ngg)
2064          return "Tessellation Evaluation Shader as ESGS";
2065       else
2066          return "Tessellation Evaluation Shader as VS";
2067    case MESA_SHADER_GEOMETRY:
2068       return "Geometry Shader";
2069    case MESA_SHADER_FRAGMENT:
2070       return "Pixel Shader";
2071    case MESA_SHADER_COMPUTE:
2072       return "Compute Shader";
2073    default:
2074       return "Unknown shader";
2075    };
2076 }
2077 
2078 unsigned
2079 radv_get_max_waves(const struct radv_device *device, struct radv_shader_variant *variant,
2080                    gl_shader_stage stage)
2081 {
2082    struct radeon_info *info = &device->physical_device->rad_info;
2083    enum chip_class chip_class = info->chip_class;
2084    uint8_t wave_size = variant->info.wave_size;
2085    struct ac_shader_config *conf = &variant->config;
2086    unsigned max_simd_waves;
2087    unsigned lds_per_wave = 0;
2088 
2089    max_simd_waves = info->max_wave64_per_simd * (64 / wave_size);
2090 
2091    if (stage == MESA_SHADER_FRAGMENT) {
2092       lds_per_wave =
2093          conf->lds_size * info->lds_encode_granularity + variant->info.ps.num_interp * 48;
2094       lds_per_wave = align(lds_per_wave, info->lds_alloc_granularity);
2095    } else if (stage == MESA_SHADER_COMPUTE) {
2096       unsigned max_workgroup_size = variant->info.workgroup_size;
2097       lds_per_wave =
2098          align(conf->lds_size * info->lds_encode_granularity, info->lds_alloc_granularity);
2099       lds_per_wave /= DIV_ROUND_UP(max_workgroup_size, wave_size);
2100    }
2101 
2102    if (conf->num_sgprs && chip_class < GFX10) {
2103       unsigned sgprs = align(conf->num_sgprs, chip_class >= GFX8 ? 16 : 8);
2104       max_simd_waves = MIN2(max_simd_waves, info->num_physical_sgprs_per_simd / sgprs);
2105    }
2106 
2107    if (conf->num_vgprs) {
2108       unsigned physical_vgprs = info->num_physical_wave64_vgprs_per_simd * (64 / wave_size);
2109       unsigned vgprs = align(conf->num_vgprs, wave_size == 32 ? 8 : 4);
2110       if (chip_class >= GFX10_3)
2111          vgprs = align(vgprs, wave_size == 32 ? 16 : 8);
2112       max_simd_waves = MIN2(max_simd_waves, physical_vgprs / vgprs);
2113    }
2114 
2115    unsigned simd_per_workgroup = info->num_simd_per_compute_unit;
2116    if (chip_class >= GFX10)
2117       simd_per_workgroup *= 2; /* like lds_size_per_workgroup, assume WGP on GFX10+ */
2118 
2119    unsigned max_lds_per_simd = info->lds_size_per_workgroup / simd_per_workgroup;
2120    if (lds_per_wave)
2121       max_simd_waves = MIN2(max_simd_waves, DIV_ROUND_UP(max_lds_per_simd, lds_per_wave));
2122 
2123    return chip_class >= GFX10 ? max_simd_waves * (wave_size / 32) : max_simd_waves;
2124 }
2125 
2126 unsigned
2127 radv_compute_spi_ps_input(const struct radv_device *device,
2128                           const struct radv_shader_info *info)
2129 {
2130    unsigned spi_ps_input;
2131 
2132    spi_ps_input = S_0286CC_PERSP_CENTER_ENA(info->ps.reads_persp_center) |
2133                   S_0286CC_PERSP_CENTROID_ENA(info->ps.reads_persp_centroid) |
2134                   S_0286CC_PERSP_SAMPLE_ENA(info->ps.reads_persp_sample) |
2135                   S_0286CC_LINEAR_CENTER_ENA(info->ps.reads_linear_center) |
2136                   S_0286CC_LINEAR_CENTROID_ENA(info->ps.reads_linear_centroid) |
2137                   S_0286CC_LINEAR_SAMPLE_ENA(info->ps.reads_linear_sample)|
2138                   S_0286CC_PERSP_PULL_MODEL_ENA(info->ps.reads_barycentric_model) |
2139                   S_0286CC_FRONT_FACE_ENA(info->ps.reads_front_face);
2140 
2141    if (info->ps.reads_frag_coord_mask ||
2142        info->ps.reads_sample_pos_mask) {
2143       uint8_t mask = info->ps.reads_frag_coord_mask | info->ps.reads_sample_pos_mask;
2144 
2145       for (unsigned i = 0; i < 4; i++) {
2146          if (mask & (1 << i))
2147             spi_ps_input |= S_0286CC_POS_X_FLOAT_ENA(1) << i;
2148       }
2149 
2150       if (device->adjust_frag_coord_z && info->ps.reads_frag_coord_mask & (1 << 2)) {
2151          spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
2152       }
2153    }
2154 
2155    if (info->ps.reads_sample_id || info->ps.reads_frag_shading_rate || info->ps.reads_sample_mask_in) {
2156       spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
2157    }
2158 
2159    if (info->ps.reads_sample_mask_in) {
2160       spi_ps_input |= S_0286CC_SAMPLE_COVERAGE_ENA(1);
2161    }
2162 
2163    if (G_0286CC_POS_W_FLOAT_ENA(spi_ps_input)) {
2164       /* If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be enabled too */
2165       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
2166    }
2167 
2168    if (!(spi_ps_input & 0x7F)) {
2169       /* At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled */
2170       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
2171    }
2172 
2173    return spi_ps_input;
2174 }
2175 
2176 VkResult
2177 radv_GetShaderInfoAMD(VkDevice _device, VkPipeline _pipeline, VkShaderStageFlagBits shaderStage,
2178                       VkShaderInfoTypeAMD infoType, size_t *pInfoSize, void *pInfo)
2179 {
2180    RADV_FROM_HANDLE(radv_device, device, _device);
2181    RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);
2182    gl_shader_stage stage = vk_to_mesa_shader_stage(shaderStage);
2183    struct radv_shader_variant *variant = pipeline->shaders[stage];
2184    VkResult result = VK_SUCCESS;
2185 
2186    /* Spec doesn't indicate what to do if the stage is invalid, so just
2187     * return no info for this. */
2188    if (!variant)
2189       return vk_error(device, VK_ERROR_FEATURE_NOT_PRESENT);
2190 
2191    switch (infoType) {
2192    case VK_SHADER_INFO_TYPE_STATISTICS_AMD:
2193       if (!pInfo) {
2194          *pInfoSize = sizeof(VkShaderStatisticsInfoAMD);
2195       } else {
2196          unsigned lds_multiplier = device->physical_device->rad_info.lds_encode_granularity;
2197          struct ac_shader_config *conf = &variant->config;
2198 
2199          VkShaderStatisticsInfoAMD statistics = {0};
2200          statistics.shaderStageMask = shaderStage;
2201          statistics.numPhysicalVgprs =
2202             device->physical_device->rad_info.num_physical_wave64_vgprs_per_simd;
2203          statistics.numPhysicalSgprs =
2204             device->physical_device->rad_info.num_physical_sgprs_per_simd;
2205          statistics.numAvailableSgprs = statistics.numPhysicalSgprs;
2206 
2207          if (stage == MESA_SHADER_COMPUTE) {
2208             unsigned *local_size = variant->info.cs.block_size;
2209             unsigned workgroup_size = pipeline->shaders[MESA_SHADER_COMPUTE]->info.workgroup_size;
2210 
2211             statistics.numAvailableVgprs =
2212                statistics.numPhysicalVgprs /
2213                ceil((double)workgroup_size / statistics.numPhysicalVgprs);
2214 
2215             statistics.computeWorkGroupSize[0] = local_size[0];
2216             statistics.computeWorkGroupSize[1] = local_size[1];
2217             statistics.computeWorkGroupSize[2] = local_size[2];
2218          } else {
2219             statistics.numAvailableVgprs = statistics.numPhysicalVgprs;
2220          }
2221 
2222          statistics.resourceUsage.numUsedVgprs = conf->num_vgprs;
2223          statistics.resourceUsage.numUsedSgprs = conf->num_sgprs;
2224          statistics.resourceUsage.ldsSizePerLocalWorkGroup = 32768;
2225          statistics.resourceUsage.ldsUsageSizeInBytes = conf->lds_size * lds_multiplier;
2226          statistics.resourceUsage.scratchMemUsageInBytes = conf->scratch_bytes_per_wave;
2227 
2228          size_t size = *pInfoSize;
2229          *pInfoSize = sizeof(statistics);
2230 
2231          memcpy(pInfo, &statistics, MIN2(size, *pInfoSize));
2232 
2233          if (size < *pInfoSize)
2234             result = VK_INCOMPLETE;
2235       }
2236 
2237       break;
2238    case VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD: {
2239       char *out;
2240       size_t outsize;
2241       struct u_memstream mem;
2242       u_memstream_open(&mem, &out, &outsize);
2243       FILE *const memf = u_memstream_get(&mem);
2244 
2245       fprintf(memf, "%s:\n", radv_get_shader_name(&variant->info, stage));
2246       fprintf(memf, "%s\n\n", variant->ir_string);
2247       if (variant->disasm_string) {
2248          fprintf(memf, "%s\n\n", variant->disasm_string);
2249       }
2250       radv_dump_shader_stats(device, pipeline, stage, memf);
2251       u_memstream_close(&mem);
2252 
2253       /* Need to include the null terminator. */
2254       size_t length = outsize + 1;
2255 
2256       if (!pInfo) {
2257          *pInfoSize = length;
2258       } else {
2259          size_t size = *pInfoSize;
2260          *pInfoSize = length;
2261 
2262          memcpy(pInfo, out, MIN2(size, length));
2263 
2264          if (size < length)
2265             result = VK_INCOMPLETE;
2266       }
2267 
2268       free(out);
2269       break;
2270    }
2271    default:
2272       /* VK_SHADER_INFO_TYPE_BINARY_AMD unimplemented for now. */
2273       result = VK_ERROR_FEATURE_NOT_PRESENT;
2274       break;
2275    }
2276 
2277    return result;
2278 }
2279 
2280 VkResult
2281 radv_dump_shader_stats(struct radv_device *device, struct radv_pipeline *pipeline,
2282                        gl_shader_stage stage, FILE *output)
2283 {
2284    struct radv_shader_variant *shader = pipeline->shaders[stage];
2285    VkPipelineExecutablePropertiesKHR *props = NULL;
2286    uint32_t prop_count = 0;
2287    VkResult result;
2288 
2289    VkPipelineInfoKHR pipeline_info = {0};
2290    pipeline_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR;
2291    pipeline_info.pipeline = radv_pipeline_to_handle(pipeline);
2292 
2293    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info,
2294                                                     &prop_count, NULL);
2295    if (result != VK_SUCCESS)
2296       return result;
2297 
2298    props = calloc(prop_count, sizeof(*props));
2299    if (!props)
2300       return VK_ERROR_OUT_OF_HOST_MEMORY;
2301 
2302    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info,
2303                                                     &prop_count, props);
2304    if (result != VK_SUCCESS)
2305       goto fail;
2306 
2307    for (unsigned exec_idx = 0; exec_idx < prop_count; exec_idx++) {
2308       if (!(props[exec_idx].stages & mesa_to_vk_shader_stage(stage)))
2309          continue;
2310 
2311       VkPipelineExecutableStatisticKHR *stats = NULL;
2312       uint32_t stat_count = 0;
2313 
2314       VkPipelineExecutableInfoKHR exec_info = {0};
2315       exec_info.pipeline = radv_pipeline_to_handle(pipeline);
2316       exec_info.executableIndex = exec_idx;
2317 
2318       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info,
2319                                                        &stat_count, NULL);
2320       if (result != VK_SUCCESS)
2321          goto fail;
2322 
2323       stats = calloc(stat_count, sizeof(*stats));
2324       if (!stats) {
2325          result = VK_ERROR_OUT_OF_HOST_MEMORY;
2326          goto fail;
2327       }
2328 
2329       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info,
2330                                                        &stat_count, stats);
2331       if (result != VK_SUCCESS) {
2332          free(stats);
2333          goto fail;
2334       }
2335 
2336       fprintf(output, "\n%s:\n", radv_get_shader_name(&shader->info, stage));
2337       fprintf(output, "*** SHADER STATS ***\n");
2338 
2339       for (unsigned i = 0; i < stat_count; i++) {
2340          fprintf(output, "%s: ", stats[i].name);
2341          switch (stats[i].format) {
2342          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR:
2343             fprintf(output, "%s", stats[i].value.b32 == VK_TRUE ? "true" : "false");
2344             break;
2345          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR:
2346             fprintf(output, "%" PRIi64, stats[i].value.i64);
2347             break;
2348          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR:
2349             fprintf(output, "%" PRIu64, stats[i].value.u64);
2350             break;
2351          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR:
2352             fprintf(output, "%f", stats[i].value.f64);
2353             break;
2354          default:
2355             unreachable("Invalid pipeline statistic format");
2356          }
2357          fprintf(output, "\n");
2358       }
2359 
2360       fprintf(output, "********************\n\n\n");
2361 
2362       free(stats);
2363    }
2364 
2365 fail:
2366    free(props);
2367    return result;
2368 }
2369