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