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