radv: Add debug option to dump meta shaders.
[mesa.git] / src / amd / vulkan / radv_shader.c
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 "util/mesa-sha1.h"
29 #include "util/u_atomic.h"
30 #include "radv_debug.h"
31 #include "radv_private.h"
32 #include "radv_shader.h"
33 #include "radv_shader_helper.h"
34 #include "nir/nir.h"
35 #include "nir/nir_builder.h"
36 #include "spirv/nir_spirv.h"
37
38 #include <llvm-c/Core.h>
39 #include <llvm-c/TargetMachine.h>
40 #include <llvm-c/Support.h>
41
42 #include "sid.h"
43 #include "ac_binary.h"
44 #include "ac_llvm_util.h"
45 #include "ac_nir_to_llvm.h"
46 #include "ac_rtld.h"
47 #include "vk_format.h"
48 #include "util/debug.h"
49 #include "ac_exp_param.h"
50
51 #include "aco_interface.h"
52
53 #include "util/string_buffer.h"
54
55 static const struct nir_shader_compiler_options nir_options_llvm = {
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_fsat = true,
63 .lower_fdiv = true,
64 .lower_bitfield_insert_to_bitfield_select = true,
65 .lower_bitfield_extract = true,
66 .lower_sub = 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_unpack_snorm_2x16 = true,
72 .lower_unpack_snorm_4x8 = true,
73 .lower_unpack_unorm_2x16 = true,
74 .lower_unpack_unorm_4x8 = true,
75 .lower_extract_byte = true,
76 .lower_extract_word = true,
77 .lower_ffma = true,
78 .lower_fpow = true,
79 .lower_mul_2x32_64 = true,
80 .lower_rotate = true,
81 .max_unroll_iterations = 32,
82 .use_interpolated_input_intrinsics = true,
83 };
84
85 static const struct nir_shader_compiler_options nir_options_aco = {
86 .vertex_id_zero_based = true,
87 .lower_scmp = true,
88 .lower_flrp16 = true,
89 .lower_flrp32 = true,
90 .lower_flrp64 = true,
91 .lower_device_index_to_zero = true,
92 .lower_fdiv = true,
93 .lower_bitfield_insert_to_bitfield_select = true,
94 .lower_bitfield_extract = true,
95 .lower_sub = true, /* TODO: set this to false once !1236 is merged */
96 .lower_pack_snorm_2x16 = true,
97 .lower_pack_snorm_4x8 = true,
98 .lower_pack_unorm_2x16 = true,
99 .lower_pack_unorm_4x8 = true,
100 .lower_unpack_snorm_2x16 = true,
101 .lower_unpack_snorm_4x8 = true,
102 .lower_unpack_unorm_2x16 = true,
103 .lower_unpack_unorm_4x8 = true,
104 .lower_unpack_half_2x16 = true,
105 .lower_extract_byte = true,
106 .lower_extract_word = true,
107 .lower_ffma = true,
108 .lower_fpow = true,
109 .lower_mul_2x32_64 = true,
110 .lower_rotate = true,
111 .max_unroll_iterations = 32,
112 .use_interpolated_input_intrinsics = true,
113 };
114
115 bool
116 radv_can_dump_shader(struct radv_device *device,
117 struct radv_shader_module *module,
118 bool is_gs_copy_shader)
119 {
120 if (!(device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS))
121 return false;
122 if (module)
123 return !module->nir ||
124 (device->instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS);
125
126 return is_gs_copy_shader;
127 }
128
129 bool
130 radv_can_dump_shader_stats(struct radv_device *device,
131 struct radv_shader_module *module)
132 {
133 /* Only dump non-meta shader stats. */
134 return device->instance->debug_flags & RADV_DEBUG_DUMP_SHADER_STATS &&
135 module && !module->nir;
136 }
137
138 unsigned shader_io_get_unique_index(gl_varying_slot slot)
139 {
140 /* handle patch indices separate */
141 if (slot == VARYING_SLOT_TESS_LEVEL_OUTER)
142 return 0;
143 if (slot == VARYING_SLOT_TESS_LEVEL_INNER)
144 return 1;
145 if (slot >= VARYING_SLOT_PATCH0 && slot <= VARYING_SLOT_TESS_MAX)
146 return 2 + (slot - VARYING_SLOT_PATCH0);
147 if (slot == VARYING_SLOT_POS)
148 return 0;
149 if (slot == VARYING_SLOT_PSIZ)
150 return 1;
151 if (slot == VARYING_SLOT_CLIP_DIST0)
152 return 2;
153 if (slot == VARYING_SLOT_CLIP_DIST1)
154 return 3;
155 /* 3 is reserved for clip dist as well */
156 if (slot >= VARYING_SLOT_VAR0 && slot <= VARYING_SLOT_VAR31)
157 return 4 + (slot - VARYING_SLOT_VAR0);
158 unreachable("illegal slot in get unique index\n");
159 }
160
161 VkResult radv_CreateShaderModule(
162 VkDevice _device,
163 const VkShaderModuleCreateInfo* pCreateInfo,
164 const VkAllocationCallbacks* pAllocator,
165 VkShaderModule* pShaderModule)
166 {
167 RADV_FROM_HANDLE(radv_device, device, _device);
168 struct radv_shader_module *module;
169
170 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
171 assert(pCreateInfo->flags == 0);
172
173 module = vk_alloc2(&device->alloc, pAllocator,
174 sizeof(*module) + pCreateInfo->codeSize, 8,
175 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
176 if (module == NULL)
177 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
178
179 module->nir = NULL;
180 module->size = pCreateInfo->codeSize;
181 memcpy(module->data, pCreateInfo->pCode, module->size);
182
183 _mesa_sha1_compute(module->data, module->size, module->sha1);
184
185 *pShaderModule = radv_shader_module_to_handle(module);
186
187 return VK_SUCCESS;
188 }
189
190 void radv_DestroyShaderModule(
191 VkDevice _device,
192 VkShaderModule _module,
193 const VkAllocationCallbacks* pAllocator)
194 {
195 RADV_FROM_HANDLE(radv_device, device, _device);
196 RADV_FROM_HANDLE(radv_shader_module, module, _module);
197
198 if (!module)
199 return;
200
201 vk_free2(&device->alloc, pAllocator, module);
202 }
203
204 void
205 radv_optimize_nir(struct nir_shader *shader, bool optimize_conservatively,
206 bool allow_copies)
207 {
208 bool progress;
209 unsigned lower_flrp =
210 (shader->options->lower_flrp16 ? 16 : 0) |
211 (shader->options->lower_flrp32 ? 32 : 0) |
212 (shader->options->lower_flrp64 ? 64 : 0);
213
214 do {
215 progress = false;
216
217 NIR_PASS(progress, shader, nir_split_array_vars, nir_var_function_temp);
218 NIR_PASS(progress, shader, nir_shrink_vec_array_vars, nir_var_function_temp);
219
220 NIR_PASS_V(shader, nir_lower_vars_to_ssa);
221 NIR_PASS_V(shader, nir_lower_pack);
222
223 if (allow_copies) {
224 /* Only run this pass in the first call to
225 * radv_optimize_nir. Later calls assume that we've
226 * lowered away any copy_deref instructions and we
227 * don't want to introduce any more.
228 */
229 NIR_PASS(progress, shader, nir_opt_find_array_copies);
230 }
231
232 NIR_PASS(progress, shader, nir_opt_copy_prop_vars);
233 NIR_PASS(progress, shader, nir_opt_dead_write_vars);
234 NIR_PASS(progress, shader, nir_remove_dead_variables,
235 nir_var_function_temp);
236
237 NIR_PASS_V(shader, nir_lower_alu_to_scalar, NULL, NULL);
238 NIR_PASS_V(shader, nir_lower_phis_to_scalar);
239
240 NIR_PASS(progress, shader, nir_copy_prop);
241 NIR_PASS(progress, shader, nir_opt_remove_phis);
242 NIR_PASS(progress, shader, nir_opt_dce);
243 if (nir_opt_trivial_continues(shader)) {
244 progress = true;
245 NIR_PASS(progress, shader, nir_copy_prop);
246 NIR_PASS(progress, shader, nir_opt_remove_phis);
247 NIR_PASS(progress, shader, nir_opt_dce);
248 }
249 NIR_PASS(progress, shader, nir_opt_if, true);
250 NIR_PASS(progress, shader, nir_opt_dead_cf);
251 NIR_PASS(progress, shader, nir_opt_cse);
252 NIR_PASS(progress, shader, nir_opt_peephole_select, 8, true, true);
253 NIR_PASS(progress, shader, nir_opt_constant_folding);
254 NIR_PASS(progress, shader, nir_opt_algebraic);
255
256 if (lower_flrp != 0) {
257 bool lower_flrp_progress = false;
258 NIR_PASS(lower_flrp_progress,
259 shader,
260 nir_lower_flrp,
261 lower_flrp,
262 false /* always_precise */,
263 shader->options->lower_ffma);
264 if (lower_flrp_progress) {
265 NIR_PASS(progress, shader,
266 nir_opt_constant_folding);
267 progress = true;
268 }
269
270 /* Nothing should rematerialize any flrps, so we only
271 * need to do this lowering once.
272 */
273 lower_flrp = 0;
274 }
275
276 NIR_PASS(progress, shader, nir_opt_undef);
277 if (shader->options->max_unroll_iterations) {
278 NIR_PASS(progress, shader, nir_opt_loop_unroll, 0);
279 }
280 } while (progress && !optimize_conservatively);
281
282 NIR_PASS(progress, shader, nir_opt_conditional_discard);
283 NIR_PASS(progress, shader, nir_opt_shrink_load);
284 NIR_PASS(progress, shader, nir_opt_move, nir_move_load_ubo);
285 }
286
287 nir_shader *
288 radv_shader_compile_to_nir(struct radv_device *device,
289 struct radv_shader_module *module,
290 const char *entrypoint_name,
291 gl_shader_stage stage,
292 const VkSpecializationInfo *spec_info,
293 const VkPipelineCreateFlags flags,
294 const struct radv_pipeline_layout *layout,
295 bool use_aco)
296 {
297 nir_shader *nir;
298 const nir_shader_compiler_options *nir_options = use_aco ? &nir_options_aco :
299 &nir_options_llvm;
300 if (module->nir) {
301 /* Some things such as our meta clear/blit code will give us a NIR
302 * shader directly. In that case, we just ignore the SPIR-V entirely
303 * and just use the NIR shader */
304 nir = module->nir;
305 nir->options = nir_options;
306 nir_validate_shader(nir, "in internal shader");
307
308 assert(exec_list_length(&nir->functions) == 1);
309 } else {
310 uint32_t *spirv = (uint32_t *) module->data;
311 assert(module->size % 4 == 0);
312
313 if (device->instance->debug_flags & RADV_DEBUG_DUMP_SPIRV)
314 radv_print_spirv(spirv, module->size, stderr);
315
316 uint32_t num_spec_entries = 0;
317 struct nir_spirv_specialization *spec_entries = NULL;
318 if (spec_info && spec_info->mapEntryCount > 0) {
319 num_spec_entries = spec_info->mapEntryCount;
320 spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
321 for (uint32_t i = 0; i < num_spec_entries; i++) {
322 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
323 const void *data = spec_info->pData + entry.offset;
324 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
325
326 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
327 if (spec_info->dataSize == 8)
328 spec_entries[i].data64 = *(const uint64_t *)data;
329 else
330 spec_entries[i].data32 = *(const uint32_t *)data;
331 }
332 }
333 const struct spirv_to_nir_options spirv_options = {
334 .lower_ubo_ssbo_access_to_offsets = true,
335 .caps = {
336 .amd_gcn_shader = true,
337 .amd_shader_ballot = device->physical_device->use_shader_ballot,
338 .amd_trinary_minmax = true,
339 .demote_to_helper_invocation = device->physical_device->use_aco,
340 .derivative_group = true,
341 .descriptor_array_dynamic_indexing = true,
342 .descriptor_array_non_uniform_indexing = true,
343 .descriptor_indexing = true,
344 .device_group = true,
345 .draw_parameters = true,
346 .float16 = !device->physical_device->use_aco,
347 .float64 = true,
348 .geometry_streams = true,
349 .image_read_without_format = true,
350 .image_write_without_format = true,
351 .int8 = !device->physical_device->use_aco,
352 .int16 = !device->physical_device->use_aco,
353 .int64 = true,
354 .int64_atomics = true,
355 .multiview = true,
356 .physical_storage_buffer_address = true,
357 .post_depth_coverage = true,
358 .runtime_descriptor_array = true,
359 .shader_viewport_index_layer = true,
360 .stencil_export = true,
361 .storage_8bit = !device->physical_device->use_aco,
362 .storage_16bit = !device->physical_device->use_aco,
363 .storage_image_ms = true,
364 .subgroup_arithmetic = true,
365 .subgroup_ballot = true,
366 .subgroup_basic = true,
367 .subgroup_quad = true,
368 .subgroup_shuffle = true,
369 .subgroup_vote = true,
370 .tessellation = true,
371 .transform_feedback = true,
372 .variable_pointers = true,
373 },
374 .ubo_addr_format = nir_address_format_32bit_index_offset,
375 .ssbo_addr_format = nir_address_format_32bit_index_offset,
376 .phys_ssbo_addr_format = nir_address_format_64bit_global,
377 .push_const_addr_format = nir_address_format_logical,
378 .shared_addr_format = nir_address_format_32bit_offset,
379 .frag_coord_is_sysval = true,
380 };
381 nir = spirv_to_nir(spirv, module->size / 4,
382 spec_entries, num_spec_entries,
383 stage, entrypoint_name,
384 &spirv_options, nir_options);
385 assert(nir->info.stage == stage);
386 nir_validate_shader(nir, "after spirv_to_nir");
387
388 free(spec_entries);
389
390 /* We have to lower away local constant initializers right before we
391 * inline functions. That way they get properly initialized at the top
392 * of the function and not at the top of its caller.
393 */
394 NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_function_temp);
395 NIR_PASS_V(nir, nir_lower_returns);
396 NIR_PASS_V(nir, nir_inline_functions);
397 NIR_PASS_V(nir, nir_opt_deref);
398
399 /* Pick off the single entrypoint that we want */
400 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
401 if (func->is_entrypoint)
402 func->name = ralloc_strdup(func, "main");
403 else
404 exec_node_remove(&func->node);
405 }
406 assert(exec_list_length(&nir->functions) == 1);
407
408 /* Make sure we lower constant initializers on output variables so that
409 * nir_remove_dead_variables below sees the corresponding stores
410 */
411 NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_shader_out);
412
413 /* Now that we've deleted all but the main function, we can go ahead and
414 * lower the rest of the constant initializers.
415 */
416 NIR_PASS_V(nir, nir_lower_constant_initializers, ~0);
417
418 /* Split member structs. We do this before lower_io_to_temporaries so that
419 * it doesn't lower system values to temporaries by accident.
420 */
421 NIR_PASS_V(nir, nir_split_var_copies);
422 NIR_PASS_V(nir, nir_split_per_member_structs);
423
424 if (nir->info.stage == MESA_SHADER_FRAGMENT && use_aco)
425 NIR_PASS_V(nir, nir_lower_io_to_vector, nir_var_shader_out);
426 if (nir->info.stage == MESA_SHADER_FRAGMENT)
427 NIR_PASS_V(nir, nir_lower_input_attachments, true);
428
429 NIR_PASS_V(nir, nir_remove_dead_variables,
430 nir_var_shader_in | nir_var_shader_out | nir_var_system_value | nir_var_mem_shared);
431
432 NIR_PASS_V(nir, nir_propagate_invariant);
433
434 NIR_PASS_V(nir, nir_lower_system_values);
435 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
436 NIR_PASS_V(nir, radv_nir_lower_ycbcr_textures, layout);
437 }
438
439 /* Vulkan uses the separate-shader linking model */
440 nir->info.separate_shader = true;
441
442 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
443
444 static const nir_lower_tex_options tex_options = {
445 .lower_txp = ~0,
446 .lower_tg4_offsets = true,
447 };
448
449 nir_lower_tex(nir, &tex_options);
450
451 nir_lower_vars_to_ssa(nir);
452
453 if (nir->info.stage == MESA_SHADER_VERTEX ||
454 nir->info.stage == MESA_SHADER_GEOMETRY ||
455 nir->info.stage == MESA_SHADER_FRAGMENT) {
456 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
457 nir_shader_get_entrypoint(nir), true, true);
458 } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
459 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
460 nir_shader_get_entrypoint(nir), true, false);
461 }
462
463 nir_split_var_copies(nir);
464
465 nir_lower_global_vars_to_local(nir);
466 nir_remove_dead_variables(nir, nir_var_function_temp);
467 nir_lower_subgroups(nir, &(struct nir_lower_subgroups_options) {
468 .subgroup_size = 64,
469 .ballot_bit_size = 64,
470 .lower_to_scalar = 1,
471 .lower_subgroup_masks = 1,
472 .lower_shuffle = 1,
473 .lower_shuffle_to_32bit = 1,
474 .lower_vote_eq_to_ballot = 1,
475 });
476
477 nir_lower_load_const_to_scalar(nir);
478
479 if (!(flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT))
480 radv_optimize_nir(nir, false, true);
481
482 /* We call nir_lower_var_copies() after the first radv_optimize_nir()
483 * to remove any copies introduced by nir_opt_find_array_copies().
484 */
485 nir_lower_var_copies(nir);
486
487 /* Lower large variables that are always constant with load_constant
488 * intrinsics, which get turned into PC-relative loads from a data
489 * section next to the shader.
490 */
491 NIR_PASS_V(nir, nir_opt_large_constants,
492 glsl_get_natural_size_align_bytes, 16);
493
494 /* Indirect lowering must be called after the radv_optimize_nir() loop
495 * has been called at least once. Otherwise indirect lowering can
496 * bloat the instruction count of the loop and cause it to be
497 * considered too large for unrolling.
498 */
499 ac_lower_indirect_derefs(nir, device->physical_device->rad_info.chip_class);
500 radv_optimize_nir(nir, flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT, false);
501
502 return nir;
503 }
504
505 static int
506 type_size_vec4(const struct glsl_type *type, bool bindless)
507 {
508 return glsl_count_attribute_slots(type, false);
509 }
510
511 static nir_variable *
512 find_layer_in_var(nir_shader *nir)
513 {
514 nir_foreach_variable(var, &nir->inputs) {
515 if (var->data.location == VARYING_SLOT_LAYER) {
516 return var;
517 }
518 }
519
520 nir_variable *var =
521 nir_variable_create(nir, nir_var_shader_in, glsl_int_type(), "layer id");
522 var->data.location = VARYING_SLOT_LAYER;
523 var->data.interpolation = INTERP_MODE_FLAT;
524 return var;
525 }
526
527 /* We use layered rendering to implement multiview, which means we need to map
528 * view_index to gl_Layer. The attachment lowering also uses needs to know the
529 * layer so that it can sample from the correct layer. The code generates a
530 * load from the layer_id sysval, but since we don't have a way to get at this
531 * information from the fragment shader, we also need to lower this to the
532 * gl_Layer varying. This pass lowers both to a varying load from the LAYER
533 * slot, before lowering io, so that nir_assign_var_locations() will give the
534 * LAYER varying the correct driver_location.
535 */
536
537 static bool
538 lower_view_index(nir_shader *nir)
539 {
540 bool progress = false;
541 nir_function_impl *entry = nir_shader_get_entrypoint(nir);
542 nir_builder b;
543 nir_builder_init(&b, entry);
544
545 nir_variable *layer = NULL;
546 nir_foreach_block(block, entry) {
547 nir_foreach_instr_safe(instr, block) {
548 if (instr->type != nir_instr_type_intrinsic)
549 continue;
550
551 nir_intrinsic_instr *load = nir_instr_as_intrinsic(instr);
552 if (load->intrinsic != nir_intrinsic_load_view_index &&
553 load->intrinsic != nir_intrinsic_load_layer_id)
554 continue;
555
556 if (!layer)
557 layer = find_layer_in_var(nir);
558
559 b.cursor = nir_before_instr(instr);
560 nir_ssa_def *def = nir_load_var(&b, layer);
561 nir_ssa_def_rewrite_uses(&load->dest.ssa,
562 nir_src_for_ssa(def));
563
564 nir_instr_remove(instr);
565 progress = true;
566 }
567 }
568
569 return progress;
570 }
571
572 void
573 radv_lower_fs_io(nir_shader *nir)
574 {
575 NIR_PASS_V(nir, lower_view_index);
576 nir_assign_io_var_locations(&nir->inputs, &nir->num_inputs,
577 MESA_SHADER_FRAGMENT);
578
579 NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in, type_size_vec4, 0);
580
581 /* This pass needs actual constants */
582 nir_opt_constant_folding(nir);
583
584 NIR_PASS_V(nir, nir_io_add_const_offset_to_base, nir_var_shader_in);
585 }
586
587
588 void *
589 radv_alloc_shader_memory(struct radv_device *device,
590 struct radv_shader_variant *shader)
591 {
592 mtx_lock(&device->shader_slab_mutex);
593 list_for_each_entry(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
594 uint64_t offset = 0;
595 list_for_each_entry(struct radv_shader_variant, s, &slab->shaders, slab_list) {
596 if (s->bo_offset - offset >= shader->code_size) {
597 shader->bo = slab->bo;
598 shader->bo_offset = offset;
599 list_addtail(&shader->slab_list, &s->slab_list);
600 mtx_unlock(&device->shader_slab_mutex);
601 return slab->ptr + offset;
602 }
603 offset = align_u64(s->bo_offset + s->code_size, 256);
604 }
605 if (slab->size - offset >= shader->code_size) {
606 shader->bo = slab->bo;
607 shader->bo_offset = offset;
608 list_addtail(&shader->slab_list, &slab->shaders);
609 mtx_unlock(&device->shader_slab_mutex);
610 return slab->ptr + offset;
611 }
612 }
613
614 mtx_unlock(&device->shader_slab_mutex);
615 struct radv_shader_slab *slab = calloc(1, sizeof(struct radv_shader_slab));
616
617 slab->size = 256 * 1024;
618 slab->bo = device->ws->buffer_create(device->ws, slab->size, 256,
619 RADEON_DOMAIN_VRAM,
620 RADEON_FLAG_NO_INTERPROCESS_SHARING |
621 (device->physical_device->rad_info.cpdma_prefetch_writes_memory ?
622 0 : RADEON_FLAG_READ_ONLY),
623 RADV_BO_PRIORITY_SHADER);
624 slab->ptr = (char*)device->ws->buffer_map(slab->bo);
625 list_inithead(&slab->shaders);
626
627 mtx_lock(&device->shader_slab_mutex);
628 list_add(&slab->slabs, &device->shader_slabs);
629
630 shader->bo = slab->bo;
631 shader->bo_offset = 0;
632 list_add(&shader->slab_list, &slab->shaders);
633 mtx_unlock(&device->shader_slab_mutex);
634 return slab->ptr;
635 }
636
637 void
638 radv_destroy_shader_slabs(struct radv_device *device)
639 {
640 list_for_each_entry_safe(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
641 device->ws->buffer_destroy(slab->bo);
642 free(slab);
643 }
644 mtx_destroy(&device->shader_slab_mutex);
645 }
646
647 /* For the UMR disassembler. */
648 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
649 #define DEBUGGER_NUM_MARKERS 5
650
651 static unsigned
652 radv_get_shader_binary_size(size_t code_size)
653 {
654 return code_size + DEBUGGER_NUM_MARKERS * 4;
655 }
656
657 static void radv_postprocess_config(const struct radv_physical_device *pdevice,
658 const struct ac_shader_config *config_in,
659 const struct radv_shader_info *info,
660 gl_shader_stage stage,
661 struct ac_shader_config *config_out)
662 {
663 bool scratch_enabled = config_in->scratch_bytes_per_wave > 0;
664 unsigned vgpr_comp_cnt = 0;
665 unsigned num_input_vgprs = info->num_input_vgprs;
666
667 if (stage == MESA_SHADER_FRAGMENT) {
668 num_input_vgprs = ac_get_fs_input_vgpr_cnt(config_in, NULL, NULL);
669 }
670
671 unsigned num_vgprs = MAX2(config_in->num_vgprs, num_input_vgprs);
672 /* +3 for scratch wave offset and VCC */
673 unsigned num_sgprs = MAX2(config_in->num_sgprs, info->num_input_sgprs + 3);
674 unsigned num_shared_vgprs = config_in->num_shared_vgprs;
675 /* shared VGPRs are introduced in Navi and are allocated in blocks of 8 (RDNA ref 3.6.5) */
676 assert((pdevice->rad_info.chip_class >= GFX10 && num_shared_vgprs % 8 == 0)
677 || (pdevice->rad_info.chip_class < GFX10 && num_shared_vgprs == 0));
678 unsigned num_shared_vgpr_blocks = num_shared_vgprs / 8;
679
680 *config_out = *config_in;
681 config_out->num_vgprs = num_vgprs;
682 config_out->num_sgprs = num_sgprs;
683 config_out->num_shared_vgprs = num_shared_vgprs;
684
685 /* Enable 64-bit and 16-bit denormals, because there is no performance
686 * cost.
687 *
688 * If denormals are enabled, all floating-point output modifiers are
689 * ignored.
690 *
691 * Don't enable denormals for 32-bit floats, because:
692 * - Floating-point output modifiers would be ignored by the hw.
693 * - Some opcodes don't support denormals, such as v_mad_f32. We would
694 * have to stop using those.
695 * - GFX6 & GFX7 would be very slow.
696 */
697 config_out->float_mode |= V_00B028_FP_64_DENORMS;
698
699 config_out->rsrc2 = S_00B12C_USER_SGPR(info->num_user_sgprs) |
700 S_00B12C_SCRATCH_EN(scratch_enabled);
701
702 if (!pdevice->use_ngg_streamout) {
703 config_out->rsrc2 |= S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) |
704 S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
705 S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) |
706 S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
707 S_00B12C_SO_EN(!!info->so.num_outputs);
708 }
709
710 config_out->rsrc1 = S_00B848_VGPRS((num_vgprs - 1) /
711 (info->wave_size == 32 ? 8 : 4)) |
712 S_00B848_DX10_CLAMP(1) |
713 S_00B848_FLOAT_MODE(config_out->float_mode);
714
715 if (pdevice->rad_info.chip_class >= GFX10) {
716 config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(info->num_user_sgprs >> 5);
717 } else {
718 config_out->rsrc1 |= S_00B228_SGPRS((num_sgprs - 1) / 8);
719 config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(info->num_user_sgprs >> 5);
720 }
721
722 switch (stage) {
723 case MESA_SHADER_TESS_EVAL:
724 if (info->is_ngg) {
725 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
726 config_out->rsrc2 |= S_00B22C_OC_LDS_EN(1);
727 } else if (info->tes.as_es) {
728 assert(pdevice->rad_info.chip_class <= GFX8);
729 vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
730
731 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
732 } else {
733 bool enable_prim_id = info->tes.export_prim_id || info->uses_prim_id;
734 vgpr_comp_cnt = enable_prim_id ? 3 : 2;
735
736 config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
737 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
738 }
739 config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
740 break;
741 case MESA_SHADER_TESS_CTRL:
742 if (pdevice->rad_info.chip_class >= GFX9) {
743 /* We need at least 2 components for LS.
744 * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
745 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
746 */
747 if (pdevice->rad_info.chip_class >= GFX10) {
748 vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 1;
749 } else {
750 vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
751 }
752 } else {
753 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
754 }
755 config_out->rsrc1 |= S_00B428_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
756 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
757 config_out->rsrc2 |= S_00B42C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
758 break;
759 case MESA_SHADER_VERTEX:
760 if (info->is_ngg) {
761 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
762 } else if (info->vs.as_ls) {
763 assert(pdevice->rad_info.chip_class <= GFX8);
764 /* We need at least 2 components for LS.
765 * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
766 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
767 */
768 vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
769 } else if (info->vs.as_es) {
770 assert(pdevice->rad_info.chip_class <= GFX8);
771 /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
772 vgpr_comp_cnt = info->vs.needs_instance_id ? 1 : 0;
773 } else {
774 /* VGPR0-3: (VertexID, InstanceID / StepRate0, PrimID, InstanceID)
775 * If PrimID is disabled. InstanceID / StepRate1 is loaded instead.
776 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
777 */
778 if (info->vs.needs_instance_id && pdevice->rad_info.chip_class >= GFX10) {
779 vgpr_comp_cnt = 3;
780 } else if (info->vs.export_prim_id) {
781 vgpr_comp_cnt = 2;
782 } else if (info->vs.needs_instance_id) {
783 vgpr_comp_cnt = 1;
784 } else {
785 vgpr_comp_cnt = 0;
786 }
787
788 config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
789 config_out->rsrc2 |= S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
790 }
791 break;
792 case MESA_SHADER_FRAGMENT:
793 config_out->rsrc1 |= S_00B028_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
794 config_out->rsrc2 |= S_00B02C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
795 break;
796 case MESA_SHADER_GEOMETRY:
797 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
798 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
799 config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
800 break;
801 case MESA_SHADER_COMPUTE:
802 config_out->rsrc1 |= S_00B848_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
803 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
804 config_out->rsrc2 |=
805 S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) |
806 S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
807 S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
808 S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2] ? 2 :
809 info->cs.uses_thread_id[1] ? 1 : 0) |
810 S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) |
811 S_00B84C_LDS_SIZE(config_in->lds_size);
812 config_out->rsrc3 |= S_00B8A0_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
813
814 break;
815 default:
816 unreachable("unsupported shader type");
817 break;
818 }
819
820 if (pdevice->rad_info.chip_class >= GFX10 && info->is_ngg &&
821 (stage == MESA_SHADER_VERTEX || stage == MESA_SHADER_TESS_EVAL || stage == MESA_SHADER_GEOMETRY)) {
822 unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
823 gl_shader_stage es_stage = stage;
824 if (stage == MESA_SHADER_GEOMETRY)
825 es_stage = info->gs.es_type;
826
827 /* VGPR5-8: (VertexID, UserVGPR0, UserVGPR1, UserVGPR2 / InstanceID) */
828 if (es_stage == MESA_SHADER_VERTEX) {
829 es_vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 0;
830 } else if (es_stage == MESA_SHADER_TESS_EVAL) {
831 bool enable_prim_id = info->tes.export_prim_id || info->uses_prim_id;
832 es_vgpr_comp_cnt = enable_prim_id ? 3 : 2;
833 } else
834 unreachable("Unexpected ES shader stage");
835
836 bool tes_triangles = stage == MESA_SHADER_TESS_EVAL &&
837 info->tes.primitive_mode >= 4; /* GL_TRIANGLES */
838 if (info->uses_invocation_id || stage == MESA_SHADER_VERTEX) {
839 gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
840 } else if (info->uses_prim_id) {
841 gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
842 } else if (info->gs.vertices_in >= 3 || tes_triangles) {
843 gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
844 } else {
845 gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
846 }
847
848 config_out->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) |
849 S_00B228_WGP_MODE(1);
850 config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
851 S_00B22C_LDS_SIZE(config_in->lds_size) |
852 S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
853 } else if (pdevice->rad_info.chip_class >= GFX9 &&
854 stage == MESA_SHADER_GEOMETRY) {
855 unsigned es_type = info->gs.es_type;
856 unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
857
858 if (es_type == MESA_SHADER_VERTEX) {
859 /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
860 if (info->vs.needs_instance_id) {
861 es_vgpr_comp_cnt = pdevice->rad_info.chip_class >= GFX10 ? 3 : 1;
862 } else {
863 es_vgpr_comp_cnt = 0;
864 }
865 } else if (es_type == MESA_SHADER_TESS_EVAL) {
866 es_vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
867 } else {
868 unreachable("invalid shader ES type");
869 }
870
871 /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
872 * VGPR[0:4] are always loaded.
873 */
874 if (info->uses_invocation_id) {
875 gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
876 } else if (info->uses_prim_id) {
877 gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
878 } else if (info->gs.vertices_in >= 3) {
879 gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
880 } else {
881 gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
882 }
883
884 config_out->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt);
885 config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
886 S_00B22C_OC_LDS_EN(es_type == MESA_SHADER_TESS_EVAL);
887 } else if (pdevice->rad_info.chip_class >= GFX9 &&
888 stage == MESA_SHADER_TESS_CTRL) {
889 config_out->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
890 } else {
891 config_out->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
892 }
893 }
894
895 struct radv_shader_variant *
896 radv_shader_variant_create(struct radv_device *device,
897 const struct radv_shader_binary *binary,
898 bool keep_shader_info)
899 {
900 struct ac_shader_config config = {0};
901 struct ac_rtld_binary rtld_binary = {0};
902 struct radv_shader_variant *variant = calloc(1, sizeof(struct radv_shader_variant));
903 if (!variant)
904 return NULL;
905
906 variant->ref_count = 1;
907
908 if (binary->type == RADV_BINARY_TYPE_RTLD) {
909 struct ac_rtld_symbol lds_symbols[2];
910 unsigned num_lds_symbols = 0;
911 const char *elf_data = (const char *)((struct radv_shader_binary_rtld *)binary)->data;
912 size_t elf_size = ((struct radv_shader_binary_rtld *)binary)->elf_size;
913
914 if (device->physical_device->rad_info.chip_class >= GFX9 &&
915 (binary->stage == MESA_SHADER_GEOMETRY || binary->info.is_ngg) &&
916 !binary->is_gs_copy_shader) {
917 /* We add this symbol even on LLVM <= 8 to ensure that
918 * shader->config.lds_size is set correctly below.
919 */
920 /* TODO: For some reasons, using the computed ESGS ring
921 * size randomly hangs with CTS. Just use the maximum
922 * possible LDS size for now.
923 */
924 unsigned ngg_scratch_size = 8 * 4;
925 if (binary->info.so.num_outputs) {
926 /* Memory layout of NGG streamout scratch:
927 * [0-3]: number of generated primitives
928 * [4-7]: number of emitted primitives
929 * [8-11]: streamout offsets
930 * [12:19]: primitive offsets for stream 0
931 * [20:27]: primitive offsets for stream 1
932 * [28:35]: primitive offsets for stream 2
933 * [36:43]: primitive offsets for stream 3
934 */
935 ngg_scratch_size = 44 * 4;
936 }
937
938 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
939 sym->name = "esgs_ring";
940 sym->size = (32 * 1024) - (binary->info.ngg_info.ngg_emit_size * 4) - ngg_scratch_size;
941 sym->align = 64 * 1024;
942 }
943
944 if (binary->info.is_ngg &&
945 binary->stage == MESA_SHADER_GEOMETRY) {
946 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
947 sym->name = "ngg_emit";
948 sym->size = binary->info.ngg_info.ngg_emit_size * 4;
949 sym->align = 4;
950 }
951
952 struct ac_rtld_open_info open_info = {
953 .info = &device->physical_device->rad_info,
954 .shader_type = binary->stage,
955 .wave_size = binary->info.wave_size,
956 .num_parts = 1,
957 .elf_ptrs = &elf_data,
958 .elf_sizes = &elf_size,
959 .num_shared_lds_symbols = num_lds_symbols,
960 .shared_lds_symbols = lds_symbols,
961 };
962
963 if (!ac_rtld_open(&rtld_binary, open_info)) {
964 free(variant);
965 return NULL;
966 }
967
968 if (!ac_rtld_read_config(&rtld_binary, &config)) {
969 ac_rtld_close(&rtld_binary);
970 free(variant);
971 return NULL;
972 }
973
974 if (rtld_binary.lds_size > 0) {
975 unsigned alloc_granularity = device->physical_device->rad_info.chip_class >= GFX7 ? 512 : 256;
976 config.lds_size = align(rtld_binary.lds_size, alloc_granularity) / alloc_granularity;
977 }
978
979 variant->code_size = rtld_binary.rx_size;
980 variant->exec_size = rtld_binary.exec_size;
981 } else {
982 assert(binary->type == RADV_BINARY_TYPE_LEGACY);
983 config = ((struct radv_shader_binary_legacy *)binary)->config;
984 variant->code_size = radv_get_shader_binary_size(((struct radv_shader_binary_legacy *)binary)->code_size);
985 variant->exec_size = ((struct radv_shader_binary_legacy *)binary)->exec_size;
986 }
987
988 variant->info = binary->info;
989 radv_postprocess_config(device->physical_device, &config, &binary->info,
990 binary->stage, &variant->config);
991
992 void *dest_ptr = radv_alloc_shader_memory(device, variant);
993
994 if (binary->type == RADV_BINARY_TYPE_RTLD) {
995 struct radv_shader_binary_rtld* bin = (struct radv_shader_binary_rtld *)binary;
996 struct ac_rtld_upload_info info = {
997 .binary = &rtld_binary,
998 .rx_va = radv_buffer_get_va(variant->bo) + variant->bo_offset,
999 .rx_ptr = dest_ptr,
1000 };
1001
1002 if (!ac_rtld_upload(&info)) {
1003 radv_shader_variant_destroy(device, variant);
1004 ac_rtld_close(&rtld_binary);
1005 return NULL;
1006 }
1007
1008 if (keep_shader_info ||
1009 (device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS)) {
1010 const char *disasm_data;
1011 size_t disasm_size;
1012 if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm_data, &disasm_size)) {
1013 radv_shader_variant_destroy(device, variant);
1014 ac_rtld_close(&rtld_binary);
1015 return NULL;
1016 }
1017
1018 variant->ir_string = bin->llvm_ir_size ? strdup((const char*)(bin->data + bin->elf_size)) : NULL;
1019 variant->disasm_string = malloc(disasm_size + 1);
1020 memcpy(variant->disasm_string, disasm_data, disasm_size);
1021 variant->disasm_string[disasm_size] = 0;
1022 }
1023
1024 ac_rtld_close(&rtld_binary);
1025 } else {
1026 struct radv_shader_binary_legacy* bin = (struct radv_shader_binary_legacy *)binary;
1027 memcpy(dest_ptr, bin->data, bin->code_size);
1028
1029 /* Add end-of-code markers for the UMR disassembler. */
1030 uint32_t *ptr32 = (uint32_t *)dest_ptr + bin->code_size / 4;
1031 for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
1032 ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
1033
1034 variant->ir_string = bin->ir_size ? strdup((const char*)(bin->data + bin->code_size)) : NULL;
1035 variant->disasm_string = bin->disasm_size ? strdup((const char*)(bin->data + bin->code_size + bin->ir_size)) : NULL;
1036 }
1037 return variant;
1038 }
1039
1040 static char *
1041 radv_dump_nir_shaders(struct nir_shader * const *shaders,
1042 int shader_count)
1043 {
1044 char *data = NULL;
1045 char *ret = NULL;
1046 size_t size = 0;
1047 FILE *f = open_memstream(&data, &size);
1048 if (f) {
1049 for (int i = 0; i < shader_count; ++i)
1050 nir_print_shader(shaders[i], f);
1051 fclose(f);
1052 }
1053
1054 ret = malloc(size + 1);
1055 if (ret) {
1056 memcpy(ret, data, size);
1057 ret[size] = 0;
1058 }
1059 free(data);
1060 return ret;
1061 }
1062
1063 static struct radv_shader_variant *
1064 shader_variant_compile(struct radv_device *device,
1065 struct radv_shader_module *module,
1066 struct nir_shader * const *shaders,
1067 int shader_count,
1068 gl_shader_stage stage,
1069 struct radv_shader_info *info,
1070 struct radv_nir_compiler_options *options,
1071 bool gs_copy_shader,
1072 bool keep_shader_info,
1073 bool use_aco,
1074 struct radv_shader_binary **binary_out)
1075 {
1076 enum radeon_family chip_family = device->physical_device->rad_info.family;
1077 struct radv_shader_binary *binary = NULL;
1078
1079 options->family = chip_family;
1080 options->chip_class = device->physical_device->rad_info.chip_class;
1081 options->dump_shader = radv_can_dump_shader(device, module, gs_copy_shader);
1082 options->dump_preoptir = options->dump_shader &&
1083 device->instance->debug_flags & RADV_DEBUG_PREOPTIR;
1084 options->record_ir = keep_shader_info;
1085 options->check_ir = device->instance->debug_flags & RADV_DEBUG_CHECKIR;
1086 options->tess_offchip_block_dw_size = device->tess_offchip_block_dw_size;
1087 options->address32_hi = device->physical_device->rad_info.address32_hi;
1088 options->has_ls_vgpr_init_bug = device->physical_device->rad_info.has_ls_vgpr_init_bug;
1089 options->use_ngg_streamout = device->physical_device->use_ngg_streamout;
1090
1091 if ((stage == MESA_SHADER_GEOMETRY && !options->key.vs_common_out.as_ngg) ||
1092 gs_copy_shader)
1093 options->wave_size = 64;
1094 else if (stage == MESA_SHADER_COMPUTE)
1095 options->wave_size = device->physical_device->cs_wave_size;
1096 else if (stage == MESA_SHADER_FRAGMENT)
1097 options->wave_size = device->physical_device->ps_wave_size;
1098 else
1099 options->wave_size = device->physical_device->ge_wave_size;
1100
1101 if (!use_aco || options->dump_shader || options->record_ir)
1102 ac_init_llvm_once();
1103
1104 if (use_aco) {
1105 aco_compile_shader(shader_count, shaders, &binary, info, options);
1106 binary->info = *info;
1107 } else {
1108 enum ac_target_machine_options tm_options = 0;
1109 struct ac_llvm_compiler ac_llvm;
1110 bool thread_compiler;
1111
1112 if (options->supports_spill)
1113 tm_options |= AC_TM_SUPPORTS_SPILL;
1114 if (device->instance->perftest_flags & RADV_PERFTEST_SISCHED)
1115 tm_options |= AC_TM_SISCHED;
1116 if (options->check_ir)
1117 tm_options |= AC_TM_CHECK_IR;
1118 if (device->instance->debug_flags & RADV_DEBUG_NO_LOAD_STORE_OPT)
1119 tm_options |= AC_TM_NO_LOAD_STORE_OPT;
1120
1121 thread_compiler = !(device->instance->debug_flags & RADV_DEBUG_NOTHREADLLVM);
1122 radv_init_llvm_compiler(&ac_llvm,
1123 thread_compiler,
1124 chip_family, tm_options,
1125 options->wave_size);
1126
1127 if (gs_copy_shader) {
1128 assert(shader_count == 1);
1129 radv_compile_gs_copy_shader(&ac_llvm, *shaders, &binary,
1130 info, options);
1131 } else {
1132 radv_compile_nir_shader(&ac_llvm, &binary, info,
1133 shaders, shader_count, options);
1134 }
1135
1136 binary->info = *info;
1137 radv_destroy_llvm_compiler(&ac_llvm, thread_compiler);
1138 }
1139
1140 struct radv_shader_variant *variant = radv_shader_variant_create(device, binary,
1141 keep_shader_info);
1142 if (!variant) {
1143 free(binary);
1144 return NULL;
1145 }
1146 variant->aco_used = use_aco;
1147
1148 if (options->dump_shader) {
1149 fprintf(stderr, "disasm:\n%s\n", variant->disasm_string);
1150 }
1151
1152
1153 if (keep_shader_info) {
1154 variant->nir_string = radv_dump_nir_shaders(shaders, shader_count);
1155 if (!gs_copy_shader && !module->nir) {
1156 variant->spirv = (uint32_t *)module->data;
1157 variant->spirv_size = module->size;
1158 }
1159 }
1160
1161 if (binary_out)
1162 *binary_out = binary;
1163 else
1164 free(binary);
1165
1166 return variant;
1167 }
1168
1169 struct radv_shader_variant *
1170 radv_shader_variant_compile(struct radv_device *device,
1171 struct radv_shader_module *module,
1172 struct nir_shader *const *shaders,
1173 int shader_count,
1174 struct radv_pipeline_layout *layout,
1175 const struct radv_shader_variant_key *key,
1176 struct radv_shader_info *info,
1177 bool keep_shader_info,
1178 bool use_aco,
1179 struct radv_shader_binary **binary_out)
1180 {
1181 struct radv_nir_compiler_options options = {0};
1182
1183 options.layout = layout;
1184 if (key)
1185 options.key = *key;
1186
1187 options.unsafe_math = !!(device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH);
1188 options.supports_spill = true;
1189 options.robust_buffer_access = device->robust_buffer_access;
1190
1191 return shader_variant_compile(device, module, shaders, shader_count, shaders[shader_count - 1]->info.stage, info,
1192 &options, false, keep_shader_info, use_aco, binary_out);
1193 }
1194
1195 struct radv_shader_variant *
1196 radv_create_gs_copy_shader(struct radv_device *device,
1197 struct nir_shader *shader,
1198 struct radv_shader_info *info,
1199 struct radv_shader_binary **binary_out,
1200 bool keep_shader_info,
1201 bool multiview)
1202 {
1203 struct radv_nir_compiler_options options = {0};
1204
1205 options.key.has_multiview_view_index = multiview;
1206
1207 return shader_variant_compile(device, NULL, &shader, 1, MESA_SHADER_VERTEX,
1208 info, &options, true, keep_shader_info, false, binary_out);
1209 }
1210
1211 void
1212 radv_shader_variant_destroy(struct radv_device *device,
1213 struct radv_shader_variant *variant)
1214 {
1215 if (!p_atomic_dec_zero(&variant->ref_count))
1216 return;
1217
1218 mtx_lock(&device->shader_slab_mutex);
1219 list_del(&variant->slab_list);
1220 mtx_unlock(&device->shader_slab_mutex);
1221
1222 free(variant->nir_string);
1223 free(variant->disasm_string);
1224 free(variant->ir_string);
1225 free(variant);
1226 }
1227
1228 const char *
1229 radv_get_shader_name(struct radv_shader_info *info,
1230 gl_shader_stage stage)
1231 {
1232 switch (stage) {
1233 case MESA_SHADER_VERTEX:
1234 if (info->vs.as_ls)
1235 return "Vertex Shader as LS";
1236 else if (info->vs.as_es)
1237 return "Vertex Shader as ES";
1238 else if (info->is_ngg)
1239 return "Vertex Shader as ESGS";
1240 else
1241 return "Vertex Shader as VS";
1242 case MESA_SHADER_TESS_CTRL:
1243 return "Tessellation Control Shader";
1244 case MESA_SHADER_TESS_EVAL:
1245 if (info->tes.as_es)
1246 return "Tessellation Evaluation Shader as ES";
1247 else if (info->is_ngg)
1248 return "Tessellation Evaluation Shader as ESGS";
1249 else
1250 return "Tessellation Evaluation Shader as VS";
1251 case MESA_SHADER_GEOMETRY:
1252 return "Geometry Shader";
1253 case MESA_SHADER_FRAGMENT:
1254 return "Pixel Shader";
1255 case MESA_SHADER_COMPUTE:
1256 return "Compute Shader";
1257 default:
1258 return "Unknown shader";
1259 };
1260 }
1261
1262 unsigned
1263 radv_get_max_workgroup_size(enum chip_class chip_class,
1264 gl_shader_stage stage,
1265 const unsigned *sizes)
1266 {
1267 switch (stage) {
1268 case MESA_SHADER_TESS_CTRL:
1269 return chip_class >= GFX7 ? 128 : 64;
1270 case MESA_SHADER_GEOMETRY:
1271 return chip_class >= GFX9 ? 128 : 64;
1272 case MESA_SHADER_COMPUTE:
1273 break;
1274 default:
1275 return 0;
1276 }
1277
1278 unsigned max_workgroup_size = sizes[0] * sizes[1] * sizes[2];
1279 return max_workgroup_size;
1280 }
1281
1282 unsigned
1283 radv_get_max_waves(struct radv_device *device,
1284 struct radv_shader_variant *variant,
1285 gl_shader_stage stage)
1286 {
1287 enum chip_class chip_class = device->physical_device->rad_info.chip_class;
1288 unsigned lds_increment = chip_class >= GFX7 ? 512 : 256;
1289 uint8_t wave_size = variant->info.wave_size;
1290 struct ac_shader_config *conf = &variant->config;
1291 unsigned max_simd_waves;
1292 unsigned lds_per_wave = 0;
1293
1294 max_simd_waves = device->physical_device->rad_info.max_wave64_per_simd;
1295
1296 if (stage == MESA_SHADER_FRAGMENT) {
1297 lds_per_wave = conf->lds_size * lds_increment +
1298 align(variant->info.ps.num_interp * 48,
1299 lds_increment);
1300 } else if (stage == MESA_SHADER_COMPUTE) {
1301 unsigned max_workgroup_size =
1302 radv_get_max_workgroup_size(chip_class, stage, variant->info.cs.block_size);
1303 lds_per_wave = (conf->lds_size * lds_increment) /
1304 DIV_ROUND_UP(max_workgroup_size, wave_size);
1305 }
1306
1307 if (conf->num_sgprs)
1308 max_simd_waves =
1309 MIN2(max_simd_waves,
1310 device->physical_device->rad_info.num_physical_sgprs_per_simd /
1311 conf->num_sgprs);
1312
1313 if (conf->num_vgprs)
1314 max_simd_waves =
1315 MIN2(max_simd_waves,
1316 RADV_NUM_PHYSICAL_VGPRS / conf->num_vgprs);
1317
1318 /* LDS is 64KB per CU (4 SIMDs), divided into 16KB blocks per SIMD
1319 * that PS can use.
1320 */
1321 if (lds_per_wave)
1322 max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
1323
1324 return max_simd_waves;
1325 }
1326
1327 static void
1328 generate_shader_stats(struct radv_device *device,
1329 struct radv_shader_variant *variant,
1330 gl_shader_stage stage,
1331 struct _mesa_string_buffer *buf)
1332 {
1333 struct ac_shader_config *conf = &variant->config;
1334 unsigned max_simd_waves = radv_get_max_waves(device, variant, stage);
1335
1336 if (stage == MESA_SHADER_FRAGMENT) {
1337 _mesa_string_buffer_printf(buf, "*** SHADER CONFIG ***\n"
1338 "SPI_PS_INPUT_ADDR = 0x%04x\n"
1339 "SPI_PS_INPUT_ENA = 0x%04x\n",
1340 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
1341 }
1342
1343 _mesa_string_buffer_printf(buf, "*** SHADER STATS ***\n"
1344 "SGPRS: %d\n"
1345 "VGPRS: %d\n"
1346 "Spilled SGPRs: %d\n"
1347 "Spilled VGPRs: %d\n"
1348 "PrivMem VGPRS: %d\n"
1349 "Code Size: %d bytes\n"
1350 "LDS: %d blocks\n"
1351 "Scratch: %d bytes per wave\n"
1352 "Max Waves: %d\n"
1353 "********************\n\n\n",
1354 conf->num_sgprs, conf->num_vgprs,
1355 conf->spilled_sgprs, conf->spilled_vgprs,
1356 variant->info.private_mem_vgprs, variant->exec_size,
1357 conf->lds_size, conf->scratch_bytes_per_wave,
1358 max_simd_waves);
1359 }
1360
1361 void
1362 radv_shader_dump_stats(struct radv_device *device,
1363 struct radv_shader_variant *variant,
1364 gl_shader_stage stage,
1365 FILE *file)
1366 {
1367 struct _mesa_string_buffer *buf = _mesa_string_buffer_create(NULL, 256);
1368
1369 generate_shader_stats(device, variant, stage, buf);
1370
1371 fprintf(file, "\n%s:\n", radv_get_shader_name(&variant->info, stage));
1372 fprintf(file, "%s", buf->buf);
1373
1374 _mesa_string_buffer_destroy(buf);
1375 }
1376
1377 VkResult
1378 radv_GetShaderInfoAMD(VkDevice _device,
1379 VkPipeline _pipeline,
1380 VkShaderStageFlagBits shaderStage,
1381 VkShaderInfoTypeAMD infoType,
1382 size_t* pInfoSize,
1383 void* pInfo)
1384 {
1385 RADV_FROM_HANDLE(radv_device, device, _device);
1386 RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);
1387 gl_shader_stage stage = vk_to_mesa_shader_stage(shaderStage);
1388 struct radv_shader_variant *variant = pipeline->shaders[stage];
1389 struct _mesa_string_buffer *buf;
1390 VkResult result = VK_SUCCESS;
1391
1392 /* Spec doesn't indicate what to do if the stage is invalid, so just
1393 * return no info for this. */
1394 if (!variant)
1395 return vk_error(device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
1396
1397 switch (infoType) {
1398 case VK_SHADER_INFO_TYPE_STATISTICS_AMD:
1399 if (!pInfo) {
1400 *pInfoSize = sizeof(VkShaderStatisticsInfoAMD);
1401 } else {
1402 unsigned lds_multiplier = device->physical_device->rad_info.chip_class >= GFX7 ? 512 : 256;
1403 struct ac_shader_config *conf = &variant->config;
1404
1405 VkShaderStatisticsInfoAMD statistics = {};
1406 statistics.shaderStageMask = shaderStage;
1407 statistics.numPhysicalVgprs = RADV_NUM_PHYSICAL_VGPRS;
1408 statistics.numPhysicalSgprs = device->physical_device->rad_info.num_physical_sgprs_per_simd;
1409 statistics.numAvailableSgprs = statistics.numPhysicalSgprs;
1410
1411 if (stage == MESA_SHADER_COMPUTE) {
1412 unsigned *local_size = variant->info.cs.block_size;
1413 unsigned workgroup_size = local_size[0] * local_size[1] * local_size[2];
1414
1415 statistics.numAvailableVgprs = statistics.numPhysicalVgprs /
1416 ceil((double)workgroup_size / statistics.numPhysicalVgprs);
1417
1418 statistics.computeWorkGroupSize[0] = local_size[0];
1419 statistics.computeWorkGroupSize[1] = local_size[1];
1420 statistics.computeWorkGroupSize[2] = local_size[2];
1421 } else {
1422 statistics.numAvailableVgprs = statistics.numPhysicalVgprs;
1423 }
1424
1425 statistics.resourceUsage.numUsedVgprs = conf->num_vgprs;
1426 statistics.resourceUsage.numUsedSgprs = conf->num_sgprs;
1427 statistics.resourceUsage.ldsSizePerLocalWorkGroup = 32768;
1428 statistics.resourceUsage.ldsUsageSizeInBytes = conf->lds_size * lds_multiplier;
1429 statistics.resourceUsage.scratchMemUsageInBytes = conf->scratch_bytes_per_wave;
1430
1431 size_t size = *pInfoSize;
1432 *pInfoSize = sizeof(statistics);
1433
1434 memcpy(pInfo, &statistics, MIN2(size, *pInfoSize));
1435
1436 if (size < *pInfoSize)
1437 result = VK_INCOMPLETE;
1438 }
1439
1440 break;
1441 case VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD:
1442 buf = _mesa_string_buffer_create(NULL, 1024);
1443
1444 _mesa_string_buffer_printf(buf, "%s:\n", radv_get_shader_name(&variant->info, stage));
1445 _mesa_string_buffer_printf(buf, "%s\n\n", variant->ir_string);
1446 _mesa_string_buffer_printf(buf, "%s\n\n", variant->disasm_string);
1447 generate_shader_stats(device, variant, stage, buf);
1448
1449 /* Need to include the null terminator. */
1450 size_t length = buf->length + 1;
1451
1452 if (!pInfo) {
1453 *pInfoSize = length;
1454 } else {
1455 size_t size = *pInfoSize;
1456 *pInfoSize = length;
1457
1458 memcpy(pInfo, buf->buf, MIN2(size, length));
1459
1460 if (size < length)
1461 result = VK_INCOMPLETE;
1462 }
1463
1464 _mesa_string_buffer_destroy(buf);
1465 break;
1466 default:
1467 /* VK_SHADER_INFO_TYPE_BINARY_AMD unimplemented for now. */
1468 result = VK_ERROR_FEATURE_NOT_PRESENT;
1469 break;
1470 }
1471
1472 return result;
1473 }