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