1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "util/mesa-sha1.h"
31 #include "util/os_time.h"
32 #include "common/intel_compute_slm.h"
33 #include "common/intel_l3_config.h"
34 #include "common/intel_sample_positions.h"
35 #include "compiler/brw_disasm.h"
36 #include "anv_private.h"
37 #include "compiler/brw_nir.h"
38 #include "compiler/brw_nir_rt.h"
39 #include "compiler/intel_nir.h"
40 #include "anv_nir.h"
41 #include "nir/nir_xfb_info.h"
42 #include "spirv/nir_spirv.h"
43 #include "vk_nir_convert_ycbcr.h"
44 #include "vk_nir.h"
45 #include "vk_pipeline.h"
46 #include "vk_render_pass.h"
47 #include "vk_util.h"
48
49 struct lower_set_vtx_and_prim_count_state {
50 nir_variable *primitive_count;
51 };
52
53 static nir_variable *
anv_nir_prim_count_store(nir_builder * b,nir_def * val)54 anv_nir_prim_count_store(nir_builder *b, nir_def *val)
55 {
56 nir_variable *primitive_count =
57 nir_variable_create(b->shader,
58 nir_var_shader_out,
59 glsl_uint_type(),
60 "gl_PrimitiveCountNV");
61 primitive_count->data.location = VARYING_SLOT_PRIMITIVE_COUNT;
62 primitive_count->data.interpolation = INTERP_MODE_NONE;
63
64 nir_def *local_invocation_index = nir_load_local_invocation_index(b);
65
66 nir_def *cmp = nir_ieq_imm(b, local_invocation_index, 0);
67 nir_if *if_stmt = nir_push_if(b, cmp);
68 {
69 nir_deref_instr *prim_count_deref = nir_build_deref_var(b, primitive_count);
70 nir_store_deref(b, prim_count_deref, val, 1);
71 }
72 nir_pop_if(b, if_stmt);
73
74 return primitive_count;
75 }
76
77 static bool
anv_nir_lower_set_vtx_and_prim_count_instr(nir_builder * b,nir_intrinsic_instr * intrin,void * data)78 anv_nir_lower_set_vtx_and_prim_count_instr(nir_builder *b,
79 nir_intrinsic_instr *intrin,
80 void *data)
81 {
82 if (intrin->intrinsic != nir_intrinsic_set_vertex_and_primitive_count)
83 return false;
84
85 /* Detect some cases of invalid primitive count. They might lead to URB
86 * memory corruption, where workgroups overwrite each other output memory.
87 */
88 if (nir_src_is_const(intrin->src[1]) &&
89 nir_src_as_uint(intrin->src[1]) > b->shader->info.mesh.max_primitives_out) {
90 assert(!"number of primitives bigger than max specified");
91 }
92
93 struct lower_set_vtx_and_prim_count_state *state = data;
94 /* this intrinsic should show up only once */
95 assert(state->primitive_count == NULL);
96
97 b->cursor = nir_before_instr(&intrin->instr);
98
99 state->primitive_count = anv_nir_prim_count_store(b, intrin->src[1].ssa);
100
101 nir_instr_remove(&intrin->instr);
102
103 return true;
104 }
105
106 static bool
anv_nir_lower_set_vtx_and_prim_count(nir_shader * nir)107 anv_nir_lower_set_vtx_and_prim_count(nir_shader *nir)
108 {
109 struct lower_set_vtx_and_prim_count_state state = { NULL, };
110
111 nir_shader_intrinsics_pass(nir, anv_nir_lower_set_vtx_and_prim_count_instr,
112 nir_metadata_none,
113 &state);
114
115 /* If we didn't find set_vertex_and_primitive_count, then we have to
116 * insert store of value 0 to primitive_count.
117 */
118 if (state.primitive_count == NULL) {
119 nir_builder b;
120 nir_function_impl *entrypoint = nir_shader_get_entrypoint(nir);
121 b = nir_builder_at(nir_before_impl(entrypoint));
122 nir_def *zero = nir_imm_int(&b, 0);
123 state.primitive_count = anv_nir_prim_count_store(&b, zero);
124 }
125
126 assert(state.primitive_count != NULL);
127 return true;
128 }
129
130 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
131 * we can't do that yet because we don't have the ability to copy nir.
132 */
133 static nir_shader *
anv_shader_stage_to_nir(struct anv_device * device,VkPipelineCreateFlags2KHR pipeline_flags,const VkPipelineShaderStageCreateInfo * stage_info,enum brw_robustness_flags robust_flags,void * mem_ctx)134 anv_shader_stage_to_nir(struct anv_device *device,
135 VkPipelineCreateFlags2KHR pipeline_flags,
136 const VkPipelineShaderStageCreateInfo *stage_info,
137 enum brw_robustness_flags robust_flags,
138 void *mem_ctx)
139 {
140 const struct anv_physical_device *pdevice = device->physical;
141 const struct brw_compiler *compiler = pdevice->compiler;
142 gl_shader_stage stage = vk_to_mesa_shader_stage(stage_info->stage);
143 const nir_shader_compiler_options *nir_options =
144 compiler->nir_options[stage];
145
146 const struct spirv_to_nir_options spirv_options = {
147 .ubo_addr_format = anv_nir_ubo_addr_format(pdevice, robust_flags),
148 .ssbo_addr_format = anv_nir_ssbo_addr_format(pdevice, robust_flags),
149 .phys_ssbo_addr_format = nir_address_format_64bit_global,
150 .push_const_addr_format = nir_address_format_logical,
151
152 /* TODO: Consider changing this to an address format that has the NULL
153 * pointer equals to 0. That might be a better format to play nice
154 * with certain code / code generators.
155 */
156 .shared_addr_format = nir_address_format_32bit_offset,
157
158 .min_ubo_alignment = ANV_UBO_ALIGNMENT,
159 .min_ssbo_alignment = ANV_SSBO_ALIGNMENT,
160 };
161
162 nir_shader *nir;
163 VkResult result =
164 vk_pipeline_shader_stage_to_nir(&device->vk, pipeline_flags, stage_info,
165 &spirv_options, nir_options,
166 mem_ctx, &nir);
167 if (result != VK_SUCCESS)
168 return NULL;
169
170 if (INTEL_DEBUG(intel_debug_flag_for_shader_stage(stage))) {
171 fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
172 gl_shader_stage_name(stage));
173 nir_print_shader(nir, stderr);
174 }
175
176 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
177 nir_shader_get_entrypoint(nir), true, false);
178
179 return nir;
180 }
181
182 static VkResult
anv_pipeline_init(struct anv_pipeline * pipeline,struct anv_device * device,enum anv_pipeline_type type,VkPipelineCreateFlags2KHR flags,const VkAllocationCallbacks * pAllocator)183 anv_pipeline_init(struct anv_pipeline *pipeline,
184 struct anv_device *device,
185 enum anv_pipeline_type type,
186 VkPipelineCreateFlags2KHR flags,
187 const VkAllocationCallbacks *pAllocator)
188 {
189 VkResult result;
190
191 memset(pipeline, 0, sizeof(*pipeline));
192
193 vk_object_base_init(&device->vk, &pipeline->base,
194 VK_OBJECT_TYPE_PIPELINE);
195 pipeline->device = device;
196
197 /* It's the job of the child class to provide actual backing storage for
198 * the batch by setting batch.start, batch.next, and batch.end.
199 */
200 pipeline->batch.alloc = pAllocator ? pAllocator : &device->vk.alloc;
201 pipeline->batch.relocs = &pipeline->batch_relocs;
202 pipeline->batch.status = VK_SUCCESS;
203
204 const bool uses_relocs = device->physical->uses_relocs;
205 result = anv_reloc_list_init(&pipeline->batch_relocs,
206 pipeline->batch.alloc, uses_relocs);
207 if (result != VK_SUCCESS)
208 return result;
209
210 pipeline->mem_ctx = ralloc_context(NULL);
211
212 pipeline->type = type;
213 pipeline->flags = flags;
214
215 util_dynarray_init(&pipeline->executables, pipeline->mem_ctx);
216
217 anv_pipeline_sets_layout_init(&pipeline->layout, device,
218 false /* independent_sets */);
219
220 return VK_SUCCESS;
221 }
222
223 static void
anv_pipeline_init_layout(struct anv_pipeline * pipeline,struct anv_pipeline_layout * pipeline_layout)224 anv_pipeline_init_layout(struct anv_pipeline *pipeline,
225 struct anv_pipeline_layout *pipeline_layout)
226 {
227 if (pipeline_layout) {
228 struct anv_pipeline_sets_layout *layout = &pipeline_layout->sets_layout;
229 for (uint32_t s = 0; s < layout->num_sets; s++) {
230 if (layout->set[s].layout == NULL)
231 continue;
232
233 anv_pipeline_sets_layout_add(&pipeline->layout, s,
234 layout->set[s].layout);
235 }
236 }
237
238 anv_pipeline_sets_layout_hash(&pipeline->layout);
239 assert(!pipeline_layout ||
240 !memcmp(pipeline->layout.sha1,
241 pipeline_layout->sets_layout.sha1,
242 sizeof(pipeline_layout->sets_layout.sha1)));
243 }
244
245 static void
anv_pipeline_finish(struct anv_pipeline * pipeline,struct anv_device * device)246 anv_pipeline_finish(struct anv_pipeline *pipeline,
247 struct anv_device *device)
248 {
249 anv_pipeline_sets_layout_fini(&pipeline->layout);
250 anv_reloc_list_finish(&pipeline->batch_relocs);
251 ralloc_free(pipeline->mem_ctx);
252 vk_object_base_finish(&pipeline->base);
253 }
254
anv_DestroyPipeline(VkDevice _device,VkPipeline _pipeline,const VkAllocationCallbacks * pAllocator)255 void anv_DestroyPipeline(
256 VkDevice _device,
257 VkPipeline _pipeline,
258 const VkAllocationCallbacks* pAllocator)
259 {
260 ANV_FROM_HANDLE(anv_device, device, _device);
261 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
262
263 if (!pipeline)
264 return;
265
266 ANV_RMV(resource_destroy, device, pipeline);
267
268 switch (pipeline->type) {
269 case ANV_PIPELINE_GRAPHICS:
270 case ANV_PIPELINE_GRAPHICS_LIB: {
271 struct anv_graphics_base_pipeline *gfx_pipeline =
272 anv_pipeline_to_graphics_base(pipeline);
273
274 for (unsigned s = 0; s < ARRAY_SIZE(gfx_pipeline->shaders); s++) {
275 if (gfx_pipeline->shaders[s])
276 anv_shader_bin_unref(device, gfx_pipeline->shaders[s]);
277 }
278 break;
279 }
280
281 case ANV_PIPELINE_COMPUTE: {
282 struct anv_compute_pipeline *compute_pipeline =
283 anv_pipeline_to_compute(pipeline);
284
285 if (compute_pipeline->cs)
286 anv_shader_bin_unref(device, compute_pipeline->cs);
287
288 break;
289 }
290
291 case ANV_PIPELINE_RAY_TRACING: {
292 struct anv_ray_tracing_pipeline *rt_pipeline =
293 anv_pipeline_to_ray_tracing(pipeline);
294
295 util_dynarray_foreach(&rt_pipeline->shaders,
296 struct anv_shader_bin *, shader) {
297 anv_shader_bin_unref(device, *shader);
298 }
299 break;
300 }
301
302 default:
303 unreachable("invalid pipeline type");
304 }
305
306 anv_pipeline_finish(pipeline, device);
307 vk_free2(&device->vk.alloc, pAllocator, pipeline);
308 }
309
310 struct anv_pipeline_stage {
311 gl_shader_stage stage;
312
313 VkPipelineCreateFlags2KHR pipeline_flags;
314 struct vk_pipeline_robustness_state rstate;
315
316 /* VkComputePipelineCreateInfo, VkGraphicsPipelineCreateInfo or
317 * VkRayTracingPipelineCreateInfoKHR pNext field
318 */
319 const void *pipeline_pNext;
320 const VkPipelineShaderStageCreateInfo *info;
321
322 unsigned char shader_sha1[20];
323 uint32_t source_hash;
324
325 union brw_any_prog_key key;
326
327 struct {
328 gl_shader_stage stage;
329 unsigned char sha1[20];
330 } cache_key;
331
332 nir_shader *nir;
333
334 struct {
335 nir_shader *nir;
336 struct anv_shader_bin *bin;
337 } imported;
338
339 struct anv_push_descriptor_info push_desc_info;
340
341 enum gl_subgroup_size subgroup_size_type;
342
343 enum brw_robustness_flags robust_flags;
344
345 struct anv_pipeline_bind_map bind_map;
346
347 bool uses_bt_for_push_descs;
348
349 enum anv_dynamic_push_bits dynamic_push_values;
350
351 union brw_any_prog_data prog_data;
352
353 uint32_t num_stats;
354 struct brw_compile_stats stats[3];
355 char *disasm[3];
356
357 VkPipelineCreationFeedback feedback;
358 uint32_t feedback_idx;
359
360 const unsigned *code;
361
362 struct anv_shader_bin *bin;
363 };
364
365 static void
anv_stage_allocate_bind_map_tables(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage,void * mem_ctx)366 anv_stage_allocate_bind_map_tables(struct anv_pipeline *pipeline,
367 struct anv_pipeline_stage *stage,
368 void *mem_ctx)
369 {
370 struct anv_pipeline_binding *surface_bindings =
371 brw_shader_stage_requires_bindless_resources(stage->stage) ? NULL :
372 rzalloc_array(mem_ctx, struct anv_pipeline_binding, 256);
373 struct anv_pipeline_binding *sampler_bindings =
374 brw_shader_stage_requires_bindless_resources(stage->stage) ? NULL :
375 rzalloc_array(mem_ctx, struct anv_pipeline_binding, 256);
376 struct anv_pipeline_embedded_sampler_binding *embedded_sampler_bindings =
377 rzalloc_array(mem_ctx, struct anv_pipeline_embedded_sampler_binding,
378 anv_pipeline_sets_layout_embedded_sampler_count(
379 &pipeline->layout));
380
381 stage->bind_map = (struct anv_pipeline_bind_map) {
382 .surface_to_descriptor = surface_bindings,
383 .sampler_to_descriptor = sampler_bindings,
384 .embedded_sampler_to_binding = embedded_sampler_bindings,
385 };
386 }
387
388 static enum brw_robustness_flags
anv_get_robust_flags(const struct vk_pipeline_robustness_state * rstate)389 anv_get_robust_flags(const struct vk_pipeline_robustness_state *rstate)
390 {
391 return
392 ((rstate->storage_buffers !=
393 VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT) ?
394 BRW_ROBUSTNESS_SSBO : 0) |
395 ((rstate->uniform_buffers !=
396 VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT) ?
397 BRW_ROBUSTNESS_UBO : 0);
398 }
399
400 static void
populate_base_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)401 populate_base_prog_key(struct anv_pipeline_stage *stage,
402 const struct anv_device *device)
403 {
404 stage->key.base.robust_flags = anv_get_robust_flags(&stage->rstate);
405 stage->key.base.limit_trig_input_range =
406 device->physical->instance->limit_trig_input_range;
407 }
408
409 static void
populate_vs_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)410 populate_vs_prog_key(struct anv_pipeline_stage *stage,
411 const struct anv_device *device)
412 {
413 memset(&stage->key, 0, sizeof(stage->key));
414
415 populate_base_prog_key(stage, device);
416 }
417
418 static void
populate_tcs_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device,unsigned input_vertices)419 populate_tcs_prog_key(struct anv_pipeline_stage *stage,
420 const struct anv_device *device,
421 unsigned input_vertices)
422 {
423 memset(&stage->key, 0, sizeof(stage->key));
424
425 populate_base_prog_key(stage, device);
426
427 stage->key.tcs.input_vertices = input_vertices;
428 }
429
430 static void
populate_tes_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)431 populate_tes_prog_key(struct anv_pipeline_stage *stage,
432 const struct anv_device *device)
433 {
434 memset(&stage->key, 0, sizeof(stage->key));
435
436 populate_base_prog_key(stage, device);
437 }
438
439 static void
populate_gs_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)440 populate_gs_prog_key(struct anv_pipeline_stage *stage,
441 const struct anv_device *device)
442 {
443 memset(&stage->key, 0, sizeof(stage->key));
444
445 populate_base_prog_key(stage, device);
446 }
447
448 static bool
pipeline_has_coarse_pixel(const BITSET_WORD * dynamic,const struct vk_multisample_state * ms,const struct vk_fragment_shading_rate_state * fsr)449 pipeline_has_coarse_pixel(const BITSET_WORD *dynamic,
450 const struct vk_multisample_state *ms,
451 const struct vk_fragment_shading_rate_state *fsr)
452 {
453 /* The Vulkan 1.2.199 spec says:
454 *
455 * "If any of the following conditions are met, Cxy' must be set to
456 * {1,1}:
457 *
458 * * If Sample Shading is enabled.
459 * * [...]"
460 *
461 * And "sample shading" is defined as follows:
462 *
463 * "Sample shading is enabled for a graphics pipeline:
464 *
465 * * If the interface of the fragment shader entry point of the
466 * graphics pipeline includes an input variable decorated with
467 * SampleId or SamplePosition. In this case minSampleShadingFactor
468 * takes the value 1.0.
469 *
470 * * Else if the sampleShadingEnable member of the
471 * VkPipelineMultisampleStateCreateInfo structure specified when
472 * creating the graphics pipeline is set to VK_TRUE. In this case
473 * minSampleShadingFactor takes the value of
474 * VkPipelineMultisampleStateCreateInfo::minSampleShading.
475 *
476 * Otherwise, sample shading is considered disabled."
477 *
478 * The first bullet above is handled by the back-end compiler because those
479 * inputs both force per-sample dispatch. The second bullet is handled
480 * here. Note that this sample shading being enabled has nothing to do
481 * with minSampleShading.
482 */
483 if (ms != NULL && ms->sample_shading_enable)
484 return false;
485
486 /* Not dynamic & pipeline has a 1x1 fragment shading rate with no
487 * possibility for element of the pipeline to change the value or fragment
488 * shading rate not specified at all.
489 */
490 if (!BITSET_TEST(dynamic, MESA_VK_DYNAMIC_FSR) &&
491 (fsr == NULL ||
492 (fsr->fragment_size.width <= 1 &&
493 fsr->fragment_size.height <= 1 &&
494 fsr->combiner_ops[0] == VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR &&
495 fsr->combiner_ops[1] == VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR)))
496 return false;
497
498 return true;
499 }
500
501 static void
populate_task_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)502 populate_task_prog_key(struct anv_pipeline_stage *stage,
503 const struct anv_device *device)
504 {
505 memset(&stage->key, 0, sizeof(stage->key));
506
507 populate_base_prog_key(stage, device);
508 }
509
510 static void
populate_mesh_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device,bool compact_mue)511 populate_mesh_prog_key(struct anv_pipeline_stage *stage,
512 const struct anv_device *device,
513 bool compact_mue)
514 {
515 memset(&stage->key, 0, sizeof(stage->key));
516
517 populate_base_prog_key(stage, device);
518
519 stage->key.mesh.compact_mue = compact_mue;
520 }
521
522 static uint32_t
rp_color_mask(const struct vk_render_pass_state * rp)523 rp_color_mask(const struct vk_render_pass_state *rp)
524 {
525 if (rp == NULL || !vk_render_pass_state_has_attachment_info(rp))
526 return ((1u << MAX_RTS) - 1);
527
528 uint32_t color_mask = 0;
529 for (uint32_t i = 0; i < rp->color_attachment_count; i++) {
530 if (rp->color_attachment_formats[i] != VK_FORMAT_UNDEFINED)
531 color_mask |= BITFIELD_BIT(i);
532 }
533
534 return color_mask;
535 }
536
537 static void
populate_wm_prog_key(struct anv_pipeline_stage * stage,const struct anv_graphics_base_pipeline * pipeline,const BITSET_WORD * dynamic,const struct vk_multisample_state * ms,const struct vk_fragment_shading_rate_state * fsr,const struct vk_render_pass_state * rp,const enum brw_sometimes is_mesh)538 populate_wm_prog_key(struct anv_pipeline_stage *stage,
539 const struct anv_graphics_base_pipeline *pipeline,
540 const BITSET_WORD *dynamic,
541 const struct vk_multisample_state *ms,
542 const struct vk_fragment_shading_rate_state *fsr,
543 const struct vk_render_pass_state *rp,
544 const enum brw_sometimes is_mesh)
545 {
546 const struct anv_device *device = pipeline->base.device;
547
548 memset(&stage->key, 0, sizeof(stage->key));
549
550 populate_base_prog_key(stage, device);
551
552 struct brw_wm_prog_key *key = &stage->key.wm;
553
554 /* We set this to 0 here and set to the actual value before we call
555 * brw_compile_fs.
556 */
557 key->input_slots_valid = 0;
558
559 /* XXX Vulkan doesn't appear to specify */
560 key->clamp_fragment_color = false;
561
562 key->ignore_sample_mask_out = false;
563
564 assert(rp == NULL || rp->color_attachment_count <= MAX_RTS);
565 /* Consider all inputs as valid until look at the NIR variables. */
566 key->color_outputs_valid = rp_color_mask(rp);
567 key->nr_color_regions = util_last_bit(key->color_outputs_valid);
568
569 /* To reduce possible shader recompilations we would need to know if
570 * there is a SampleMask output variable to compute if we should emit
571 * code to workaround the issue that hardware disables alpha to coverage
572 * when there is SampleMask output.
573 *
574 * If the pipeline we compile the fragment shader in includes the output
575 * interface, then we can be sure whether alpha_coverage is enabled or not.
576 * If we don't have that output interface, then we have to compile the
577 * shader with some conditionals.
578 */
579 if (ms != NULL) {
580 /* VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00751:
581 *
582 * "If the pipeline is being created with fragment shader state,
583 * pMultisampleState must be a valid pointer to a valid
584 * VkPipelineMultisampleStateCreateInfo structure"
585 *
586 * It's also required for the fragment output interface.
587 */
588 key->multisample_fbo =
589 BITSET_TEST(dynamic, MESA_VK_DYNAMIC_MS_RASTERIZATION_SAMPLES) ?
590 BRW_SOMETIMES :
591 ms->rasterization_samples > 1 ? BRW_ALWAYS : BRW_NEVER;
592 key->persample_interp =
593 BITSET_TEST(dynamic, MESA_VK_DYNAMIC_MS_RASTERIZATION_SAMPLES) ?
594 BRW_SOMETIMES :
595 (ms->sample_shading_enable &&
596 (ms->min_sample_shading * ms->rasterization_samples) > 1) ?
597 BRW_ALWAYS : BRW_NEVER;
598 key->alpha_to_coverage =
599 BITSET_TEST(dynamic, MESA_VK_DYNAMIC_MS_ALPHA_TO_COVERAGE_ENABLE) ?
600 BRW_SOMETIMES :
601 (ms->alpha_to_coverage_enable ? BRW_ALWAYS : BRW_NEVER);
602
603 /* TODO: We should make this dynamic */
604 if (device->physical->instance->sample_mask_out_opengl_behaviour)
605 key->ignore_sample_mask_out = !key->multisample_fbo;
606 } else {
607 /* Consider all inputs as valid until we look at the NIR variables. */
608 key->color_outputs_valid = (1u << MAX_RTS) - 1;
609 key->nr_color_regions = MAX_RTS;
610
611 key->alpha_to_coverage = BRW_SOMETIMES;
612 key->multisample_fbo = BRW_SOMETIMES;
613 key->persample_interp = BRW_SOMETIMES;
614 }
615
616 key->mesh_input = is_mesh;
617
618 /* Vulkan doesn't support fixed-function alpha test */
619 key->alpha_test_replicate_alpha = false;
620
621 key->coarse_pixel =
622 device->vk.enabled_extensions.KHR_fragment_shading_rate &&
623 pipeline_has_coarse_pixel(dynamic, ms, fsr);
624
625 key->null_push_constant_tbimr_workaround =
626 device->info->needs_null_push_constant_tbimr_workaround;
627 }
628
629 static void
populate_cs_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device)630 populate_cs_prog_key(struct anv_pipeline_stage *stage,
631 const struct anv_device *device)
632 {
633 memset(&stage->key, 0, sizeof(stage->key));
634
635 populate_base_prog_key(stage, device);
636 }
637
638 static void
populate_bs_prog_key(struct anv_pipeline_stage * stage,const struct anv_device * device,uint32_t ray_flags)639 populate_bs_prog_key(struct anv_pipeline_stage *stage,
640 const struct anv_device *device,
641 uint32_t ray_flags)
642 {
643 memset(&stage->key, 0, sizeof(stage->key));
644
645 populate_base_prog_key(stage, device);
646
647 stage->key.bs.pipeline_ray_flags = ray_flags;
648 stage->key.bs.pipeline_ray_flags = ray_flags;
649 }
650
651 static void
anv_stage_write_shader_hash(struct anv_pipeline_stage * stage,const struct anv_device * device)652 anv_stage_write_shader_hash(struct anv_pipeline_stage *stage,
653 const struct anv_device *device)
654 {
655 vk_pipeline_robustness_state_fill(&device->vk,
656 &stage->rstate,
657 stage->pipeline_pNext,
658 stage->info->pNext);
659
660 vk_pipeline_hash_shader_stage(stage->pipeline_flags, stage->info,
661 &stage->rstate, stage->shader_sha1);
662
663 stage->robust_flags = anv_get_robust_flags(&stage->rstate);
664
665 /* Use lowest dword of source shader sha1 for shader hash. */
666 stage->source_hash = ((uint32_t*)stage->shader_sha1)[0];
667 }
668
669 static bool
anv_graphics_pipeline_stage_fragment_dynamic(const struct anv_pipeline_stage * stage)670 anv_graphics_pipeline_stage_fragment_dynamic(const struct anv_pipeline_stage *stage)
671 {
672 if (stage->stage != MESA_SHADER_FRAGMENT)
673 return false;
674
675 return stage->key.wm.persample_interp == BRW_SOMETIMES ||
676 stage->key.wm.multisample_fbo == BRW_SOMETIMES ||
677 stage->key.wm.alpha_to_coverage == BRW_SOMETIMES;
678 }
679
680 static void
anv_pipeline_hash_common(struct mesa_sha1 * ctx,const struct anv_pipeline * pipeline)681 anv_pipeline_hash_common(struct mesa_sha1 *ctx,
682 const struct anv_pipeline *pipeline)
683 {
684 struct anv_device *device = pipeline->device;
685
686 _mesa_sha1_update(ctx, pipeline->layout.sha1, sizeof(pipeline->layout.sha1));
687
688 const bool indirect_descriptors = device->physical->indirect_descriptors;
689 _mesa_sha1_update(ctx, &indirect_descriptors, sizeof(indirect_descriptors));
690
691 const bool rba = device->robust_buffer_access;
692 _mesa_sha1_update(ctx, &rba, sizeof(rba));
693
694 const int spilling_rate = device->physical->compiler->spilling_rate;
695 _mesa_sha1_update(ctx, &spilling_rate, sizeof(spilling_rate));
696 }
697
698 static void
anv_pipeline_hash_graphics(struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_stage * stages,uint32_t view_mask,unsigned char * sha1_out)699 anv_pipeline_hash_graphics(struct anv_graphics_base_pipeline *pipeline,
700 struct anv_pipeline_stage *stages,
701 uint32_t view_mask,
702 unsigned char *sha1_out)
703 {
704 const struct anv_device *device = pipeline->base.device;
705 struct mesa_sha1 ctx;
706 _mesa_sha1_init(&ctx);
707
708 anv_pipeline_hash_common(&ctx, &pipeline->base);
709
710 _mesa_sha1_update(&ctx, &view_mask, sizeof(view_mask));
711
712 for (uint32_t s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
713 if (pipeline->base.active_stages & BITFIELD_BIT(s)) {
714 _mesa_sha1_update(&ctx, stages[s].shader_sha1,
715 sizeof(stages[s].shader_sha1));
716 _mesa_sha1_update(&ctx, &stages[s].key, brw_prog_key_size(s));
717 }
718 }
719
720 if (stages[MESA_SHADER_MESH].info || stages[MESA_SHADER_TASK].info) {
721 const uint8_t afs = device->physical->instance->assume_full_subgroups;
722 _mesa_sha1_update(&ctx, &afs, sizeof(afs));
723 }
724
725 _mesa_sha1_final(&ctx, sha1_out);
726 }
727
728 static void
anv_pipeline_hash_compute(struct anv_compute_pipeline * pipeline,struct anv_pipeline_stage * stage,unsigned char * sha1_out)729 anv_pipeline_hash_compute(struct anv_compute_pipeline *pipeline,
730 struct anv_pipeline_stage *stage,
731 unsigned char *sha1_out)
732 {
733 const struct anv_device *device = pipeline->base.device;
734 struct mesa_sha1 ctx;
735 _mesa_sha1_init(&ctx);
736
737 anv_pipeline_hash_common(&ctx, &pipeline->base);
738
739 const uint8_t afs = device->physical->instance->assume_full_subgroups;
740 _mesa_sha1_update(&ctx, &afs, sizeof(afs));
741
742 const bool afswb = device->physical->instance->assume_full_subgroups_with_barrier;
743 _mesa_sha1_update(&ctx, &afswb, sizeof(afswb));
744
745 _mesa_sha1_update(&ctx, stage->shader_sha1,
746 sizeof(stage->shader_sha1));
747 _mesa_sha1_update(&ctx, &stage->key.cs, sizeof(stage->key.cs));
748
749 _mesa_sha1_final(&ctx, sha1_out);
750 }
751
752 static void
anv_pipeline_hash_ray_tracing_shader(struct anv_ray_tracing_pipeline * pipeline,struct anv_pipeline_stage * stage,unsigned char * sha1_out)753 anv_pipeline_hash_ray_tracing_shader(struct anv_ray_tracing_pipeline *pipeline,
754 struct anv_pipeline_stage *stage,
755 unsigned char *sha1_out)
756 {
757 struct mesa_sha1 ctx;
758 _mesa_sha1_init(&ctx);
759
760 anv_pipeline_hash_common(&ctx, &pipeline->base);
761
762 _mesa_sha1_update(&ctx, stage->shader_sha1, sizeof(stage->shader_sha1));
763 _mesa_sha1_update(&ctx, &stage->key, sizeof(stage->key.bs));
764
765 _mesa_sha1_final(&ctx, sha1_out);
766 }
767
768 static void
anv_pipeline_hash_ray_tracing_combined_shader(struct anv_ray_tracing_pipeline * pipeline,struct anv_pipeline_stage * intersection,struct anv_pipeline_stage * any_hit,unsigned char * sha1_out)769 anv_pipeline_hash_ray_tracing_combined_shader(struct anv_ray_tracing_pipeline *pipeline,
770 struct anv_pipeline_stage *intersection,
771 struct anv_pipeline_stage *any_hit,
772 unsigned char *sha1_out)
773 {
774 struct mesa_sha1 ctx;
775 _mesa_sha1_init(&ctx);
776
777 _mesa_sha1_update(&ctx, pipeline->base.layout.sha1,
778 sizeof(pipeline->base.layout.sha1));
779
780 const bool rba = pipeline->base.device->robust_buffer_access;
781 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
782
783 _mesa_sha1_update(&ctx, intersection->shader_sha1, sizeof(intersection->shader_sha1));
784 _mesa_sha1_update(&ctx, &intersection->key, sizeof(intersection->key.bs));
785 _mesa_sha1_update(&ctx, any_hit->shader_sha1, sizeof(any_hit->shader_sha1));
786 _mesa_sha1_update(&ctx, &any_hit->key, sizeof(any_hit->key.bs));
787
788 _mesa_sha1_final(&ctx, sha1_out);
789 }
790
791 static VkResult
anv_pipeline_stage_get_nir(struct anv_pipeline * pipeline,struct vk_pipeline_cache * cache,void * mem_ctx,struct anv_pipeline_stage * stage)792 anv_pipeline_stage_get_nir(struct anv_pipeline *pipeline,
793 struct vk_pipeline_cache *cache,
794 void *mem_ctx,
795 struct anv_pipeline_stage *stage)
796 {
797 const struct brw_compiler *compiler =
798 pipeline->device->physical->compiler;
799 const nir_shader_compiler_options *nir_options =
800 compiler->nir_options[stage->stage];
801
802 stage->nir = anv_device_search_for_nir(pipeline->device, cache,
803 nir_options,
804 stage->shader_sha1,
805 mem_ctx);
806 if (stage->nir) {
807 assert(stage->nir->info.stage == stage->stage);
808 return VK_SUCCESS;
809 }
810
811 /* VkPipelineShaderStageCreateInfo:
812 *
813 * "If a pipeline is not found, pipeline compilation is not possible and
814 * the implementation must fail as specified by
815 * VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT."
816 */
817 if (vk_pipeline_shader_stage_has_identifier(stage->info))
818 return VK_PIPELINE_COMPILE_REQUIRED;
819
820 stage->nir = anv_shader_stage_to_nir(pipeline->device,
821 stage->pipeline_flags, stage->info,
822 stage->key.base.robust_flags, mem_ctx);
823 if (stage->nir) {
824 anv_device_upload_nir(pipeline->device, cache,
825 stage->nir, stage->shader_sha1);
826 return VK_SUCCESS;
827 }
828
829 return vk_errorf(&pipeline->device->vk, VK_ERROR_UNKNOWN,
830 "Unable to load NIR");
831 }
832
833 static const struct vk_ycbcr_conversion_state *
lookup_ycbcr_conversion(const void * _sets_layout,uint32_t set,uint32_t binding,uint32_t array_index)834 lookup_ycbcr_conversion(const void *_sets_layout, uint32_t set,
835 uint32_t binding, uint32_t array_index)
836 {
837 const struct anv_pipeline_sets_layout *sets_layout = _sets_layout;
838
839 assert(set < MAX_SETS);
840 assert(binding < sets_layout->set[set].layout->binding_count);
841 const struct anv_descriptor_set_binding_layout *bind_layout =
842 &sets_layout->set[set].layout->binding[binding];
843
844 if (bind_layout->immutable_samplers == NULL)
845 return NULL;
846
847 array_index = MIN2(array_index, bind_layout->array_size - 1);
848
849 const struct anv_sampler *sampler =
850 bind_layout->immutable_samplers[array_index];
851
852 return sampler && sampler->vk.ycbcr_conversion ?
853 &sampler->vk.ycbcr_conversion->state : NULL;
854 }
855
856 static void
shared_type_info(const struct glsl_type * type,unsigned * size,unsigned * align)857 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
858 {
859 assert(glsl_type_is_vector_or_scalar(type));
860
861 uint32_t comp_size = glsl_type_is_boolean(type)
862 ? 4 : glsl_get_bit_size(type) / 8;
863 unsigned length = glsl_get_vector_elements(type);
864 *size = comp_size * length,
865 *align = comp_size * (length == 3 ? 4 : length);
866 }
867
868 static enum anv_dynamic_push_bits
anv_nir_compute_dynamic_push_bits(nir_shader * shader)869 anv_nir_compute_dynamic_push_bits(nir_shader *shader)
870 {
871 enum anv_dynamic_push_bits ret = 0;
872
873 nir_foreach_function_impl(impl, shader) {
874 nir_foreach_block(block, impl) {
875 nir_foreach_instr(instr, block) {
876 if (instr->type != nir_instr_type_intrinsic)
877 continue;
878
879 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
880 if (intrin->intrinsic != nir_intrinsic_load_push_constant)
881 continue;
882
883 switch (nir_intrinsic_base(intrin)) {
884 case anv_drv_const_offset(gfx.tcs_input_vertices):
885 ret |= ANV_DYNAMIC_PUSH_INPUT_VERTICES;
886 break;
887
888 default:
889 break;
890 }
891 }
892 }
893 }
894
895 return ret;
896 }
897
898 static void
anv_fixup_subgroup_size(struct anv_device * device,struct shader_info * info)899 anv_fixup_subgroup_size(struct anv_device *device, struct shader_info *info)
900 {
901 switch (info->stage) {
902 case MESA_SHADER_COMPUTE:
903 case MESA_SHADER_TASK:
904 case MESA_SHADER_MESH:
905 break;
906 default:
907 return;
908 }
909
910 unsigned local_size = info->workgroup_size[0] *
911 info->workgroup_size[1] *
912 info->workgroup_size[2];
913
914 /* Games don't always request full subgroups when they should,
915 * which can cause bugs, as they may expect bigger size of the
916 * subgroup than we choose for the execution.
917 */
918 if (device->physical->instance->assume_full_subgroups &&
919 info->uses_wide_subgroup_intrinsics &&
920 info->subgroup_size == SUBGROUP_SIZE_API_CONSTANT &&
921 local_size &&
922 local_size % BRW_SUBGROUP_SIZE == 0)
923 info->subgroup_size = SUBGROUP_SIZE_FULL_SUBGROUPS;
924
925 if (device->physical->instance->assume_full_subgroups_with_barrier &&
926 info->stage == MESA_SHADER_COMPUTE &&
927 device->info->verx10 <= 125 &&
928 info->uses_control_barrier &&
929 info->subgroup_size == SUBGROUP_SIZE_VARYING &&
930 local_size &&
931 local_size % BRW_SUBGROUP_SIZE == 0)
932 info->subgroup_size = SUBGROUP_SIZE_FULL_SUBGROUPS;
933
934 /* If the client requests that we dispatch full subgroups but doesn't
935 * allow us to pick a subgroup size, we have to smash it to the API
936 * value of 32. Performance will likely be terrible in this case but
937 * there's nothing we can do about that. The client should have chosen
938 * a size.
939 */
940 if (info->subgroup_size == SUBGROUP_SIZE_FULL_SUBGROUPS)
941 info->subgroup_size =
942 device->physical->instance->assume_full_subgroups != 0 ?
943 device->physical->instance->assume_full_subgroups : BRW_SUBGROUP_SIZE;
944
945 /* Cooperative matrix extension requires that all invocations in a subgroup
946 * be active. As a result, when the application does not request a specific
947 * subgroup size, we must use SIMD32.
948 */
949 if (info->stage == MESA_SHADER_COMPUTE && info->cs.has_cooperative_matrix &&
950 info->subgroup_size < SUBGROUP_SIZE_REQUIRE_8) {
951 info->subgroup_size = BRW_SUBGROUP_SIZE;
952 }
953 }
954
955 /* #define DEBUG_PRINTF_EXAMPLE 0 */
956
957 #if DEBUG_PRINTF_EXAMPLE
958 static bool
print_ubo_load(nir_builder * b,nir_intrinsic_instr * intrin,UNUSED void * cb_data)959 print_ubo_load(nir_builder *b,
960 nir_intrinsic_instr *intrin,
961 UNUSED void *cb_data)
962 {
963 if (intrin->intrinsic != nir_intrinsic_load_ubo)
964 return false;
965
966 b->cursor = nir_before_instr(&intrin->instr);
967 nir_printf_fmt(b, true, 64, "ubo=> pos=%02.2fx%02.2f offset=0x%08x\n",
968 nir_channel(b, nir_load_frag_coord(b), 0),
969 nir_channel(b, nir_load_frag_coord(b), 1),
970 intrin->src[1].ssa);
971
972 b->cursor = nir_after_instr(&intrin->instr);
973 nir_printf_fmt(b, true, 64, "ubo<= pos=%02.2fx%02.2f offset=0x%08x val=0x%08x\n",
974 nir_channel(b, nir_load_frag_coord(b), 0),
975 nir_channel(b, nir_load_frag_coord(b), 1),
976 intrin->src[1].ssa,
977 &intrin->def);
978 return true;
979 }
980 #endif
981
982 static bool
print_tex_handle(nir_builder * b,nir_instr * instr,UNUSED void * cb_data)983 print_tex_handle(nir_builder *b,
984 nir_instr *instr,
985 UNUSED void *cb_data)
986 {
987 if (instr->type != nir_instr_type_tex)
988 return false;
989
990 nir_tex_instr *tex = nir_instr_as_tex(instr);
991
992 nir_src tex_src = {};
993 for (unsigned i = 0; i < tex->num_srcs; i++) {
994 if (tex->src[i].src_type == nir_tex_src_texture_handle)
995 tex_src = tex->src[i].src;
996 }
997
998 b->cursor = nir_before_instr(instr);
999 nir_printf_fmt(b, true, 64, "starting pos=%02.2fx%02.2f tex=0x%08x\n",
1000 nir_channel(b, nir_load_frag_coord(b), 0),
1001 nir_channel(b, nir_load_frag_coord(b), 1),
1002 tex_src.ssa);
1003
1004 b->cursor = nir_after_instr(instr);
1005 nir_printf_fmt(b, true, 64, "done pos=%02.2fx%02.2f tex=0x%08x\n",
1006 nir_channel(b, nir_load_frag_coord(b), 0),
1007 nir_channel(b, nir_load_frag_coord(b), 1),
1008 tex_src.ssa);
1009
1010 return true;
1011 }
1012
1013 static void
anv_pipeline_lower_nir(struct anv_pipeline * pipeline,void * mem_ctx,struct anv_pipeline_stage * stage,struct anv_pipeline_sets_layout * layout,uint32_t view_mask,bool use_primitive_replication)1014 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
1015 void *mem_ctx,
1016 struct anv_pipeline_stage *stage,
1017 struct anv_pipeline_sets_layout *layout,
1018 uint32_t view_mask,
1019 bool use_primitive_replication)
1020 {
1021 const struct anv_physical_device *pdevice = pipeline->device->physical;
1022 const struct brw_compiler *compiler = pdevice->compiler;
1023
1024 struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
1025 nir_shader *nir = stage->nir;
1026
1027 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
1028 NIR_PASS(_, nir, nir_lower_wpos_center);
1029 NIR_PASS(_, nir, nir_lower_input_attachments,
1030 &(nir_input_attachment_options) {
1031 .use_fragcoord_sysval = true,
1032 .use_layer_id_sysval = true,
1033 });
1034 }
1035
1036 if (nir->info.stage == MESA_SHADER_MESH ||
1037 nir->info.stage == MESA_SHADER_TASK) {
1038 nir_lower_compute_system_values_options options = {
1039 .lower_workgroup_id_to_index = true,
1040 /* nir_lower_idiv generates expensive code */
1041 .shortcut_1d_workgroup_id = compiler->devinfo->verx10 >= 125,
1042 };
1043
1044 NIR_PASS(_, nir, nir_lower_compute_system_values, &options);
1045 }
1046
1047 NIR_PASS(_, nir, nir_vk_lower_ycbcr_tex, lookup_ycbcr_conversion, layout);
1048
1049 if (pipeline->type == ANV_PIPELINE_GRAPHICS ||
1050 pipeline->type == ANV_PIPELINE_GRAPHICS_LIB) {
1051 NIR_PASS(_, nir, anv_nir_lower_multiview, view_mask,
1052 use_primitive_replication);
1053 }
1054
1055 if (nir->info.stage == MESA_SHADER_COMPUTE && nir->info.cs.has_cooperative_matrix) {
1056 anv_fixup_subgroup_size(pipeline->device, &nir->info);
1057 NIR_PASS(_, nir, brw_nir_lower_cmat, nir->info.subgroup_size);
1058 NIR_PASS_V(nir, nir_lower_indirect_derefs, nir_var_function_temp, 16);
1059 }
1060
1061 /* The patch control points are delivered through a push constant when
1062 * dynamic.
1063 */
1064 if (nir->info.stage == MESA_SHADER_TESS_CTRL &&
1065 stage->key.tcs.input_vertices == 0)
1066 NIR_PASS(_, nir, anv_nir_lower_load_patch_vertices_in);
1067
1068 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
1069
1070 NIR_PASS(_, nir, brw_nir_lower_storage_image,
1071 &(struct brw_nir_lower_storage_image_opts) {
1072 /* Anv only supports Gfx9+ which has better defined typed read
1073 * behavior. It allows us to only have to care about lowering
1074 * loads.
1075 */
1076 .devinfo = compiler->devinfo,
1077 .lower_loads = true,
1078 });
1079
1080 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_global,
1081 nir_address_format_64bit_global);
1082 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_push_const,
1083 nir_address_format_32bit_offset);
1084
1085 NIR_PASS(_, nir, brw_nir_lower_ray_queries, &pdevice->info);
1086
1087 stage->push_desc_info.used_descriptors =
1088 anv_nir_compute_used_push_descriptors(nir, layout);
1089
1090 struct anv_pipeline_push_map push_map = {};
1091
1092 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
1093 NIR_PASS_V(nir, anv_nir_apply_pipeline_layout,
1094 pdevice, stage->key.base.robust_flags,
1095 layout->independent_sets,
1096 layout, &stage->bind_map, &push_map, mem_ctx);
1097
1098 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ubo,
1099 anv_nir_ubo_addr_format(pdevice, stage->key.base.robust_flags));
1100 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ssbo,
1101 anv_nir_ssbo_addr_format(pdevice, stage->key.base.robust_flags));
1102
1103 /* First run copy-prop to get rid of all of the vec() that address
1104 * calculations often create and then constant-fold so that, when we
1105 * get to anv_nir_lower_ubo_loads, we can detect constant offsets.
1106 */
1107 bool progress;
1108 do {
1109 progress = false;
1110 NIR_PASS(progress, nir, nir_opt_algebraic);
1111 NIR_PASS(progress, nir, nir_copy_prop);
1112 NIR_PASS(progress, nir, nir_opt_constant_folding);
1113 NIR_PASS(progress, nir, nir_opt_dce);
1114 } while (progress);
1115
1116 /* Required for nir_divergence_analysis() which is needed for
1117 * anv_nir_lower_ubo_loads.
1118 */
1119 NIR_PASS(_, nir, nir_convert_to_lcssa, true, true);
1120 nir_divergence_analysis(nir);
1121
1122 NIR_PASS(_, nir, anv_nir_lower_ubo_loads);
1123
1124 NIR_PASS(_, nir, nir_opt_remove_phis);
1125
1126 enum nir_lower_non_uniform_access_type lower_non_uniform_access_types =
1127 nir_lower_non_uniform_texture_access |
1128 nir_lower_non_uniform_image_access |
1129 nir_lower_non_uniform_get_ssbo_size;
1130
1131 /* In practice, most shaders do not have non-uniform-qualified
1132 * accesses (see
1133 * https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/17558#note_1475069)
1134 * thus a cheaper and likely to fail check is run first.
1135 */
1136 if (nir_has_non_uniform_access(nir, lower_non_uniform_access_types)) {
1137 NIR_PASS(_, nir, nir_opt_non_uniform_access);
1138
1139 /* We don't support non-uniform UBOs and non-uniform SSBO access is
1140 * handled naturally by falling back to A64 messages.
1141 */
1142 NIR_PASS(_, nir, nir_lower_non_uniform_access,
1143 &(nir_lower_non_uniform_access_options) {
1144 .types = lower_non_uniform_access_types,
1145 .callback = NULL,
1146 });
1147
1148 NIR_PASS(_, nir, intel_nir_lower_non_uniform_resource_intel);
1149 NIR_PASS(_, nir, intel_nir_cleanup_resource_intel);
1150 NIR_PASS(_, nir, nir_opt_dce);
1151 }
1152
1153 NIR_PASS_V(nir, anv_nir_update_resource_intel_block);
1154
1155 stage->dynamic_push_values = anv_nir_compute_dynamic_push_bits(nir);
1156
1157 NIR_PASS_V(nir, anv_nir_compute_push_layout,
1158 pdevice, stage->key.base.robust_flags,
1159 anv_graphics_pipeline_stage_fragment_dynamic(stage),
1160 prog_data, &stage->bind_map, &push_map,
1161 pipeline->layout.type, mem_ctx);
1162
1163 NIR_PASS_V(nir, anv_nir_lower_resource_intel, pdevice,
1164 pipeline->layout.type);
1165
1166 if (gl_shader_stage_uses_workgroup(nir->info.stage)) {
1167 if (!nir->info.shared_memory_explicit_layout) {
1168 NIR_PASS(_, nir, nir_lower_vars_to_explicit_types,
1169 nir_var_mem_shared, shared_type_info);
1170 }
1171
1172 NIR_PASS(_, nir, nir_lower_explicit_io,
1173 nir_var_mem_shared, nir_address_format_32bit_offset);
1174
1175 if (nir->info.zero_initialize_shared_memory &&
1176 nir->info.shared_size > 0) {
1177 /* The effective Shared Local Memory size is at least 1024 bytes and
1178 * is always rounded to a power of two, so it is OK to align the size
1179 * used by the shader to chunk_size -- which does simplify the logic.
1180 */
1181 const unsigned chunk_size = 16;
1182 const unsigned shared_size = ALIGN(nir->info.shared_size, chunk_size);
1183 assert(shared_size <=
1184 intel_compute_slm_calculate_size(compiler->devinfo->ver, nir->info.shared_size));
1185
1186 NIR_PASS(_, nir, nir_zero_initialize_shared_memory,
1187 shared_size, chunk_size);
1188 }
1189 }
1190
1191 if (gl_shader_stage_is_compute(nir->info.stage) ||
1192 gl_shader_stage_is_mesh(nir->info.stage)) {
1193 NIR_PASS(_, nir, brw_nir_lower_cs_intrinsics, compiler->devinfo,
1194 &stage->prog_data.cs);
1195 }
1196
1197 stage->push_desc_info.used_set_buffer =
1198 anv_nir_loads_push_desc_buffer(nir, layout, &stage->bind_map);
1199 stage->push_desc_info.fully_promoted_ubo_descriptors =
1200 anv_nir_push_desc_ubo_fully_promoted(nir, layout, &stage->bind_map);
1201
1202 #if DEBUG_PRINTF_EXAMPLE
1203 if (stage->stage == MESA_SHADER_FRAGMENT) {
1204 nir_shader_intrinsics_pass(nir, print_ubo_load,
1205 nir_metadata_control_flow,
1206 NULL);
1207 }
1208 #endif
1209
1210 stage->nir = nir;
1211 }
1212
1213 static void
anv_pipeline_link_vs(const struct brw_compiler * compiler,struct anv_pipeline_stage * vs_stage,struct anv_pipeline_stage * next_stage)1214 anv_pipeline_link_vs(const struct brw_compiler *compiler,
1215 struct anv_pipeline_stage *vs_stage,
1216 struct anv_pipeline_stage *next_stage)
1217 {
1218 if (next_stage)
1219 brw_nir_link_shaders(compiler, vs_stage->nir, next_stage->nir);
1220 }
1221
1222 static void
anv_pipeline_compile_vs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_stage * vs_stage,uint32_t view_mask,char ** error_str)1223 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
1224 void *mem_ctx,
1225 struct anv_graphics_base_pipeline *pipeline,
1226 struct anv_pipeline_stage *vs_stage,
1227 uint32_t view_mask,
1228 char **error_str)
1229 {
1230 /* When using Primitive Replication for multiview, each view gets its own
1231 * position slot.
1232 */
1233 uint32_t pos_slots =
1234 (vs_stage->nir->info.per_view_outputs & VARYING_BIT_POS) ?
1235 MAX2(1, util_bitcount(view_mask)) : 1;
1236
1237 /* Only position is allowed to be per-view */
1238 assert(!(vs_stage->nir->info.per_view_outputs & ~VARYING_BIT_POS));
1239
1240 brw_compute_vue_map(compiler->devinfo,
1241 &vs_stage->prog_data.vs.base.vue_map,
1242 vs_stage->nir->info.outputs_written,
1243 vs_stage->nir->info.separate_shader,
1244 pos_slots);
1245
1246 vs_stage->num_stats = 1;
1247
1248 struct brw_compile_vs_params params = {
1249 .base = {
1250 .nir = vs_stage->nir,
1251 .stats = vs_stage->stats,
1252 .log_data = pipeline->base.device,
1253 .mem_ctx = mem_ctx,
1254 .source_hash = vs_stage->source_hash,
1255 },
1256 .key = &vs_stage->key.vs,
1257 .prog_data = &vs_stage->prog_data.vs,
1258 };
1259
1260 vs_stage->code = brw_compile_vs(compiler, ¶ms);
1261 *error_str = params.base.error_str;
1262 }
1263
1264 static void
merge_tess_info(struct shader_info * tes_info,const struct shader_info * tcs_info)1265 merge_tess_info(struct shader_info *tes_info,
1266 const struct shader_info *tcs_info)
1267 {
1268 /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
1269 *
1270 * "PointMode. Controls generation of points rather than triangles
1271 * or lines. This functionality defaults to disabled, and is
1272 * enabled if either shader stage includes the execution mode.
1273 *
1274 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
1275 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
1276 * and OutputVertices, it says:
1277 *
1278 * "One mode must be set in at least one of the tessellation
1279 * shader stages."
1280 *
1281 * So, the fields can be set in either the TCS or TES, but they must
1282 * agree if set in both. Our backend looks at TES, so bitwise-or in
1283 * the values from the TCS.
1284 */
1285 assert(tcs_info->tess.tcs_vertices_out == 0 ||
1286 tes_info->tess.tcs_vertices_out == 0 ||
1287 tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
1288 tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
1289
1290 assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
1291 tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
1292 tcs_info->tess.spacing == tes_info->tess.spacing);
1293 tes_info->tess.spacing |= tcs_info->tess.spacing;
1294
1295 assert(tcs_info->tess._primitive_mode == 0 ||
1296 tes_info->tess._primitive_mode == 0 ||
1297 tcs_info->tess._primitive_mode == tes_info->tess._primitive_mode);
1298 tes_info->tess._primitive_mode |= tcs_info->tess._primitive_mode;
1299 tes_info->tess.ccw |= tcs_info->tess.ccw;
1300 tes_info->tess.point_mode |= tcs_info->tess.point_mode;
1301 }
1302
1303 static void
anv_pipeline_link_tcs(const struct brw_compiler * compiler,struct anv_pipeline_stage * tcs_stage,struct anv_pipeline_stage * tes_stage)1304 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
1305 struct anv_pipeline_stage *tcs_stage,
1306 struct anv_pipeline_stage *tes_stage)
1307 {
1308 assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
1309
1310 brw_nir_link_shaders(compiler, tcs_stage->nir, tes_stage->nir);
1311
1312 nir_lower_patch_vertices(tes_stage->nir,
1313 tcs_stage->nir->info.tess.tcs_vertices_out,
1314 NULL);
1315
1316 /* Copy TCS info into the TES info */
1317 merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
1318
1319 /* Whacking the key after cache lookup is a bit sketchy, but all of
1320 * this comes from the SPIR-V, which is part of the hash used for the
1321 * pipeline cache. So it should be safe.
1322 */
1323 tcs_stage->key.tcs._tes_primitive_mode =
1324 tes_stage->nir->info.tess._primitive_mode;
1325 }
1326
1327 static void
anv_pipeline_compile_tcs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * tcs_stage,struct anv_pipeline_stage * prev_stage,char ** error_str)1328 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
1329 void *mem_ctx,
1330 struct anv_device *device,
1331 struct anv_pipeline_stage *tcs_stage,
1332 struct anv_pipeline_stage *prev_stage,
1333 char **error_str)
1334 {
1335 tcs_stage->key.tcs.outputs_written =
1336 tcs_stage->nir->info.outputs_written;
1337 tcs_stage->key.tcs.patch_outputs_written =
1338 tcs_stage->nir->info.patch_outputs_written;
1339
1340 tcs_stage->num_stats = 1;
1341
1342 struct brw_compile_tcs_params params = {
1343 .base = {
1344 .nir = tcs_stage->nir,
1345 .stats = tcs_stage->stats,
1346 .log_data = device,
1347 .mem_ctx = mem_ctx,
1348 .source_hash = tcs_stage->source_hash,
1349 },
1350 .key = &tcs_stage->key.tcs,
1351 .prog_data = &tcs_stage->prog_data.tcs,
1352 };
1353
1354 tcs_stage->code = brw_compile_tcs(compiler, ¶ms);
1355 *error_str = params.base.error_str;
1356 }
1357
1358 static void
anv_pipeline_link_tes(const struct brw_compiler * compiler,struct anv_pipeline_stage * tes_stage,struct anv_pipeline_stage * next_stage)1359 anv_pipeline_link_tes(const struct brw_compiler *compiler,
1360 struct anv_pipeline_stage *tes_stage,
1361 struct anv_pipeline_stage *next_stage)
1362 {
1363 if (next_stage)
1364 brw_nir_link_shaders(compiler, tes_stage->nir, next_stage->nir);
1365 }
1366
1367 static void
anv_pipeline_compile_tes(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * tes_stage,struct anv_pipeline_stage * tcs_stage,char ** error_str)1368 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
1369 void *mem_ctx,
1370 struct anv_device *device,
1371 struct anv_pipeline_stage *tes_stage,
1372 struct anv_pipeline_stage *tcs_stage,
1373 char **error_str)
1374 {
1375 tes_stage->key.tes.inputs_read =
1376 tcs_stage->nir->info.outputs_written;
1377 tes_stage->key.tes.patch_inputs_read =
1378 tcs_stage->nir->info.patch_outputs_written;
1379
1380 tes_stage->num_stats = 1;
1381
1382 struct brw_compile_tes_params params = {
1383 .base = {
1384 .nir = tes_stage->nir,
1385 .stats = tes_stage->stats,
1386 .log_data = device,
1387 .mem_ctx = mem_ctx,
1388 .source_hash = tes_stage->source_hash,
1389 },
1390 .key = &tes_stage->key.tes,
1391 .prog_data = &tes_stage->prog_data.tes,
1392 .input_vue_map = &tcs_stage->prog_data.tcs.base.vue_map,
1393 };
1394
1395 tes_stage->code = brw_compile_tes(compiler, ¶ms);
1396 *error_str = params.base.error_str;
1397 }
1398
1399 static void
anv_pipeline_link_gs(const struct brw_compiler * compiler,struct anv_pipeline_stage * gs_stage,struct anv_pipeline_stage * next_stage)1400 anv_pipeline_link_gs(const struct brw_compiler *compiler,
1401 struct anv_pipeline_stage *gs_stage,
1402 struct anv_pipeline_stage *next_stage)
1403 {
1404 if (next_stage)
1405 brw_nir_link_shaders(compiler, gs_stage->nir, next_stage->nir);
1406 }
1407
1408 static void
anv_pipeline_compile_gs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * gs_stage,struct anv_pipeline_stage * prev_stage,char ** error_str)1409 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
1410 void *mem_ctx,
1411 struct anv_device *device,
1412 struct anv_pipeline_stage *gs_stage,
1413 struct anv_pipeline_stage *prev_stage,
1414 char **error_str)
1415 {
1416 brw_compute_vue_map(compiler->devinfo,
1417 &gs_stage->prog_data.gs.base.vue_map,
1418 gs_stage->nir->info.outputs_written,
1419 gs_stage->nir->info.separate_shader, 1);
1420
1421 gs_stage->num_stats = 1;
1422
1423 struct brw_compile_gs_params params = {
1424 .base = {
1425 .nir = gs_stage->nir,
1426 .stats = gs_stage->stats,
1427 .log_data = device,
1428 .mem_ctx = mem_ctx,
1429 .source_hash = gs_stage->source_hash,
1430 },
1431 .key = &gs_stage->key.gs,
1432 .prog_data = &gs_stage->prog_data.gs,
1433 };
1434
1435 gs_stage->code = brw_compile_gs(compiler, ¶ms);
1436 *error_str = params.base.error_str;
1437 }
1438
1439 static void
anv_pipeline_link_task(const struct brw_compiler * compiler,struct anv_pipeline_stage * task_stage,struct anv_pipeline_stage * next_stage)1440 anv_pipeline_link_task(const struct brw_compiler *compiler,
1441 struct anv_pipeline_stage *task_stage,
1442 struct anv_pipeline_stage *next_stage)
1443 {
1444 assert(next_stage);
1445 assert(next_stage->stage == MESA_SHADER_MESH);
1446 brw_nir_link_shaders(compiler, task_stage->nir, next_stage->nir);
1447 }
1448
1449 static void
anv_pipeline_compile_task(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * task_stage,char ** error_str)1450 anv_pipeline_compile_task(const struct brw_compiler *compiler,
1451 void *mem_ctx,
1452 struct anv_device *device,
1453 struct anv_pipeline_stage *task_stage,
1454 char **error_str)
1455 {
1456 task_stage->num_stats = 1;
1457
1458 struct brw_compile_task_params params = {
1459 .base = {
1460 .nir = task_stage->nir,
1461 .stats = task_stage->stats,
1462 .log_data = device,
1463 .mem_ctx = mem_ctx,
1464 .source_hash = task_stage->source_hash,
1465 },
1466 .key = &task_stage->key.task,
1467 .prog_data = &task_stage->prog_data.task,
1468 };
1469
1470 task_stage->code = brw_compile_task(compiler, ¶ms);
1471 *error_str = params.base.error_str;
1472 }
1473
1474 static void
anv_pipeline_link_mesh(const struct brw_compiler * compiler,struct anv_pipeline_stage * mesh_stage,struct anv_pipeline_stage * next_stage)1475 anv_pipeline_link_mesh(const struct brw_compiler *compiler,
1476 struct anv_pipeline_stage *mesh_stage,
1477 struct anv_pipeline_stage *next_stage)
1478 {
1479 if (next_stage) {
1480 brw_nir_link_shaders(compiler, mesh_stage->nir, next_stage->nir);
1481 }
1482 }
1483
1484 static void
anv_pipeline_compile_mesh(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * mesh_stage,struct anv_pipeline_stage * prev_stage,char ** error_str)1485 anv_pipeline_compile_mesh(const struct brw_compiler *compiler,
1486 void *mem_ctx,
1487 struct anv_device *device,
1488 struct anv_pipeline_stage *mesh_stage,
1489 struct anv_pipeline_stage *prev_stage,
1490 char **error_str)
1491 {
1492 mesh_stage->num_stats = 1;
1493
1494 struct brw_compile_mesh_params params = {
1495 .base = {
1496 .nir = mesh_stage->nir,
1497 .stats = mesh_stage->stats,
1498 .log_data = device,
1499 .mem_ctx = mem_ctx,
1500 .source_hash = mesh_stage->source_hash,
1501 },
1502 .key = &mesh_stage->key.mesh,
1503 .prog_data = &mesh_stage->prog_data.mesh,
1504 };
1505
1506 if (prev_stage) {
1507 assert(prev_stage->stage == MESA_SHADER_TASK);
1508 params.tue_map = &prev_stage->prog_data.task.map;
1509 }
1510
1511 mesh_stage->code = brw_compile_mesh(compiler, ¶ms);
1512 *error_str = params.base.error_str;
1513 }
1514
1515 static void
anv_pipeline_link_fs(const struct brw_compiler * compiler,struct anv_pipeline_stage * stage,const struct vk_render_pass_state * rp)1516 anv_pipeline_link_fs(const struct brw_compiler *compiler,
1517 struct anv_pipeline_stage *stage,
1518 const struct vk_render_pass_state *rp)
1519 {
1520 /* Initially the valid outputs value is set to all possible render targets
1521 * valid (see populate_wm_prog_key()), before we look at the shader
1522 * variables. Here we look at the output variables of the shader an compute
1523 * a correct number of render target outputs.
1524 */
1525 stage->key.wm.color_outputs_valid = 0;
1526 nir_foreach_shader_out_variable_safe(var, stage->nir) {
1527 if (var->data.location < FRAG_RESULT_DATA0)
1528 continue;
1529
1530 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
1531 const unsigned array_len =
1532 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
1533 assert(rt + array_len <= MAX_RTS);
1534
1535 stage->key.wm.color_outputs_valid |= BITFIELD_RANGE(rt, array_len);
1536 }
1537 stage->key.wm.color_outputs_valid &= rp_color_mask(rp);
1538 stage->key.wm.nr_color_regions =
1539 util_last_bit(stage->key.wm.color_outputs_valid);
1540
1541 unsigned num_rt_bindings;
1542 struct anv_pipeline_binding rt_bindings[MAX_RTS];
1543 if (stage->key.wm.nr_color_regions > 0) {
1544 assert(stage->key.wm.nr_color_regions <= MAX_RTS);
1545 for (unsigned rt = 0; rt < stage->key.wm.nr_color_regions; rt++) {
1546 if (stage->key.wm.color_outputs_valid & BITFIELD_BIT(rt)) {
1547 rt_bindings[rt] = (struct anv_pipeline_binding) {
1548 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
1549 .index = rt,
1550 .binding = UINT32_MAX,
1551
1552 };
1553 } else {
1554 /* Setup a null render target */
1555 rt_bindings[rt] = (struct anv_pipeline_binding) {
1556 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
1557 .index = UINT32_MAX,
1558 .binding = UINT32_MAX,
1559 };
1560 }
1561 }
1562 num_rt_bindings = stage->key.wm.nr_color_regions;
1563 } else {
1564 /* Setup a null render target */
1565 rt_bindings[0] = (struct anv_pipeline_binding) {
1566 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
1567 .index = UINT32_MAX,
1568 };
1569 num_rt_bindings = 1;
1570 }
1571
1572 assert(num_rt_bindings <= MAX_RTS);
1573 assert(stage->bind_map.surface_count == 0);
1574 typed_memcpy(stage->bind_map.surface_to_descriptor,
1575 rt_bindings, num_rt_bindings);
1576 stage->bind_map.surface_count += num_rt_bindings;
1577 }
1578
1579 static void
anv_pipeline_compile_fs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * fs_stage,struct anv_pipeline_stage * prev_stage,struct anv_graphics_base_pipeline * pipeline,uint32_t view_mask,bool use_primitive_replication,char ** error_str)1580 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
1581 void *mem_ctx,
1582 struct anv_device *device,
1583 struct anv_pipeline_stage *fs_stage,
1584 struct anv_pipeline_stage *prev_stage,
1585 struct anv_graphics_base_pipeline *pipeline,
1586 uint32_t view_mask,
1587 bool use_primitive_replication,
1588 char **error_str)
1589 {
1590 /* When using Primitive Replication for multiview, each view gets its own
1591 * position slot.
1592 */
1593 uint32_t pos_slots = use_primitive_replication ?
1594 MAX2(1, util_bitcount(view_mask)) : 1;
1595
1596 /* If we have a previous stage we can use that to deduce valid slots.
1597 * Otherwise, rely on inputs of the input shader.
1598 */
1599 if (prev_stage) {
1600 fs_stage->key.wm.input_slots_valid =
1601 prev_stage->prog_data.vue.vue_map.slots_valid;
1602 } else {
1603 struct intel_vue_map prev_vue_map;
1604 brw_compute_vue_map(compiler->devinfo,
1605 &prev_vue_map,
1606 fs_stage->nir->info.inputs_read,
1607 fs_stage->nir->info.separate_shader,
1608 pos_slots);
1609
1610 fs_stage->key.wm.input_slots_valid = prev_vue_map.slots_valid;
1611 }
1612
1613 struct brw_compile_fs_params params = {
1614 .base = {
1615 .nir = fs_stage->nir,
1616 .stats = fs_stage->stats,
1617 .log_data = device,
1618 .mem_ctx = mem_ctx,
1619 .source_hash = fs_stage->source_hash,
1620 },
1621 .key = &fs_stage->key.wm,
1622 .prog_data = &fs_stage->prog_data.wm,
1623
1624 .allow_spilling = true,
1625 .max_polygons = UCHAR_MAX,
1626 };
1627
1628 if (prev_stage && prev_stage->stage == MESA_SHADER_MESH) {
1629 params.mue_map = &prev_stage->prog_data.mesh.map;
1630 /* TODO(mesh): Slots valid, do we even use/rely on it? */
1631 }
1632
1633 fs_stage->code = brw_compile_fs(compiler, ¶ms);
1634 *error_str = params.base.error_str;
1635
1636 fs_stage->num_stats = (uint32_t)!!fs_stage->prog_data.wm.dispatch_multi +
1637 (uint32_t)fs_stage->prog_data.wm.dispatch_8 +
1638 (uint32_t)fs_stage->prog_data.wm.dispatch_16 +
1639 (uint32_t)fs_stage->prog_data.wm.dispatch_32;
1640 assert(fs_stage->num_stats <= ARRAY_SIZE(fs_stage->stats));
1641 }
1642
1643 static void
anv_pipeline_add_executable(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage,struct brw_compile_stats * stats,uint32_t code_offset)1644 anv_pipeline_add_executable(struct anv_pipeline *pipeline,
1645 struct anv_pipeline_stage *stage,
1646 struct brw_compile_stats *stats,
1647 uint32_t code_offset)
1648 {
1649 char *nir = NULL;
1650 if (stage->nir &&
1651 (pipeline->flags &
1652 VK_PIPELINE_CREATE_2_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1653 nir = nir_shader_as_str(stage->nir, pipeline->mem_ctx);
1654 }
1655
1656 char *disasm = NULL;
1657 if (stage->code &&
1658 (pipeline->flags &
1659 VK_PIPELINE_CREATE_2_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1660 char *stream_data = NULL;
1661 size_t stream_size = 0;
1662 FILE *stream = open_memstream(&stream_data, &stream_size);
1663
1664 uint32_t push_size = 0;
1665 for (unsigned i = 0; i < 4; i++)
1666 push_size += stage->bind_map.push_ranges[i].length;
1667 if (push_size > 0) {
1668 fprintf(stream, "Push constant ranges:\n");
1669 for (unsigned i = 0; i < 4; i++) {
1670 if (stage->bind_map.push_ranges[i].length == 0)
1671 continue;
1672
1673 fprintf(stream, " RANGE%d (%dB): ", i,
1674 stage->bind_map.push_ranges[i].length * 32);
1675
1676 switch (stage->bind_map.push_ranges[i].set) {
1677 case ANV_DESCRIPTOR_SET_NULL:
1678 fprintf(stream, "NULL");
1679 break;
1680
1681 case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS:
1682 fprintf(stream, "Vulkan push constants and API params");
1683 break;
1684
1685 case ANV_DESCRIPTOR_SET_DESCRIPTORS_BUFFER:
1686 fprintf(stream, "Descriptor buffer (desc buffer) for set %d (start=%dB)",
1687 stage->bind_map.push_ranges[i].index,
1688 stage->bind_map.push_ranges[i].start * 32);
1689 break;
1690
1691 case ANV_DESCRIPTOR_SET_DESCRIPTORS:
1692 fprintf(stream, "Descriptor buffer for set %d (start=%dB)",
1693 stage->bind_map.push_ranges[i].index,
1694 stage->bind_map.push_ranges[i].start * 32);
1695 break;
1696
1697 case ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS:
1698 unreachable("gl_NumWorkgroups is never pushed");
1699
1700 case ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS:
1701 unreachable("Color attachments can't be pushed");
1702
1703 default:
1704 fprintf(stream, "UBO (set=%d binding=%d start=%dB)",
1705 stage->bind_map.push_ranges[i].set,
1706 stage->bind_map.push_ranges[i].index,
1707 stage->bind_map.push_ranges[i].start * 32);
1708 break;
1709 }
1710 fprintf(stream, "\n");
1711 }
1712 fprintf(stream, "\n");
1713 }
1714
1715 /* Creating this is far cheaper than it looks. It's perfectly fine to
1716 * do it for every binary.
1717 */
1718 brw_disassemble_with_errors(&pipeline->device->physical->compiler->isa,
1719 stage->code, code_offset, stream);
1720
1721 fclose(stream);
1722
1723 /* Copy it to a ralloc'd thing */
1724 disasm = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1725 memcpy(disasm, stream_data, stream_size);
1726 disasm[stream_size] = 0;
1727
1728 free(stream_data);
1729 }
1730
1731 const struct anv_pipeline_executable exe = {
1732 .stage = stage->stage,
1733 .stats = *stats,
1734 .nir = nir,
1735 .disasm = disasm,
1736 };
1737 util_dynarray_append(&pipeline->executables,
1738 struct anv_pipeline_executable, exe);
1739 }
1740
1741 static void
anv_pipeline_add_executables(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage)1742 anv_pipeline_add_executables(struct anv_pipeline *pipeline,
1743 struct anv_pipeline_stage *stage)
1744 {
1745 if (stage->stage == MESA_SHADER_FRAGMENT) {
1746 /* We pull the prog data and stats out of the anv_shader_bin because
1747 * the anv_pipeline_stage may not be fully populated if we successfully
1748 * looked up the shader in a cache.
1749 */
1750 const struct brw_wm_prog_data *wm_prog_data =
1751 (const struct brw_wm_prog_data *)stage->bin->prog_data;
1752 struct brw_compile_stats *stats = stage->bin->stats;
1753
1754 if (wm_prog_data->dispatch_8 ||
1755 wm_prog_data->dispatch_multi) {
1756 anv_pipeline_add_executable(pipeline, stage, stats++, 0);
1757 }
1758
1759 if (wm_prog_data->dispatch_16) {
1760 anv_pipeline_add_executable(pipeline, stage, stats++,
1761 wm_prog_data->prog_offset_16);
1762 }
1763
1764 if (wm_prog_data->dispatch_32) {
1765 anv_pipeline_add_executable(pipeline, stage, stats++,
1766 wm_prog_data->prog_offset_32);
1767 }
1768 } else {
1769 anv_pipeline_add_executable(pipeline, stage, stage->bin->stats, 0);
1770 }
1771 }
1772
1773 static void
anv_pipeline_account_shader(struct anv_pipeline * pipeline,struct anv_shader_bin * shader)1774 anv_pipeline_account_shader(struct anv_pipeline *pipeline,
1775 struct anv_shader_bin *shader)
1776 {
1777 pipeline->scratch_size = MAX2(pipeline->scratch_size,
1778 shader->prog_data->total_scratch);
1779
1780 pipeline->ray_queries = MAX2(pipeline->ray_queries,
1781 shader->prog_data->ray_queries);
1782
1783 if (shader->push_desc_info.used_set_buffer) {
1784 pipeline->use_push_descriptor_buffer |=
1785 mesa_to_vk_shader_stage(shader->stage);
1786 }
1787 if (shader->push_desc_info.used_descriptors &
1788 ~shader->push_desc_info.fully_promoted_ubo_descriptors)
1789 pipeline->use_push_descriptor |= mesa_to_vk_shader_stage(shader->stage);
1790 }
1791
1792 /* This function return true if a shader should not be looked at because of
1793 * fast linking. Instead we should use the shader binaries provided by
1794 * libraries.
1795 */
1796 static bool
anv_graphics_pipeline_skip_shader_compile(struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_stage * stages,bool link_optimize,gl_shader_stage stage)1797 anv_graphics_pipeline_skip_shader_compile(struct anv_graphics_base_pipeline *pipeline,
1798 struct anv_pipeline_stage *stages,
1799 bool link_optimize,
1800 gl_shader_stage stage)
1801 {
1802 /* Always skip non active stages */
1803 if (!anv_pipeline_base_has_stage(pipeline, stage))
1804 return true;
1805
1806 /* When link optimizing, consider all stages */
1807 if (link_optimize)
1808 return false;
1809
1810 /* Otherwise check if the stage was specified through
1811 * VkGraphicsPipelineCreateInfo
1812 */
1813 assert(stages[stage].info != NULL || stages[stage].imported.bin != NULL);
1814 return stages[stage].info == NULL;
1815 }
1816
1817 static void
anv_graphics_pipeline_init_keys(struct anv_graphics_base_pipeline * pipeline,const struct vk_graphics_pipeline_state * state,struct anv_pipeline_stage * stages)1818 anv_graphics_pipeline_init_keys(struct anv_graphics_base_pipeline *pipeline,
1819 const struct vk_graphics_pipeline_state *state,
1820 struct anv_pipeline_stage *stages)
1821 {
1822 for (uint32_t s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
1823 if (!anv_pipeline_base_has_stage(pipeline, s))
1824 continue;
1825
1826 int64_t stage_start = os_time_get_nano();
1827
1828 const struct anv_device *device = pipeline->base.device;
1829 switch (stages[s].stage) {
1830 case MESA_SHADER_VERTEX:
1831 populate_vs_prog_key(&stages[s], device);
1832 break;
1833 case MESA_SHADER_TESS_CTRL:
1834 populate_tcs_prog_key(&stages[s],
1835 device,
1836 BITSET_TEST(state->dynamic,
1837 MESA_VK_DYNAMIC_TS_PATCH_CONTROL_POINTS) ?
1838 0 : state->ts->patch_control_points);
1839 break;
1840 case MESA_SHADER_TESS_EVAL:
1841 populate_tes_prog_key(&stages[s], device);
1842 break;
1843 case MESA_SHADER_GEOMETRY:
1844 populate_gs_prog_key(&stages[s], device);
1845 break;
1846 case MESA_SHADER_FRAGMENT: {
1847 /* Assume rasterization enabled in any of the following case :
1848 *
1849 * - We're a pipeline library without pre-rasterization information
1850 *
1851 * - Rasterization is not disabled in the non dynamic state
1852 *
1853 * - Rasterization disable is dynamic
1854 */
1855 const bool raster_enabled =
1856 state->rs == NULL ||
1857 !state->rs->rasterizer_discard_enable ||
1858 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_RS_RASTERIZER_DISCARD_ENABLE);
1859 enum brw_sometimes is_mesh = BRW_NEVER;
1860 if (device->vk.enabled_extensions.EXT_mesh_shader) {
1861 if (anv_pipeline_base_has_stage(pipeline, MESA_SHADER_VERTEX))
1862 is_mesh = BRW_NEVER;
1863 else if (anv_pipeline_base_has_stage(pipeline, MESA_SHADER_MESH))
1864 is_mesh = BRW_ALWAYS;
1865 else {
1866 assert(pipeline->base.type == ANV_PIPELINE_GRAPHICS_LIB);
1867 is_mesh = BRW_SOMETIMES;
1868 }
1869 }
1870 populate_wm_prog_key(&stages[s],
1871 pipeline,
1872 state->dynamic,
1873 raster_enabled ? state->ms : NULL,
1874 state->fsr, state->rp, is_mesh);
1875 break;
1876 }
1877
1878 case MESA_SHADER_TASK:
1879 populate_task_prog_key(&stages[s], device);
1880 break;
1881
1882 case MESA_SHADER_MESH: {
1883 const bool compact_mue =
1884 !(pipeline->base.type == ANV_PIPELINE_GRAPHICS_LIB &&
1885 !anv_pipeline_base_has_stage(pipeline, MESA_SHADER_FRAGMENT));
1886 populate_mesh_prog_key(&stages[s], device, compact_mue);
1887 break;
1888 }
1889
1890 default:
1891 unreachable("Invalid graphics shader stage");
1892 }
1893
1894 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1895 stages[s].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT;
1896 }
1897 }
1898
1899 static void
anv_graphics_lib_retain_shaders(struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_stage * stages,bool will_compile)1900 anv_graphics_lib_retain_shaders(struct anv_graphics_base_pipeline *pipeline,
1901 struct anv_pipeline_stage *stages,
1902 bool will_compile)
1903 {
1904 /* There isn't much point in retaining NIR shaders on final pipelines. */
1905 assert(pipeline->base.type == ANV_PIPELINE_GRAPHICS_LIB);
1906
1907 struct anv_graphics_lib_pipeline *lib = (struct anv_graphics_lib_pipeline *) pipeline;
1908
1909 for (int s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
1910 if (!anv_pipeline_base_has_stage(pipeline, s))
1911 continue;
1912
1913 memcpy(lib->retained_shaders[s].shader_sha1, stages[s].shader_sha1,
1914 sizeof(stages[s].shader_sha1));
1915
1916 lib->retained_shaders[s].subgroup_size_type = stages[s].subgroup_size_type;
1917
1918 nir_shader *nir = stages[s].nir != NULL ? stages[s].nir : stages[s].imported.nir;
1919 assert(nir != NULL);
1920
1921 if (!will_compile) {
1922 lib->retained_shaders[s].nir = nir;
1923 } else {
1924 lib->retained_shaders[s].nir =
1925 nir_shader_clone(pipeline->base.mem_ctx, nir);
1926 }
1927 }
1928 }
1929
1930 static bool
anv_graphics_pipeline_load_cached_shaders(struct anv_graphics_base_pipeline * pipeline,struct vk_pipeline_cache * cache,struct anv_pipeline_stage * stages,bool link_optimize,VkPipelineCreationFeedback * pipeline_feedback)1931 anv_graphics_pipeline_load_cached_shaders(struct anv_graphics_base_pipeline *pipeline,
1932 struct vk_pipeline_cache *cache,
1933 struct anv_pipeline_stage *stages,
1934 bool link_optimize,
1935 VkPipelineCreationFeedback *pipeline_feedback)
1936 {
1937 struct anv_device *device = pipeline->base.device;
1938 unsigned cache_hits = 0, found = 0, imported = 0;
1939
1940 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
1941 if (!anv_pipeline_base_has_stage(pipeline, s))
1942 continue;
1943
1944 int64_t stage_start = os_time_get_nano();
1945
1946 bool cache_hit;
1947 stages[s].bin =
1948 anv_device_search_for_kernel(device, cache, &stages[s].cache_key,
1949 sizeof(stages[s].cache_key), &cache_hit);
1950 if (stages[s].bin) {
1951 found++;
1952 pipeline->shaders[s] = stages[s].bin;
1953 }
1954
1955 if (cache_hit) {
1956 cache_hits++;
1957 stages[s].feedback.flags |=
1958 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
1959 }
1960 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1961 }
1962
1963 /* When not link optimizing, lookup the missing shader in the imported
1964 * libraries.
1965 */
1966 if (!link_optimize) {
1967 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
1968 if (!anv_pipeline_base_has_stage(pipeline, s))
1969 continue;
1970
1971 if (pipeline->shaders[s] != NULL)
1972 continue;
1973
1974 if (stages[s].imported.bin == NULL)
1975 continue;
1976
1977 stages[s].bin = stages[s].imported.bin;
1978 pipeline->shaders[s] = anv_shader_bin_ref(stages[s].imported.bin);
1979 pipeline->source_hashes[s] = stages[s].source_hash;
1980 imported++;
1981 }
1982 }
1983
1984 if ((found + imported) == __builtin_popcount(pipeline->base.active_stages)) {
1985 if (cache_hits == found && found != 0) {
1986 pipeline_feedback->flags |=
1987 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
1988 }
1989 /* We found all our shaders in the cache. We're done. */
1990 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
1991 if (pipeline->shaders[s] == NULL)
1992 continue;
1993
1994 /* Only add the executables when we're not importing or doing link
1995 * optimizations. The imported executables are added earlier. Link
1996 * optimization can produce different binaries.
1997 */
1998 if (stages[s].imported.bin == NULL || link_optimize)
1999 anv_pipeline_add_executables(&pipeline->base, &stages[s]);
2000 pipeline->source_hashes[s] = stages[s].source_hash;
2001 }
2002 return true;
2003 } else if (found > 0) {
2004 /* We found some but not all of our shaders. This shouldn't happen most
2005 * of the time but it can if we have a partially populated pipeline
2006 * cache.
2007 */
2008 assert(found < __builtin_popcount(pipeline->base.active_stages));
2009
2010 /* With GPL, this might well happen if the app does an optimized
2011 * link.
2012 */
2013 if (!pipeline->base.device->vk.enabled_extensions.EXT_graphics_pipeline_library) {
2014 vk_perf(VK_LOG_OBJS(cache ? &cache->base :
2015 &pipeline->base.device->vk.base),
2016 "Found a partial pipeline in the cache. This is "
2017 "most likely caused by an incomplete pipeline cache "
2018 "import or export");
2019 }
2020
2021 /* We're going to have to recompile anyway, so just throw away our
2022 * references to the shaders in the cache. We'll get them out of the
2023 * cache again as part of the compilation process.
2024 */
2025 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
2026 stages[s].feedback.flags = 0;
2027 if (pipeline->shaders[s]) {
2028 anv_shader_bin_unref(device, pipeline->shaders[s]);
2029 pipeline->shaders[s] = NULL;
2030 }
2031 }
2032 }
2033
2034 return false;
2035 }
2036
2037 static const gl_shader_stage graphics_shader_order[] = {
2038 MESA_SHADER_VERTEX,
2039 MESA_SHADER_TESS_CTRL,
2040 MESA_SHADER_TESS_EVAL,
2041 MESA_SHADER_GEOMETRY,
2042
2043 MESA_SHADER_TASK,
2044 MESA_SHADER_MESH,
2045
2046 MESA_SHADER_FRAGMENT,
2047 };
2048
2049 /* This function loads NIR only for stages specified in
2050 * VkGraphicsPipelineCreateInfo::pStages[]
2051 */
2052 static VkResult
anv_graphics_pipeline_load_nir(struct anv_graphics_base_pipeline * pipeline,struct vk_pipeline_cache * cache,struct anv_pipeline_stage * stages,void * mem_ctx,bool need_clone)2053 anv_graphics_pipeline_load_nir(struct anv_graphics_base_pipeline *pipeline,
2054 struct vk_pipeline_cache *cache,
2055 struct anv_pipeline_stage *stages,
2056 void *mem_ctx,
2057 bool need_clone)
2058 {
2059 for (unsigned s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
2060 if (!anv_pipeline_base_has_stage(pipeline, s))
2061 continue;
2062
2063 int64_t stage_start = os_time_get_nano();
2064
2065 assert(stages[s].stage == s);
2066
2067 /* Only use the create NIR from the pStages[] element if we don't have
2068 * an imported library for the same stage.
2069 */
2070 if (stages[s].imported.bin == NULL) {
2071 VkResult result = anv_pipeline_stage_get_nir(&pipeline->base, cache,
2072 mem_ctx, &stages[s]);
2073 if (result != VK_SUCCESS)
2074 return result;
2075 } else {
2076 stages[s].nir = need_clone ?
2077 nir_shader_clone(mem_ctx, stages[s].imported.nir) :
2078 stages[s].imported.nir;
2079 }
2080
2081 stages[s].feedback.duration += os_time_get_nano() - stage_start;
2082 }
2083
2084 return VK_SUCCESS;
2085 }
2086
2087 static void
anv_pipeline_nir_preprocess(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage)2088 anv_pipeline_nir_preprocess(struct anv_pipeline *pipeline,
2089 struct anv_pipeline_stage *stage)
2090 {
2091 struct anv_device *device = pipeline->device;
2092 const struct brw_compiler *compiler = device->physical->compiler;
2093
2094 const struct nir_lower_sysvals_to_varyings_options sysvals_to_varyings = {
2095 .point_coord = true,
2096 };
2097 NIR_PASS(_, stage->nir, nir_lower_sysvals_to_varyings, &sysvals_to_varyings);
2098
2099 const nir_opt_access_options opt_access_options = {
2100 .is_vulkan = true,
2101 };
2102 NIR_PASS(_, stage->nir, nir_opt_access, &opt_access_options);
2103
2104 /* Vulkan uses the separate-shader linking model */
2105 stage->nir->info.separate_shader = true;
2106
2107 struct brw_nir_compiler_opts opts = {
2108 .softfp64 = device->fp64_nir,
2109 /* Assume robustness with EXT_pipeline_robustness because this can be
2110 * turned on/off per pipeline and we have no visibility on this here.
2111 */
2112 .robust_image_access = device->vk.enabled_features.robustImageAccess ||
2113 device->vk.enabled_features.robustImageAccess2 ||
2114 device->vk.enabled_extensions.EXT_pipeline_robustness,
2115 .input_vertices = stage->nir->info.stage == MESA_SHADER_TESS_CTRL ?
2116 stage->key.tcs.input_vertices : 0,
2117 };
2118 brw_preprocess_nir(compiler, stage->nir, &opts);
2119
2120 if (stage->nir->info.stage == MESA_SHADER_MESH) {
2121 NIR_PASS(_, stage->nir, anv_nir_lower_set_vtx_and_prim_count);
2122 NIR_PASS(_, stage->nir, nir_opt_dce);
2123 NIR_PASS(_, stage->nir, nir_remove_dead_variables, nir_var_shader_out, NULL);
2124 }
2125
2126 NIR_PASS(_, stage->nir, nir_opt_barrier_modes);
2127
2128 nir_shader_gather_info(stage->nir, nir_shader_get_entrypoint(stage->nir));
2129 }
2130
2131 static void
anv_fill_pipeline_creation_feedback(const struct anv_graphics_base_pipeline * pipeline,VkPipelineCreationFeedback * pipeline_feedback,const VkGraphicsPipelineCreateInfo * info,struct anv_pipeline_stage * stages)2132 anv_fill_pipeline_creation_feedback(const struct anv_graphics_base_pipeline *pipeline,
2133 VkPipelineCreationFeedback *pipeline_feedback,
2134 const VkGraphicsPipelineCreateInfo *info,
2135 struct anv_pipeline_stage *stages)
2136 {
2137 const VkPipelineCreationFeedbackCreateInfo *create_feedback =
2138 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO);
2139 if (create_feedback) {
2140 *create_feedback->pPipelineCreationFeedback = *pipeline_feedback;
2141
2142 /* VkPipelineCreationFeedbackCreateInfo:
2143 *
2144 * "An implementation must set or clear the
2145 * VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT in
2146 * VkPipelineCreationFeedback::flags for pPipelineCreationFeedback
2147 * and every element of pPipelineStageCreationFeedbacks."
2148 *
2149 */
2150 for (uint32_t i = 0; i < create_feedback->pipelineStageCreationFeedbackCount; i++) {
2151 create_feedback->pPipelineStageCreationFeedbacks[i].flags &=
2152 ~VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT;
2153 }
2154 /* This part is not really specified in the Vulkan spec at the moment.
2155 * We're kind of guessing what the CTS wants. We might need to update
2156 * when https://gitlab.khronos.org/vulkan/vulkan/-/issues/3115 is
2157 * clarified.
2158 */
2159 for (uint32_t s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
2160 if (!anv_pipeline_base_has_stage(pipeline, s))
2161 continue;
2162
2163 if (stages[s].feedback_idx < create_feedback->pipelineStageCreationFeedbackCount) {
2164 create_feedback->pPipelineStageCreationFeedbacks[
2165 stages[s].feedback_idx] = stages[s].feedback;
2166 }
2167 }
2168 }
2169 }
2170
2171 static uint32_t
anv_graphics_pipeline_imported_shader_count(struct anv_pipeline_stage * stages)2172 anv_graphics_pipeline_imported_shader_count(struct anv_pipeline_stage *stages)
2173 {
2174 uint32_t count = 0;
2175 for (uint32_t s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
2176 if (stages[s].imported.bin != NULL)
2177 count++;
2178 }
2179 return count;
2180 }
2181
2182 static VkResult
anv_graphics_pipeline_compile(struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_stage * stages,struct vk_pipeline_cache * cache,VkPipelineCreationFeedback * pipeline_feedback,const VkGraphicsPipelineCreateInfo * info,const struct vk_graphics_pipeline_state * state)2183 anv_graphics_pipeline_compile(struct anv_graphics_base_pipeline *pipeline,
2184 struct anv_pipeline_stage *stages,
2185 struct vk_pipeline_cache *cache,
2186 VkPipelineCreationFeedback *pipeline_feedback,
2187 const VkGraphicsPipelineCreateInfo *info,
2188 const struct vk_graphics_pipeline_state *state)
2189 {
2190 int64_t pipeline_start = os_time_get_nano();
2191
2192 struct anv_device *device = pipeline->base.device;
2193 const struct intel_device_info *devinfo = device->info;
2194 const struct brw_compiler *compiler = device->physical->compiler;
2195
2196 /* Setup the shaders given in this VkGraphicsPipelineCreateInfo::pStages[].
2197 * Other shaders imported from libraries should have been added by
2198 * anv_graphics_pipeline_import_lib().
2199 */
2200 uint32_t shader_count = anv_graphics_pipeline_imported_shader_count(stages);
2201 for (uint32_t i = 0; i < info->stageCount; i++) {
2202 gl_shader_stage stage = vk_to_mesa_shader_stage(info->pStages[i].stage);
2203
2204 /* If a pipeline library is loaded in this stage, we should ignore the
2205 * pStages[] entry of the same stage.
2206 */
2207 if (stages[stage].imported.bin != NULL)
2208 continue;
2209
2210 stages[stage].stage = stage;
2211 stages[stage].pipeline_flags = pipeline->base.flags;
2212 stages[stage].pipeline_pNext = info->pNext;
2213 stages[stage].info = &info->pStages[i];
2214 stages[stage].feedback_idx = shader_count++;
2215
2216 anv_stage_write_shader_hash(&stages[stage], device);
2217 }
2218
2219 /* Prepare shader keys for all shaders in pipeline->base.active_stages
2220 * (this includes libraries) before generating the hash for cache look up.
2221 *
2222 * We're doing this because the spec states that :
2223 *
2224 * "When an implementation is looking up a pipeline in a pipeline cache,
2225 * if that pipeline is being created using linked libraries,
2226 * implementations should always return an equivalent pipeline created
2227 * with VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT if available,
2228 * whether or not that bit was specified."
2229 *
2230 * So even if the application does not request link optimization, we have
2231 * to do our cache lookup with the entire set of shader sha1s so that we
2232 * can find what would be the best optimized pipeline in the case as if we
2233 * had compiled all the shaders together and known the full graphics state.
2234 */
2235 anv_graphics_pipeline_init_keys(pipeline, state, stages);
2236
2237 uint32_t view_mask = state->rp ? state->rp->view_mask : 0;
2238
2239 unsigned char sha1[20];
2240 anv_pipeline_hash_graphics(pipeline, stages, view_mask, sha1);
2241
2242 for (unsigned s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
2243 if (!anv_pipeline_base_has_stage(pipeline, s))
2244 continue;
2245
2246 stages[s].cache_key.stage = s;
2247 memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
2248 }
2249
2250 const bool retain_shaders =
2251 pipeline->base.flags & VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT;
2252 const bool link_optimize =
2253 pipeline->base.flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT;
2254
2255 VkResult result = VK_SUCCESS;
2256 const bool skip_cache_lookup =
2257 (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
2258
2259 if (!skip_cache_lookup) {
2260 bool found_all_shaders =
2261 anv_graphics_pipeline_load_cached_shaders(pipeline, cache, stages,
2262 link_optimize,
2263 pipeline_feedback);
2264
2265 if (found_all_shaders) {
2266 /* If we need to retain shaders, we need to also load from the NIR
2267 * cache.
2268 */
2269 if (pipeline->base.type == ANV_PIPELINE_GRAPHICS_LIB && retain_shaders) {
2270 result = anv_graphics_pipeline_load_nir(pipeline, cache,
2271 stages,
2272 pipeline->base.mem_ctx,
2273 false /* need_clone */);
2274 if (result != VK_SUCCESS) {
2275 vk_perf(VK_LOG_OBJS(cache ? &cache->base :
2276 &pipeline->base.device->vk.base),
2277 "Found all ISA shaders in the cache but not all NIR shaders.");
2278 } else {
2279 anv_graphics_lib_retain_shaders(pipeline, stages, false /* will_compile */);
2280 }
2281 }
2282
2283 if (result == VK_SUCCESS)
2284 goto done;
2285
2286 for (unsigned s = 0; s < ANV_GRAPHICS_SHADER_STAGE_COUNT; s++) {
2287 if (!anv_pipeline_base_has_stage(pipeline, s))
2288 continue;
2289
2290 if (stages[s].nir) {
2291 ralloc_free(stages[s].nir);
2292 stages[s].nir = NULL;
2293 }
2294
2295 assert(pipeline->shaders[s] != NULL);
2296 anv_shader_bin_unref(device, pipeline->shaders[s]);
2297 pipeline->shaders[s] = NULL;
2298 }
2299 }
2300 }
2301
2302 if (pipeline->base.flags & VK_PIPELINE_CREATE_2_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_KHR)
2303 return VK_PIPELINE_COMPILE_REQUIRED;
2304
2305 void *tmp_ctx = ralloc_context(NULL);
2306
2307 result = anv_graphics_pipeline_load_nir(pipeline, cache, stages,
2308 tmp_ctx, link_optimize /* need_clone */);
2309 if (result != VK_SUCCESS)
2310 goto fail;
2311
2312 /* Retain shaders now if asked, this only applies to libraries */
2313 if (pipeline->base.type == ANV_PIPELINE_GRAPHICS_LIB && retain_shaders)
2314 anv_graphics_lib_retain_shaders(pipeline, stages, true /* will_compile */);
2315
2316 /* The following steps will be executed for shaders we need to compile :
2317 *
2318 * - specified through VkGraphicsPipelineCreateInfo::pStages[]
2319 *
2320 * - or compiled from libraries with retained shaders (libraries
2321 * compiled with CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT) if the
2322 * pipeline has the CREATE_LINK_TIME_OPTIMIZATION_BIT flag.
2323 */
2324
2325 /* Preprocess all NIR shaders. */
2326 for (int s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
2327 if (anv_graphics_pipeline_skip_shader_compile(pipeline, stages,
2328 link_optimize, s))
2329 continue;
2330
2331 anv_stage_allocate_bind_map_tables(&pipeline->base, &stages[s], tmp_ctx);
2332
2333 anv_pipeline_nir_preprocess(&pipeline->base, &stages[s]);
2334 }
2335
2336 if (stages[MESA_SHADER_MESH].info && stages[MESA_SHADER_FRAGMENT].info) {
2337 anv_apply_per_prim_attr_wa(stages[MESA_SHADER_MESH].nir,
2338 stages[MESA_SHADER_FRAGMENT].nir,
2339 device,
2340 info);
2341 }
2342
2343 /* Walk backwards to link */
2344 struct anv_pipeline_stage *next_stage = NULL;
2345 for (int i = ARRAY_SIZE(graphics_shader_order) - 1; i >= 0; i--) {
2346 gl_shader_stage s = graphics_shader_order[i];
2347 if (anv_graphics_pipeline_skip_shader_compile(pipeline, stages,
2348 link_optimize, s))
2349 continue;
2350
2351 struct anv_pipeline_stage *stage = &stages[s];
2352
2353 switch (s) {
2354 case MESA_SHADER_VERTEX:
2355 anv_pipeline_link_vs(compiler, stage, next_stage);
2356 break;
2357 case MESA_SHADER_TESS_CTRL:
2358 anv_pipeline_link_tcs(compiler, stage, next_stage);
2359 break;
2360 case MESA_SHADER_TESS_EVAL:
2361 anv_pipeline_link_tes(compiler, stage, next_stage);
2362 break;
2363 case MESA_SHADER_GEOMETRY:
2364 anv_pipeline_link_gs(compiler, stage, next_stage);
2365 break;
2366 case MESA_SHADER_TASK:
2367 anv_pipeline_link_task(compiler, stage, next_stage);
2368 break;
2369 case MESA_SHADER_MESH:
2370 anv_pipeline_link_mesh(compiler, stage, next_stage);
2371 break;
2372 case MESA_SHADER_FRAGMENT:
2373 anv_pipeline_link_fs(compiler, stage, state->rp);
2374 break;
2375 default:
2376 unreachable("Invalid graphics shader stage");
2377 }
2378
2379 next_stage = stage;
2380 }
2381
2382 bool use_primitive_replication = false;
2383 if (devinfo->ver >= 12 && view_mask != 0) {
2384 /* For some pipelines HW Primitive Replication can be used instead of
2385 * instancing to implement Multiview. This depend on how viewIndex is
2386 * used in all the active shaders, so this check can't be done per
2387 * individual shaders.
2388 */
2389 nir_shader *shaders[ANV_GRAPHICS_SHADER_STAGE_COUNT] = {};
2390 for (unsigned s = 0; s < ARRAY_SIZE(shaders); s++)
2391 shaders[s] = stages[s].nir;
2392
2393 use_primitive_replication =
2394 anv_check_for_primitive_replication(device,
2395 pipeline->base.active_stages,
2396 shaders, view_mask);
2397 }
2398
2399 struct anv_pipeline_stage *prev_stage = NULL;
2400 for (unsigned i = 0; i < ARRAY_SIZE(graphics_shader_order); i++) {
2401 gl_shader_stage s = graphics_shader_order[i];
2402 if (anv_graphics_pipeline_skip_shader_compile(pipeline, stages,
2403 link_optimize, s))
2404 continue;
2405
2406 struct anv_pipeline_stage *stage = &stages[s];
2407
2408 int64_t stage_start = os_time_get_nano();
2409
2410 anv_pipeline_lower_nir(&pipeline->base, tmp_ctx, stage,
2411 &pipeline->base.layout, view_mask,
2412 use_primitive_replication);
2413
2414 struct shader_info *cur_info = &stage->nir->info;
2415
2416 if (prev_stage && compiler->nir_options[s]->unify_interfaces) {
2417 struct shader_info *prev_info = &prev_stage->nir->info;
2418
2419 prev_info->outputs_written |= cur_info->inputs_read &
2420 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
2421 cur_info->inputs_read |= prev_info->outputs_written &
2422 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
2423 prev_info->patch_outputs_written |= cur_info->patch_inputs_read;
2424 cur_info->patch_inputs_read |= prev_info->patch_outputs_written;
2425 }
2426
2427 anv_fixup_subgroup_size(device, cur_info);
2428
2429 stage->feedback.duration += os_time_get_nano() - stage_start;
2430
2431 prev_stage = stage;
2432 }
2433
2434 /* In the case the platform can write the primitive variable shading rate
2435 * and KHR_fragment_shading_rate is enabled :
2436 * - there can be a fragment shader but we don't have it yet
2437 * - the fragment shader needs fragment shading rate
2438 *
2439 * figure out the last geometry stage that should write the primitive
2440 * shading rate, and ensure it is marked as used there. The backend will
2441 * write a default value if the shader doesn't actually write it.
2442 *
2443 * We iterate backwards in the stage and stop on the first shader that can
2444 * set the value.
2445 *
2446 * Don't apply this to MESH stages, as this is a per primitive thing.
2447 */
2448 if (devinfo->has_coarse_pixel_primitive_and_cb &&
2449 device->vk.enabled_extensions.KHR_fragment_shading_rate &&
2450 pipeline_has_coarse_pixel(state->dynamic, state->ms, state->fsr) &&
2451 (!stages[MESA_SHADER_FRAGMENT].info ||
2452 stages[MESA_SHADER_FRAGMENT].key.wm.coarse_pixel) &&
2453 stages[MESA_SHADER_MESH].nir == NULL) {
2454 struct anv_pipeline_stage *last_psr = NULL;
2455
2456 for (unsigned i = 0; i < ARRAY_SIZE(graphics_shader_order); i++) {
2457 gl_shader_stage s =
2458 graphics_shader_order[ARRAY_SIZE(graphics_shader_order) - i - 1];
2459
2460 if (anv_graphics_pipeline_skip_shader_compile(pipeline, stages,
2461 link_optimize, s) ||
2462 !gl_shader_stage_can_set_fragment_shading_rate(s))
2463 continue;
2464
2465 last_psr = &stages[s];
2466 break;
2467 }
2468
2469 /* Only set primitive shading rate if there is a pre-rasterization
2470 * shader in this pipeline/pipeline-library.
2471 */
2472 if (last_psr)
2473 last_psr->nir->info.outputs_written |= VARYING_BIT_PRIMITIVE_SHADING_RATE;
2474 }
2475
2476 prev_stage = NULL;
2477 for (unsigned i = 0; i < ARRAY_SIZE(graphics_shader_order); i++) {
2478 gl_shader_stage s = graphics_shader_order[i];
2479 struct anv_pipeline_stage *stage = &stages[s];
2480
2481 if (anv_graphics_pipeline_skip_shader_compile(pipeline, stages, link_optimize, s))
2482 continue;
2483
2484 int64_t stage_start = os_time_get_nano();
2485
2486 void *stage_ctx = ralloc_context(NULL);
2487 char *error_str = NULL;
2488
2489 switch (s) {
2490 case MESA_SHADER_VERTEX:
2491 anv_pipeline_compile_vs(compiler, stage_ctx, pipeline,
2492 stage, view_mask, &error_str);
2493 break;
2494 case MESA_SHADER_TESS_CTRL:
2495 anv_pipeline_compile_tcs(compiler, stage_ctx, device,
2496 stage, prev_stage, &error_str);
2497 break;
2498 case MESA_SHADER_TESS_EVAL:
2499 anv_pipeline_compile_tes(compiler, stage_ctx, device,
2500 stage, prev_stage, &error_str);
2501 break;
2502 case MESA_SHADER_GEOMETRY:
2503 anv_pipeline_compile_gs(compiler, stage_ctx, device,
2504 stage, prev_stage, &error_str);
2505 break;
2506 case MESA_SHADER_TASK:
2507 anv_pipeline_compile_task(compiler, stage_ctx, device,
2508 stage, &error_str);
2509 break;
2510 case MESA_SHADER_MESH:
2511 anv_pipeline_compile_mesh(compiler, stage_ctx, device,
2512 stage, prev_stage, &error_str);
2513 break;
2514 case MESA_SHADER_FRAGMENT:
2515 anv_pipeline_compile_fs(compiler, stage_ctx, device,
2516 stage, prev_stage, pipeline,
2517 view_mask, use_primitive_replication,
2518 &error_str);
2519 break;
2520 default:
2521 unreachable("Invalid graphics shader stage");
2522 }
2523 if (stage->code == NULL) {
2524 if (error_str)
2525 result = vk_errorf(pipeline, VK_ERROR_UNKNOWN, "%s", error_str);
2526 else
2527 result = vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
2528 ralloc_free(stage_ctx);
2529 goto fail;
2530 }
2531
2532 anv_nir_validate_push_layout(device->physical, &stage->prog_data.base,
2533 &stage->bind_map);
2534
2535 struct anv_shader_upload_params upload_params = {
2536 .stage = s,
2537 .key_data = &stage->cache_key,
2538 .key_size = sizeof(stage->cache_key),
2539 .kernel_data = stage->code,
2540 .kernel_size = stage->prog_data.base.program_size,
2541 .prog_data = &stage->prog_data.base,
2542 .prog_data_size = brw_prog_data_size(s),
2543 .stats = stage->stats,
2544 .num_stats = stage->num_stats,
2545 .xfb_info = stage->nir->xfb_info,
2546 .bind_map = &stage->bind_map,
2547 .push_desc_info = &stage->push_desc_info,
2548 .dynamic_push_values = stage->dynamic_push_values,
2549 };
2550
2551 stage->bin =
2552 anv_device_upload_kernel(device, cache, &upload_params);
2553 if (!stage->bin) {
2554 ralloc_free(stage_ctx);
2555 result = vk_error(pipeline, VK_ERROR_OUT_OF_HOST_MEMORY);
2556 goto fail;
2557 }
2558
2559 anv_pipeline_add_executables(&pipeline->base, stage);
2560 pipeline->source_hashes[s] = stage->source_hash;
2561 pipeline->shaders[s] = stage->bin;
2562
2563 ralloc_free(stage_ctx);
2564
2565 stage->feedback.duration += os_time_get_nano() - stage_start;
2566
2567 prev_stage = stage;
2568 }
2569
2570 /* Finally add the imported shaders that were not compiled as part of this
2571 * step.
2572 */
2573 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
2574 if (!anv_pipeline_base_has_stage(pipeline, s))
2575 continue;
2576
2577 if (pipeline->shaders[s] != NULL)
2578 continue;
2579
2580 /* We should have recompiled everything with link optimization. */
2581 assert(!link_optimize);
2582
2583 struct anv_pipeline_stage *stage = &stages[s];
2584
2585 pipeline->source_hashes[s] = stage->source_hash;
2586 pipeline->shaders[s] = anv_shader_bin_ref(stage->imported.bin);
2587 }
2588
2589 ralloc_free(tmp_ctx);
2590
2591 done:
2592
2593 /* Write the feedback index into the pipeline */
2594 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
2595 if (!anv_pipeline_base_has_stage(pipeline, s))
2596 continue;
2597
2598 struct anv_pipeline_stage *stage = &stages[s];
2599 pipeline->feedback_index[s] = stage->feedback_idx;
2600 pipeline->robust_flags[s] = stage->robust_flags;
2601
2602 anv_pipeline_account_shader(&pipeline->base, pipeline->shaders[s]);
2603 }
2604
2605 pipeline_feedback->duration = os_time_get_nano() - pipeline_start;
2606
2607 if (pipeline->shaders[MESA_SHADER_FRAGMENT]) {
2608 pipeline->fragment_dynamic =
2609 anv_graphics_pipeline_stage_fragment_dynamic(
2610 &stages[MESA_SHADER_FRAGMENT]);
2611 }
2612
2613 return VK_SUCCESS;
2614
2615 fail:
2616 ralloc_free(tmp_ctx);
2617
2618 for (unsigned s = 0; s < ARRAY_SIZE(pipeline->shaders); s++) {
2619 if (pipeline->shaders[s])
2620 anv_shader_bin_unref(device, pipeline->shaders[s]);
2621 }
2622
2623 return result;
2624 }
2625
2626 static VkResult
anv_pipeline_compile_cs(struct anv_compute_pipeline * pipeline,struct vk_pipeline_cache * cache,const VkComputePipelineCreateInfo * info)2627 anv_pipeline_compile_cs(struct anv_compute_pipeline *pipeline,
2628 struct vk_pipeline_cache *cache,
2629 const VkComputePipelineCreateInfo *info)
2630 {
2631 ASSERTED const VkPipelineShaderStageCreateInfo *sinfo = &info->stage;
2632 assert(sinfo->stage == VK_SHADER_STAGE_COMPUTE_BIT);
2633
2634 VkPipelineCreationFeedback pipeline_feedback = {
2635 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
2636 };
2637 int64_t pipeline_start = os_time_get_nano();
2638
2639 struct anv_device *device = pipeline->base.device;
2640 const struct brw_compiler *compiler = device->physical->compiler;
2641
2642 struct anv_pipeline_stage stage = {
2643 .stage = MESA_SHADER_COMPUTE,
2644 .info = &info->stage,
2645 .pipeline_flags = pipeline->base.flags,
2646 .pipeline_pNext = info->pNext,
2647 .cache_key = {
2648 .stage = MESA_SHADER_COMPUTE,
2649 },
2650 .feedback = {
2651 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
2652 },
2653 };
2654 anv_stage_write_shader_hash(&stage, device);
2655
2656 populate_cs_prog_key(&stage, device);
2657
2658 const bool skip_cache_lookup =
2659 (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
2660
2661 anv_pipeline_hash_compute(pipeline, &stage, stage.cache_key.sha1);
2662
2663 bool cache_hit = false;
2664 if (!skip_cache_lookup) {
2665 stage.bin = anv_device_search_for_kernel(device, cache,
2666 &stage.cache_key,
2667 sizeof(stage.cache_key),
2668 &cache_hit);
2669 }
2670
2671 if (stage.bin == NULL &&
2672 (pipeline->base.flags & VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT))
2673 return VK_PIPELINE_COMPILE_REQUIRED;
2674
2675 void *mem_ctx = ralloc_context(NULL);
2676 if (stage.bin == NULL) {
2677 int64_t stage_start = os_time_get_nano();
2678
2679 anv_stage_allocate_bind_map_tables(&pipeline->base, &stage, mem_ctx);
2680
2681 /* Set up a binding for the gl_NumWorkGroups */
2682 stage.bind_map.surface_count = 1;
2683 stage.bind_map.surface_to_descriptor[0] = (struct anv_pipeline_binding) {
2684 .set = ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS,
2685 .binding = UINT32_MAX,
2686 };
2687
2688 VkResult result = anv_pipeline_stage_get_nir(&pipeline->base, cache,
2689 mem_ctx, &stage);
2690 if (result != VK_SUCCESS) {
2691 ralloc_free(mem_ctx);
2692 return result;
2693 }
2694
2695 anv_pipeline_nir_preprocess(&pipeline->base, &stage);
2696
2697 anv_pipeline_lower_nir(&pipeline->base, mem_ctx, &stage,
2698 &pipeline->base.layout, 0 /* view_mask */,
2699 false /* use_primitive_replication */);
2700
2701 anv_fixup_subgroup_size(device, &stage.nir->info);
2702
2703 stage.num_stats = 1;
2704
2705 struct brw_compile_cs_params params = {
2706 .base = {
2707 .nir = stage.nir,
2708 .stats = stage.stats,
2709 .log_data = device,
2710 .mem_ctx = mem_ctx,
2711 .source_hash = stage.source_hash,
2712 },
2713 .key = &stage.key.cs,
2714 .prog_data = &stage.prog_data.cs,
2715 };
2716
2717 stage.code = brw_compile_cs(compiler, ¶ms);
2718 if (stage.code == NULL) {
2719 VkResult result;
2720
2721 if (params.base.error_str)
2722 result = vk_errorf(pipeline, VK_ERROR_UNKNOWN, "%s", params.base.error_str);
2723 else
2724 result = vk_error(pipeline, VK_ERROR_OUT_OF_HOST_MEMORY);
2725
2726 ralloc_free(mem_ctx);
2727 return result;
2728 }
2729
2730 anv_nir_validate_push_layout(device->physical, &stage.prog_data.base,
2731 &stage.bind_map);
2732
2733 if (!stage.prog_data.cs.uses_num_work_groups) {
2734 assert(stage.bind_map.surface_to_descriptor[0].set ==
2735 ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS);
2736 stage.bind_map.surface_to_descriptor[0].set = ANV_DESCRIPTOR_SET_NULL;
2737 }
2738
2739 struct anv_shader_upload_params upload_params = {
2740 .stage = MESA_SHADER_COMPUTE,
2741 .key_data = &stage.cache_key,
2742 .key_size = sizeof(stage.cache_key),
2743 .kernel_data = stage.code,
2744 .kernel_size = stage.prog_data.base.program_size,
2745 .prog_data = &stage.prog_data.base,
2746 .prog_data_size = sizeof(stage.prog_data.cs),
2747 .stats = stage.stats,
2748 .num_stats = stage.num_stats,
2749 .bind_map = &stage.bind_map,
2750 .push_desc_info = &stage.push_desc_info,
2751 .dynamic_push_values = stage.dynamic_push_values,
2752 };
2753
2754 stage.bin = anv_device_upload_kernel(device, cache, &upload_params);
2755 if (!stage.bin) {
2756 ralloc_free(mem_ctx);
2757 return vk_error(pipeline, VK_ERROR_OUT_OF_HOST_MEMORY);
2758 }
2759
2760 stage.feedback.duration = os_time_get_nano() - stage_start;
2761 }
2762
2763 anv_pipeline_account_shader(&pipeline->base, stage.bin);
2764 anv_pipeline_add_executables(&pipeline->base, &stage);
2765 pipeline->source_hash = stage.source_hash;
2766
2767 ralloc_free(mem_ctx);
2768
2769 if (cache_hit) {
2770 stage.feedback.flags |=
2771 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
2772 pipeline_feedback.flags |=
2773 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
2774 }
2775 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
2776
2777 const VkPipelineCreationFeedbackCreateInfo *create_feedback =
2778 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO);
2779 if (create_feedback) {
2780 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
2781
2782 if (create_feedback->pipelineStageCreationFeedbackCount) {
2783 assert(create_feedback->pipelineStageCreationFeedbackCount == 1);
2784 create_feedback->pPipelineStageCreationFeedbacks[0] = stage.feedback;
2785 }
2786 }
2787
2788 pipeline->cs = stage.bin;
2789
2790 return VK_SUCCESS;
2791 }
2792
2793 static VkResult
anv_compute_pipeline_create(struct anv_device * device,struct vk_pipeline_cache * cache,const VkComputePipelineCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)2794 anv_compute_pipeline_create(struct anv_device *device,
2795 struct vk_pipeline_cache *cache,
2796 const VkComputePipelineCreateInfo *pCreateInfo,
2797 const VkAllocationCallbacks *pAllocator,
2798 VkPipeline *pPipeline)
2799 {
2800 struct anv_compute_pipeline *pipeline;
2801 VkResult result;
2802
2803 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
2804
2805 pipeline = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8,
2806 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2807 if (pipeline == NULL)
2808 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
2809
2810 result = anv_pipeline_init(&pipeline->base, device,
2811 ANV_PIPELINE_COMPUTE,
2812 vk_compute_pipeline_create_flags(pCreateInfo),
2813 pAllocator);
2814 if (result != VK_SUCCESS) {
2815 vk_free2(&device->vk.alloc, pAllocator, pipeline);
2816 return result;
2817 }
2818
2819
2820 ANV_FROM_HANDLE(anv_pipeline_layout, pipeline_layout, pCreateInfo->layout);
2821 anv_pipeline_init_layout(&pipeline->base, pipeline_layout);
2822
2823 pipeline->base.active_stages = VK_SHADER_STAGE_COMPUTE_BIT;
2824
2825 anv_batch_set_storage(&pipeline->base.batch, ANV_NULL_ADDRESS,
2826 pipeline->batch_data, sizeof(pipeline->batch_data));
2827
2828 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo);
2829 if (result != VK_SUCCESS) {
2830 anv_pipeline_finish(&pipeline->base, device);
2831 vk_free2(&device->vk.alloc, pAllocator, pipeline);
2832 return result;
2833 }
2834
2835 anv_genX(device->info, compute_pipeline_emit)(pipeline);
2836
2837 ANV_RMV(compute_pipeline_create, device, pipeline, false);
2838
2839 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
2840
2841 return pipeline->base.batch.status;
2842 }
2843
anv_CreateComputePipelines(VkDevice _device,VkPipelineCache pipelineCache,uint32_t count,const VkComputePipelineCreateInfo * pCreateInfos,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipelines)2844 VkResult anv_CreateComputePipelines(
2845 VkDevice _device,
2846 VkPipelineCache pipelineCache,
2847 uint32_t count,
2848 const VkComputePipelineCreateInfo* pCreateInfos,
2849 const VkAllocationCallbacks* pAllocator,
2850 VkPipeline* pPipelines)
2851 {
2852 ANV_FROM_HANDLE(anv_device, device, _device);
2853 ANV_FROM_HANDLE(vk_pipeline_cache, pipeline_cache, pipelineCache);
2854
2855 VkResult result = VK_SUCCESS;
2856
2857 unsigned i;
2858 for (i = 0; i < count; i++) {
2859 const VkPipelineCreateFlags2KHR flags =
2860 vk_compute_pipeline_create_flags(&pCreateInfos[i]);
2861 VkResult res = anv_compute_pipeline_create(device, pipeline_cache,
2862 &pCreateInfos[i],
2863 pAllocator, &pPipelines[i]);
2864
2865 if (res != VK_SUCCESS) {
2866 result = res;
2867 if (flags & VK_PIPELINE_CREATE_2_EARLY_RETURN_ON_FAILURE_BIT_KHR)
2868 break;
2869 pPipelines[i] = VK_NULL_HANDLE;
2870 }
2871 }
2872
2873 for (; i < count; i++)
2874 pPipelines[i] = VK_NULL_HANDLE;
2875
2876 return result;
2877 }
2878
2879 /**
2880 * Calculate the desired L3 partitioning based on the current state of the
2881 * pipeline. For now this simply returns the conservative defaults calculated
2882 * by get_default_l3_weights(), but we could probably do better by gathering
2883 * more statistics from the pipeline state (e.g. guess of expected URB usage
2884 * and bound surfaces), or by using feed-back from performance counters.
2885 */
2886 void
anv_pipeline_setup_l3_config(struct anv_pipeline * pipeline,bool needs_slm)2887 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
2888 {
2889 const struct intel_device_info *devinfo = pipeline->device->info;
2890
2891 const struct intel_l3_weights w =
2892 intel_get_default_l3_weights(devinfo, true, needs_slm);
2893
2894 pipeline->l3_config = intel_get_l3_config(devinfo, w);
2895 }
2896
2897 static uint32_t
get_vs_input_elements(const struct brw_vs_prog_data * vs_prog_data)2898 get_vs_input_elements(const struct brw_vs_prog_data *vs_prog_data)
2899 {
2900 /* Pull inputs_read out of the VS prog data */
2901 const uint64_t inputs_read = vs_prog_data->inputs_read;
2902 const uint64_t double_inputs_read =
2903 vs_prog_data->double_inputs_read & inputs_read;
2904 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
2905 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
2906 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
2907
2908 return __builtin_popcount(elements) -
2909 __builtin_popcount(elements_double) / 2;
2910 }
2911
2912 static void
anv_graphics_pipeline_emit(struct anv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)2913 anv_graphics_pipeline_emit(struct anv_graphics_pipeline *pipeline,
2914 const struct vk_graphics_pipeline_state *state)
2915 {
2916 pipeline->view_mask = state->rp->view_mask;
2917
2918 anv_pipeline_setup_l3_config(&pipeline->base.base, false);
2919
2920 if (anv_pipeline_is_primitive(pipeline)) {
2921 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2922
2923 /* The total number of vertex elements we need to program. We might need
2924 * a couple more to implement some of the draw parameters.
2925 */
2926 pipeline->svgs_count =
2927 (vs_prog_data->uses_vertexid ||
2928 vs_prog_data->uses_instanceid ||
2929 vs_prog_data->uses_firstvertex ||
2930 vs_prog_data->uses_baseinstance) + vs_prog_data->uses_drawid;
2931
2932 pipeline->vs_input_elements = get_vs_input_elements(vs_prog_data);
2933
2934 pipeline->vertex_input_elems =
2935 (BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_VI) ?
2936 0 : pipeline->vs_input_elements) + pipeline->svgs_count;
2937
2938 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2939 * different views when primitive replication cannot be used. If the
2940 * client asks for instancing, we need to multiply by the client's
2941 * instance count at draw time and instance divisor in the vertex
2942 * bindings by the number of views ensure that we repeat the client's
2943 * per-instance data once for each view.
2944 */
2945 const bool uses_primitive_replication =
2946 anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map.num_pos_slots > 1;
2947 pipeline->instance_multiplier = 1;
2948 if (pipeline->view_mask && !uses_primitive_replication)
2949 pipeline->instance_multiplier = util_bitcount(pipeline->view_mask);
2950 } else {
2951 assert(anv_pipeline_is_mesh(pipeline));
2952 /* TODO(mesh): Mesh vs. Multiview with Instancing. */
2953 }
2954
2955
2956 pipeline->dynamic_patch_control_points =
2957 anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_CTRL) &&
2958 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_TS_PATCH_CONTROL_POINTS) &&
2959 (pipeline->base.shaders[MESA_SHADER_TESS_CTRL]->dynamic_push_values &
2960 ANV_DYNAMIC_PUSH_INPUT_VERTICES);
2961
2962 if (pipeline->base.shaders[MESA_SHADER_FRAGMENT] && state->ms) {
2963 pipeline->sample_shading_enable = state->ms->sample_shading_enable;
2964 pipeline->min_sample_shading = state->ms->min_sample_shading;
2965 }
2966
2967 const struct anv_device *device = pipeline->base.base.device;
2968 const struct intel_device_info *devinfo = device->info;
2969 anv_genX(devinfo, graphics_pipeline_emit)(pipeline, state);
2970 }
2971
2972 static void
anv_graphics_pipeline_import_layout(struct anv_graphics_base_pipeline * pipeline,struct anv_pipeline_sets_layout * layout)2973 anv_graphics_pipeline_import_layout(struct anv_graphics_base_pipeline *pipeline,
2974 struct anv_pipeline_sets_layout *layout)
2975 {
2976 pipeline->base.layout.independent_sets |= layout->independent_sets;
2977
2978 for (uint32_t s = 0; s < layout->num_sets; s++) {
2979 if (layout->set[s].layout == NULL)
2980 continue;
2981
2982 anv_pipeline_sets_layout_add(&pipeline->base.layout, s,
2983 layout->set[s].layout);
2984 }
2985 }
2986
2987 static void
anv_graphics_pipeline_import_lib(struct anv_graphics_base_pipeline * pipeline,bool link_optimize,bool retain_shaders,struct anv_pipeline_stage * stages,struct anv_graphics_lib_pipeline * lib)2988 anv_graphics_pipeline_import_lib(struct anv_graphics_base_pipeline *pipeline,
2989 bool link_optimize,
2990 bool retain_shaders,
2991 struct anv_pipeline_stage *stages,
2992 struct anv_graphics_lib_pipeline *lib)
2993 {
2994 struct anv_pipeline_sets_layout *lib_layout =
2995 &lib->base.base.layout;
2996 anv_graphics_pipeline_import_layout(pipeline, lib_layout);
2997
2998 /* We can't have shaders specified twice through libraries. */
2999 assert((pipeline->base.active_stages & lib->base.base.active_stages) == 0);
3000
3001 /* VK_EXT_graphics_pipeline_library:
3002 *
3003 * "To perform link time optimizations,
3004 * VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT must
3005 * be specified on all pipeline libraries that are being linked
3006 * together. Implementations should retain any additional information
3007 * needed to perform optimizations at the final link step when this bit
3008 * is present."
3009 */
3010 assert(!link_optimize || lib->retain_shaders);
3011
3012 pipeline->base.active_stages |= lib->base.base.active_stages;
3013
3014 /* Propagate the fragment dynamic flag, unless we're doing link
3015 * optimization, in that case we'll have all the state information and this
3016 * will never be dynamic.
3017 */
3018 if (!link_optimize) {
3019 if (lib->base.fragment_dynamic) {
3020 assert(lib->base.base.active_stages & VK_SHADER_STAGE_FRAGMENT_BIT);
3021 pipeline->fragment_dynamic = true;
3022 }
3023 }
3024
3025 uint32_t shader_count = anv_graphics_pipeline_imported_shader_count(stages);
3026 for (uint32_t s = 0; s < ARRAY_SIZE(lib->base.shaders); s++) {
3027 if (lib->base.shaders[s] == NULL)
3028 continue;
3029
3030 stages[s].stage = s;
3031 stages[s].feedback_idx = shader_count + lib->base.feedback_index[s];
3032 stages[s].robust_flags = lib->base.robust_flags[s];
3033
3034 /* Always import the shader sha1, this will be used for cache lookup. */
3035 memcpy(stages[s].shader_sha1, lib->retained_shaders[s].shader_sha1,
3036 sizeof(stages[s].shader_sha1));
3037 stages[s].source_hash = lib->base.source_hashes[s];
3038
3039 stages[s].subgroup_size_type = lib->retained_shaders[s].subgroup_size_type;
3040 stages[s].imported.nir = lib->retained_shaders[s].nir;
3041 stages[s].imported.bin = lib->base.shaders[s];
3042 }
3043
3044 /* When not link optimizing, import the executables (shader descriptions
3045 * for VK_KHR_pipeline_executable_properties). With link optimization there
3046 * is a chance it'll produce different binaries, so we'll add the optimized
3047 * version later.
3048 */
3049 if (!link_optimize) {
3050 util_dynarray_foreach(&lib->base.base.executables,
3051 struct anv_pipeline_executable, exe) {
3052 util_dynarray_append(&pipeline->base.executables,
3053 struct anv_pipeline_executable, *exe);
3054 }
3055 }
3056 }
3057
3058 static void
anv_graphics_lib_validate_shaders(struct anv_graphics_lib_pipeline * lib,bool retained_shaders)3059 anv_graphics_lib_validate_shaders(struct anv_graphics_lib_pipeline *lib,
3060 bool retained_shaders)
3061 {
3062 for (uint32_t s = 0; s < ARRAY_SIZE(lib->retained_shaders); s++) {
3063 if (anv_pipeline_base_has_stage(&lib->base, s)) {
3064 assert(!retained_shaders || lib->retained_shaders[s].nir != NULL);
3065 assert(lib->base.shaders[s] != NULL);
3066 }
3067 }
3068 }
3069
3070 static VkResult
anv_graphics_lib_pipeline_create(struct anv_device * device,struct vk_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)3071 anv_graphics_lib_pipeline_create(struct anv_device *device,
3072 struct vk_pipeline_cache *cache,
3073 const VkGraphicsPipelineCreateInfo *pCreateInfo,
3074 const VkAllocationCallbacks *pAllocator,
3075 VkPipeline *pPipeline)
3076 {
3077 struct anv_pipeline_stage stages[ANV_GRAPHICS_SHADER_STAGE_COUNT] = {};
3078 VkPipelineCreationFeedback pipeline_feedback = {
3079 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
3080 };
3081 int64_t pipeline_start = os_time_get_nano();
3082
3083 struct anv_graphics_lib_pipeline *pipeline;
3084 VkResult result;
3085
3086 const VkPipelineCreateFlags2KHR flags =
3087 vk_graphics_pipeline_create_flags(pCreateInfo);
3088 assert(flags & VK_PIPELINE_CREATE_2_LIBRARY_BIT_KHR);
3089
3090 const VkPipelineLibraryCreateInfoKHR *libs_info =
3091 vk_find_struct_const(pCreateInfo->pNext,
3092 PIPELINE_LIBRARY_CREATE_INFO_KHR);
3093
3094 pipeline = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8,
3095 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3096 if (pipeline == NULL)
3097 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
3098
3099 result = anv_pipeline_init(&pipeline->base.base, device,
3100 ANV_PIPELINE_GRAPHICS_LIB, flags,
3101 pAllocator);
3102 if (result != VK_SUCCESS) {
3103 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3104 if (result == VK_PIPELINE_COMPILE_REQUIRED)
3105 *pPipeline = VK_NULL_HANDLE;
3106 return result;
3107 }
3108
3109 /* Capture the retain state before we compile/load any shader. */
3110 pipeline->retain_shaders =
3111 (flags & VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT) != 0;
3112
3113 /* If we have libraries, import them first. */
3114 if (libs_info) {
3115 for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
3116 ANV_FROM_HANDLE(anv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
3117 struct anv_graphics_lib_pipeline *gfx_pipeline_lib =
3118 anv_pipeline_to_graphics_lib(pipeline_lib);
3119
3120 vk_graphics_pipeline_state_merge(&pipeline->state, &gfx_pipeline_lib->state);
3121 anv_graphics_pipeline_import_lib(&pipeline->base,
3122 false /* link_optimize */,
3123 pipeline->retain_shaders,
3124 stages, gfx_pipeline_lib);
3125 }
3126 }
3127
3128 result = vk_graphics_pipeline_state_fill(&device->vk,
3129 &pipeline->state, pCreateInfo,
3130 NULL /* driver_rp */,
3131 0 /* driver_rp_flags */,
3132 &pipeline->all_state, NULL, 0, NULL);
3133 if (result != VK_SUCCESS) {
3134 anv_pipeline_finish(&pipeline->base.base, device);
3135 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3136 return result;
3137 }
3138
3139 pipeline->base.base.active_stages = pipeline->state.shader_stages;
3140
3141 /* After we've imported all the libraries' layouts, import the pipeline
3142 * layout and hash the whole lot.
3143 */
3144 ANV_FROM_HANDLE(anv_pipeline_layout, pipeline_layout, pCreateInfo->layout);
3145 if (pipeline_layout != NULL) {
3146 anv_graphics_pipeline_import_layout(&pipeline->base,
3147 &pipeline_layout->sets_layout);
3148 }
3149
3150 anv_pipeline_sets_layout_hash(&pipeline->base.base.layout);
3151
3152 /* Compile shaders. We can skip this if there are no active stage in that
3153 * pipeline.
3154 */
3155 if (pipeline->base.base.active_stages != 0) {
3156 result = anv_graphics_pipeline_compile(&pipeline->base, stages,
3157 cache, &pipeline_feedback,
3158 pCreateInfo, &pipeline->state);
3159 if (result != VK_SUCCESS) {
3160 anv_pipeline_finish(&pipeline->base.base, device);
3161 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3162 return result;
3163 }
3164 }
3165
3166 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
3167
3168 anv_fill_pipeline_creation_feedback(&pipeline->base, &pipeline_feedback,
3169 pCreateInfo, stages);
3170
3171 anv_graphics_lib_validate_shaders(
3172 pipeline,
3173 flags & VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT);
3174
3175 *pPipeline = anv_pipeline_to_handle(&pipeline->base.base);
3176
3177 return VK_SUCCESS;
3178 }
3179
3180 static VkResult
anv_graphics_pipeline_create(struct anv_device * device,struct vk_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)3181 anv_graphics_pipeline_create(struct anv_device *device,
3182 struct vk_pipeline_cache *cache,
3183 const VkGraphicsPipelineCreateInfo *pCreateInfo,
3184 const VkAllocationCallbacks *pAllocator,
3185 VkPipeline *pPipeline)
3186 {
3187 struct anv_pipeline_stage stages[ANV_GRAPHICS_SHADER_STAGE_COUNT] = {};
3188 VkPipelineCreationFeedback pipeline_feedback = {
3189 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
3190 };
3191 int64_t pipeline_start = os_time_get_nano();
3192
3193 struct anv_graphics_pipeline *pipeline;
3194 VkResult result;
3195
3196 const VkPipelineCreateFlags2KHR flags =
3197 vk_graphics_pipeline_create_flags(pCreateInfo);
3198 assert((flags & VK_PIPELINE_CREATE_2_LIBRARY_BIT_KHR) == 0);
3199
3200 const VkPipelineLibraryCreateInfoKHR *libs_info =
3201 vk_find_struct_const(pCreateInfo->pNext,
3202 PIPELINE_LIBRARY_CREATE_INFO_KHR);
3203
3204 pipeline = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8,
3205 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3206 if (pipeline == NULL)
3207 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
3208
3209 /* Initialize some information required by shaders */
3210 result = anv_pipeline_init(&pipeline->base.base, device,
3211 ANV_PIPELINE_GRAPHICS, flags,
3212 pAllocator);
3213 if (result != VK_SUCCESS) {
3214 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3215 return result;
3216 }
3217
3218 const bool link_optimize =
3219 (flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT) != 0;
3220
3221 struct vk_graphics_pipeline_all_state all;
3222 struct vk_graphics_pipeline_state state = { };
3223
3224 /* If we have libraries, import them first. */
3225 if (libs_info) {
3226 for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
3227 ANV_FROM_HANDLE(anv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
3228 struct anv_graphics_lib_pipeline *gfx_pipeline_lib =
3229 anv_pipeline_to_graphics_lib(pipeline_lib);
3230
3231 /* If we have link time optimization, all libraries must be created
3232 * with
3233 * VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT.
3234 */
3235 assert(!link_optimize || gfx_pipeline_lib->retain_shaders);
3236
3237 vk_graphics_pipeline_state_merge(&state, &gfx_pipeline_lib->state);
3238 anv_graphics_pipeline_import_lib(&pipeline->base,
3239 link_optimize,
3240 false,
3241 stages,
3242 gfx_pipeline_lib);
3243 }
3244 }
3245
3246 result = vk_graphics_pipeline_state_fill(&device->vk, &state, pCreateInfo,
3247 NULL /* driver_rp */,
3248 0 /* driver_rp_flags */,
3249 &all, NULL, 0, NULL);
3250 if (result != VK_SUCCESS) {
3251 anv_pipeline_finish(&pipeline->base.base, device);
3252 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3253 return result;
3254 }
3255
3256 pipeline->dynamic_state.vi = &pipeline->vertex_input;
3257 pipeline->dynamic_state.ms.sample_locations = &pipeline->base.sample_locations;
3258 vk_dynamic_graphics_state_fill(&pipeline->dynamic_state, &state);
3259
3260 pipeline->base.base.active_stages = state.shader_stages;
3261
3262 /* Sanity check on the shaders */
3263 assert(pipeline->base.base.active_stages & VK_SHADER_STAGE_VERTEX_BIT ||
3264 pipeline->base.base.active_stages & VK_SHADER_STAGE_MESH_BIT_EXT);
3265
3266 if (anv_pipeline_is_mesh(pipeline)) {
3267 assert(device->physical->vk.supported_extensions.EXT_mesh_shader);
3268 }
3269
3270 /* After we've imported all the libraries' layouts, import the pipeline
3271 * layout and hash the whole lot.
3272 */
3273 ANV_FROM_HANDLE(anv_pipeline_layout, pipeline_layout, pCreateInfo->layout);
3274 if (pipeline_layout != NULL) {
3275 anv_graphics_pipeline_import_layout(&pipeline->base,
3276 &pipeline_layout->sets_layout);
3277 }
3278
3279 anv_pipeline_sets_layout_hash(&pipeline->base.base.layout);
3280
3281 /* Compile shaders, all required information should be have been copied in
3282 * the previous step. We can skip this if there are no active stage in that
3283 * pipeline.
3284 */
3285 result = anv_graphics_pipeline_compile(&pipeline->base, stages,
3286 cache, &pipeline_feedback,
3287 pCreateInfo, &state);
3288 if (result != VK_SUCCESS) {
3289 anv_pipeline_finish(&pipeline->base.base, device);
3290 vk_free2(&device->vk.alloc, pAllocator, pipeline);
3291 return result;
3292 }
3293
3294 /* Prepare a batch for the commands and emit all the non dynamic ones.
3295 */
3296 anv_batch_set_storage(&pipeline->base.base.batch, ANV_NULL_ADDRESS,
3297 pipeline->batch_data, sizeof(pipeline->batch_data));
3298
3299 if (pipeline->base.base.active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
3300 pipeline->base.base.active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
3301
3302 if (anv_pipeline_is_mesh(pipeline))
3303 assert(device->physical->vk.supported_extensions.EXT_mesh_shader);
3304
3305 anv_graphics_pipeline_emit(pipeline, &state);
3306
3307 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
3308
3309 anv_fill_pipeline_creation_feedback(&pipeline->base, &pipeline_feedback,
3310 pCreateInfo, stages);
3311
3312 ANV_RMV(graphics_pipeline_create, device, pipeline, false);
3313
3314 *pPipeline = anv_pipeline_to_handle(&pipeline->base.base);
3315
3316 return pipeline->base.base.batch.status;
3317 }
3318
anv_CreateGraphicsPipelines(VkDevice _device,VkPipelineCache pipelineCache,uint32_t count,const VkGraphicsPipelineCreateInfo * pCreateInfos,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipelines)3319 VkResult anv_CreateGraphicsPipelines(
3320 VkDevice _device,
3321 VkPipelineCache pipelineCache,
3322 uint32_t count,
3323 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3324 const VkAllocationCallbacks* pAllocator,
3325 VkPipeline* pPipelines)
3326 {
3327 ANV_FROM_HANDLE(anv_device, device, _device);
3328 ANV_FROM_HANDLE(vk_pipeline_cache, pipeline_cache, pipelineCache);
3329
3330 VkResult result = VK_SUCCESS;
3331
3332 unsigned i;
3333 for (i = 0; i < count; i++) {
3334 assert(pCreateInfos[i].sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
3335
3336 const VkPipelineCreateFlags2KHR flags =
3337 vk_graphics_pipeline_create_flags(&pCreateInfos[i]);
3338 VkResult res;
3339 if (flags & VK_PIPELINE_CREATE_2_LIBRARY_BIT_KHR) {
3340 res = anv_graphics_lib_pipeline_create(device, pipeline_cache,
3341 &pCreateInfos[i],
3342 pAllocator,
3343 &pPipelines[i]);
3344 } else {
3345 res = anv_graphics_pipeline_create(device,
3346 pipeline_cache,
3347 &pCreateInfos[i],
3348 pAllocator, &pPipelines[i]);
3349 }
3350
3351 if (res != VK_SUCCESS) {
3352 result = res;
3353 if (flags & VK_PIPELINE_CREATE_2_EARLY_RETURN_ON_FAILURE_BIT_KHR)
3354 break;
3355 pPipelines[i] = VK_NULL_HANDLE;
3356 }
3357 }
3358
3359 for (; i < count; i++)
3360 pPipelines[i] = VK_NULL_HANDLE;
3361
3362 return result;
3363 }
3364
3365 static bool
should_remat_cb(nir_instr * instr,void * data)3366 should_remat_cb(nir_instr *instr, void *data)
3367 {
3368 if (instr->type != nir_instr_type_intrinsic)
3369 return false;
3370
3371 return nir_instr_as_intrinsic(instr)->intrinsic == nir_intrinsic_resource_intel;
3372 }
3373
3374 static VkResult
compile_upload_rt_shader(struct anv_ray_tracing_pipeline * pipeline,struct vk_pipeline_cache * cache,nir_shader * nir,struct anv_pipeline_stage * stage,void * mem_ctx)3375 compile_upload_rt_shader(struct anv_ray_tracing_pipeline *pipeline,
3376 struct vk_pipeline_cache *cache,
3377 nir_shader *nir,
3378 struct anv_pipeline_stage *stage,
3379 void *mem_ctx)
3380 {
3381 const struct brw_compiler *compiler =
3382 pipeline->base.device->physical->compiler;
3383 const struct intel_device_info *devinfo = compiler->devinfo;
3384
3385 nir_shader **resume_shaders = NULL;
3386 uint32_t num_resume_shaders = 0;
3387 if (nir->info.stage != MESA_SHADER_COMPUTE) {
3388 const nir_lower_shader_calls_options opts = {
3389 .address_format = nir_address_format_64bit_global,
3390 .stack_alignment = BRW_BTD_STACK_ALIGN,
3391 .localized_loads = true,
3392 .vectorizer_callback = brw_nir_should_vectorize_mem,
3393 .vectorizer_data = NULL,
3394 .should_remat_callback = should_remat_cb,
3395 };
3396
3397 NIR_PASS(_, nir, nir_lower_shader_calls, &opts,
3398 &resume_shaders, &num_resume_shaders, mem_ctx);
3399 NIR_PASS(_, nir, brw_nir_lower_shader_calls, &stage->key.bs);
3400 NIR_PASS_V(nir, brw_nir_lower_rt_intrinsics, devinfo);
3401 }
3402
3403 for (unsigned i = 0; i < num_resume_shaders; i++) {
3404 NIR_PASS(_,resume_shaders[i], brw_nir_lower_shader_calls, &stage->key.bs);
3405 NIR_PASS_V(resume_shaders[i], brw_nir_lower_rt_intrinsics, devinfo);
3406 }
3407
3408 struct brw_compile_bs_params params = {
3409 .base = {
3410 .nir = nir,
3411 .stats = stage->stats,
3412 .log_data = pipeline->base.device,
3413 .mem_ctx = mem_ctx,
3414 .source_hash = stage->source_hash,
3415 },
3416 .key = &stage->key.bs,
3417 .prog_data = &stage->prog_data.bs,
3418 .num_resume_shaders = num_resume_shaders,
3419 .resume_shaders = resume_shaders,
3420 };
3421
3422 stage->code = brw_compile_bs(compiler, ¶ms);
3423 if (stage->code == NULL) {
3424 VkResult result;
3425
3426 if (params.base.error_str)
3427 result = vk_errorf(pipeline, VK_ERROR_UNKNOWN, "%s", params.base.error_str);
3428 else
3429 result = vk_error(pipeline, VK_ERROR_OUT_OF_HOST_MEMORY);
3430
3431 return result;
3432 }
3433
3434 struct anv_shader_upload_params upload_params = {
3435 .stage = stage->stage,
3436 .key_data = &stage->cache_key,
3437 .key_size = sizeof(stage->cache_key),
3438 .kernel_data = stage->code,
3439 .kernel_size = stage->prog_data.base.program_size,
3440 .prog_data = &stage->prog_data.base,
3441 .prog_data_size = brw_prog_data_size(stage->stage),
3442 .stats = stage->stats,
3443 .num_stats = 1,
3444 .bind_map = &stage->bind_map,
3445 .push_desc_info = &stage->push_desc_info,
3446 .dynamic_push_values = stage->dynamic_push_values,
3447 };
3448
3449 stage->bin =
3450 anv_device_upload_kernel(pipeline->base.device, cache, &upload_params);
3451 if (stage->bin == NULL)
3452 return vk_error(pipeline, VK_ERROR_OUT_OF_HOST_MEMORY);
3453
3454 anv_pipeline_add_executables(&pipeline->base, stage);
3455
3456 return VK_SUCCESS;
3457 }
3458
3459 static bool
is_rt_stack_size_dynamic(const VkRayTracingPipelineCreateInfoKHR * info)3460 is_rt_stack_size_dynamic(const VkRayTracingPipelineCreateInfoKHR *info)
3461 {
3462 if (info->pDynamicState == NULL)
3463 return false;
3464
3465 for (unsigned i = 0; i < info->pDynamicState->dynamicStateCount; i++) {
3466 if (info->pDynamicState->pDynamicStates[i] ==
3467 VK_DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR)
3468 return true;
3469 }
3470
3471 return false;
3472 }
3473
3474 static void
anv_pipeline_compute_ray_tracing_stacks(struct anv_ray_tracing_pipeline * pipeline,const VkRayTracingPipelineCreateInfoKHR * info,uint32_t * stack_max)3475 anv_pipeline_compute_ray_tracing_stacks(struct anv_ray_tracing_pipeline *pipeline,
3476 const VkRayTracingPipelineCreateInfoKHR *info,
3477 uint32_t *stack_max)
3478 {
3479 if (is_rt_stack_size_dynamic(info)) {
3480 pipeline->stack_size = 0; /* 0 means dynamic */
3481 } else {
3482 /* From the Vulkan spec:
3483 *
3484 * "If the stack size is not set explicitly, the stack size for a
3485 * pipeline is:
3486 *
3487 * rayGenStackMax +
3488 * min(1, maxPipelineRayRecursionDepth) ×
3489 * max(closestHitStackMax, missStackMax,
3490 * intersectionStackMax + anyHitStackMax) +
3491 * max(0, maxPipelineRayRecursionDepth-1) ×
3492 * max(closestHitStackMax, missStackMax) +
3493 * 2 × callableStackMax"
3494 */
3495 pipeline->stack_size =
3496 stack_max[MESA_SHADER_RAYGEN] +
3497 MIN2(1, info->maxPipelineRayRecursionDepth) *
3498 MAX4(stack_max[MESA_SHADER_CLOSEST_HIT],
3499 stack_max[MESA_SHADER_MISS],
3500 stack_max[MESA_SHADER_INTERSECTION],
3501 stack_max[MESA_SHADER_ANY_HIT]) +
3502 MAX2(0, (int)info->maxPipelineRayRecursionDepth - 1) *
3503 MAX2(stack_max[MESA_SHADER_CLOSEST_HIT],
3504 stack_max[MESA_SHADER_MISS]) +
3505 2 * stack_max[MESA_SHADER_CALLABLE];
3506
3507 /* This is an extremely unlikely case but we need to set it to some
3508 * non-zero value so that we don't accidentally think it's dynamic.
3509 * Our minimum stack size is 2KB anyway so we could set to any small
3510 * value we like.
3511 */
3512 if (pipeline->stack_size == 0)
3513 pipeline->stack_size = 1;
3514 }
3515 }
3516
3517 static enum brw_rt_ray_flags
anv_pipeline_get_pipeline_ray_flags(VkPipelineCreateFlags2KHR flags)3518 anv_pipeline_get_pipeline_ray_flags(VkPipelineCreateFlags2KHR flags)
3519 {
3520 uint32_t ray_flags = 0;
3521
3522 const bool rt_skip_triangles =
3523 flags & VK_PIPELINE_CREATE_2_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR;
3524 const bool rt_skip_aabbs =
3525 flags & VK_PIPELINE_CREATE_2_RAY_TRACING_SKIP_AABBS_BIT_KHR;
3526 assert(!(rt_skip_triangles && rt_skip_aabbs));
3527
3528 if (rt_skip_triangles)
3529 ray_flags |= BRW_RT_RAY_FLAG_SKIP_TRIANGLES;
3530 else if (rt_skip_aabbs)
3531 ray_flags |= BRW_RT_RAY_FLAG_SKIP_AABBS;
3532
3533 return ray_flags;
3534 }
3535
3536 static struct anv_pipeline_stage *
anv_pipeline_init_ray_tracing_stages(struct anv_ray_tracing_pipeline * pipeline,const VkRayTracingPipelineCreateInfoKHR * info,void * tmp_pipeline_ctx)3537 anv_pipeline_init_ray_tracing_stages(struct anv_ray_tracing_pipeline *pipeline,
3538 const VkRayTracingPipelineCreateInfoKHR *info,
3539 void *tmp_pipeline_ctx)
3540 {
3541 struct anv_device *device = pipeline->base.device;
3542 /* Create enough stage entries for all shader modules plus potential
3543 * combinaisons in the groups.
3544 */
3545 struct anv_pipeline_stage *stages =
3546 rzalloc_array(tmp_pipeline_ctx, struct anv_pipeline_stage, info->stageCount);
3547
3548 enum brw_rt_ray_flags ray_flags =
3549 anv_pipeline_get_pipeline_ray_flags(pipeline->base.flags);
3550
3551 for (uint32_t i = 0; i < info->stageCount; i++) {
3552 const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
3553 if (vk_pipeline_shader_stage_is_null(sinfo))
3554 continue;
3555
3556 int64_t stage_start = os_time_get_nano();
3557
3558 stages[i] = (struct anv_pipeline_stage) {
3559 .stage = vk_to_mesa_shader_stage(sinfo->stage),
3560 .pipeline_flags = pipeline->base.flags,
3561 .pipeline_pNext = info->pNext,
3562 .info = sinfo,
3563 .cache_key = {
3564 .stage = vk_to_mesa_shader_stage(sinfo->stage),
3565 },
3566 .feedback = {
3567 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
3568 },
3569 };
3570
3571 anv_stage_allocate_bind_map_tables(&pipeline->base, &stages[i],
3572 tmp_pipeline_ctx);
3573
3574 pipeline->base.active_stages |= sinfo->stage;
3575
3576 anv_stage_write_shader_hash(&stages[i], device);
3577
3578 populate_bs_prog_key(&stages[i],
3579 pipeline->base.device,
3580 ray_flags);
3581
3582 if (stages[i].stage != MESA_SHADER_INTERSECTION) {
3583 anv_pipeline_hash_ray_tracing_shader(pipeline, &stages[i],
3584 stages[i].cache_key.sha1);
3585 }
3586
3587 stages[i].feedback.duration += os_time_get_nano() - stage_start;
3588 }
3589
3590 for (uint32_t i = 0; i < info->groupCount; i++) {
3591 const VkRayTracingShaderGroupCreateInfoKHR *ginfo = &info->pGroups[i];
3592
3593 if (ginfo->type != VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR)
3594 continue;
3595
3596 int64_t stage_start = os_time_get_nano();
3597
3598 uint32_t intersection_idx = ginfo->intersectionShader;
3599 assert(intersection_idx < info->stageCount);
3600
3601 uint32_t any_hit_idx = ginfo->anyHitShader;
3602 if (any_hit_idx != VK_SHADER_UNUSED_KHR) {
3603 assert(any_hit_idx < info->stageCount);
3604 anv_pipeline_hash_ray_tracing_combined_shader(pipeline,
3605 &stages[intersection_idx],
3606 &stages[any_hit_idx],
3607 stages[intersection_idx].cache_key.sha1);
3608 } else {
3609 anv_pipeline_hash_ray_tracing_shader(pipeline,
3610 &stages[intersection_idx],
3611 stages[intersection_idx].cache_key.sha1);
3612 }
3613
3614 stages[intersection_idx].feedback.duration += os_time_get_nano() - stage_start;
3615 }
3616
3617 return stages;
3618 }
3619
3620 static bool
anv_ray_tracing_pipeline_load_cached_shaders(struct anv_ray_tracing_pipeline * pipeline,struct vk_pipeline_cache * cache,const VkRayTracingPipelineCreateInfoKHR * info,struct anv_pipeline_stage * stages)3621 anv_ray_tracing_pipeline_load_cached_shaders(struct anv_ray_tracing_pipeline *pipeline,
3622 struct vk_pipeline_cache *cache,
3623 const VkRayTracingPipelineCreateInfoKHR *info,
3624 struct anv_pipeline_stage *stages)
3625 {
3626 uint32_t shaders = 0, cache_hits = 0;
3627 for (uint32_t i = 0; i < info->stageCount; i++) {
3628 if (stages[i].info == NULL)
3629 continue;
3630
3631 shaders++;
3632
3633 int64_t stage_start = os_time_get_nano();
3634
3635 bool cache_hit;
3636 stages[i].bin = anv_device_search_for_kernel(pipeline->base.device, cache,
3637 &stages[i].cache_key,
3638 sizeof(stages[i].cache_key),
3639 &cache_hit);
3640 if (cache_hit) {
3641 cache_hits++;
3642 stages[i].feedback.flags |=
3643 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
3644 }
3645
3646 if (stages[i].bin != NULL)
3647 anv_pipeline_add_executables(&pipeline->base, &stages[i]);
3648
3649 stages[i].feedback.duration += os_time_get_nano() - stage_start;
3650 }
3651
3652 return cache_hits == shaders;
3653 }
3654
3655 static VkResult
anv_pipeline_compile_ray_tracing(struct anv_ray_tracing_pipeline * pipeline,void * tmp_pipeline_ctx,struct anv_pipeline_stage * stages,struct vk_pipeline_cache * cache,const VkRayTracingPipelineCreateInfoKHR * info)3656 anv_pipeline_compile_ray_tracing(struct anv_ray_tracing_pipeline *pipeline,
3657 void *tmp_pipeline_ctx,
3658 struct anv_pipeline_stage *stages,
3659 struct vk_pipeline_cache *cache,
3660 const VkRayTracingPipelineCreateInfoKHR *info)
3661 {
3662 const struct intel_device_info *devinfo = pipeline->base.device->info;
3663 VkResult result;
3664
3665 VkPipelineCreationFeedback pipeline_feedback = {
3666 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
3667 };
3668 int64_t pipeline_start = os_time_get_nano();
3669
3670 const bool skip_cache_lookup =
3671 (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
3672
3673 if (!skip_cache_lookup &&
3674 anv_ray_tracing_pipeline_load_cached_shaders(pipeline, cache, info, stages)) {
3675 pipeline_feedback.flags |=
3676 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
3677 goto done;
3678 }
3679
3680 if (pipeline->base.flags & VK_PIPELINE_CREATE_2_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_KHR)
3681 return VK_PIPELINE_COMPILE_REQUIRED;
3682
3683 for (uint32_t i = 0; i < info->stageCount; i++) {
3684 if (stages[i].info == NULL)
3685 continue;
3686
3687 int64_t stage_start = os_time_get_nano();
3688
3689 VkResult result = anv_pipeline_stage_get_nir(&pipeline->base, cache,
3690 tmp_pipeline_ctx,
3691 &stages[i]);
3692 if (result != VK_SUCCESS)
3693 return result;
3694
3695 anv_pipeline_nir_preprocess(&pipeline->base, &stages[i]);
3696
3697 anv_pipeline_lower_nir(&pipeline->base, tmp_pipeline_ctx, &stages[i],
3698 &pipeline->base.layout, 0 /* view_mask */,
3699 false /* use_primitive_replication */);
3700
3701 stages[i].feedback.duration += os_time_get_nano() - stage_start;
3702 }
3703
3704 for (uint32_t i = 0; i < info->stageCount; i++) {
3705 if (stages[i].info == NULL)
3706 continue;
3707
3708 /* Shader found in cache already. */
3709 if (stages[i].bin != NULL)
3710 continue;
3711
3712 /* We handle intersection shaders as part of the group */
3713 if (stages[i].stage == MESA_SHADER_INTERSECTION)
3714 continue;
3715
3716 int64_t stage_start = os_time_get_nano();
3717
3718 void *tmp_stage_ctx = ralloc_context(tmp_pipeline_ctx);
3719
3720 nir_shader *nir = nir_shader_clone(tmp_stage_ctx, stages[i].nir);
3721 switch (stages[i].stage) {
3722 case MESA_SHADER_RAYGEN:
3723 brw_nir_lower_raygen(nir);
3724 break;
3725
3726 case MESA_SHADER_ANY_HIT:
3727 brw_nir_lower_any_hit(nir, devinfo);
3728 break;
3729
3730 case MESA_SHADER_CLOSEST_HIT:
3731 brw_nir_lower_closest_hit(nir);
3732 break;
3733
3734 case MESA_SHADER_MISS:
3735 brw_nir_lower_miss(nir);
3736 break;
3737
3738 case MESA_SHADER_INTERSECTION:
3739 unreachable("These are handled later");
3740
3741 case MESA_SHADER_CALLABLE:
3742 brw_nir_lower_callable(nir);
3743 break;
3744
3745 default:
3746 unreachable("Invalid ray-tracing shader stage");
3747 }
3748
3749 result = compile_upload_rt_shader(pipeline, cache, nir, &stages[i],
3750 tmp_stage_ctx);
3751 if (result != VK_SUCCESS) {
3752 ralloc_free(tmp_stage_ctx);
3753 return result;
3754 }
3755
3756 ralloc_free(tmp_stage_ctx);
3757
3758 stages[i].feedback.duration += os_time_get_nano() - stage_start;
3759 }
3760
3761 done:
3762 for (uint32_t i = 0; i < info->groupCount; i++) {
3763 const VkRayTracingShaderGroupCreateInfoKHR *ginfo = &info->pGroups[i];
3764 struct anv_rt_shader_group *group = &pipeline->groups[i];
3765 group->type = ginfo->type;
3766 switch (ginfo->type) {
3767 case VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR:
3768 assert(ginfo->generalShader < info->stageCount);
3769 group->general = stages[ginfo->generalShader].bin;
3770 break;
3771
3772 case VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR:
3773 if (ginfo->anyHitShader < info->stageCount)
3774 group->any_hit = stages[ginfo->anyHitShader].bin;
3775
3776 if (ginfo->closestHitShader < info->stageCount)
3777 group->closest_hit = stages[ginfo->closestHitShader].bin;
3778 break;
3779
3780 case VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR: {
3781 if (ginfo->closestHitShader < info->stageCount)
3782 group->closest_hit = stages[ginfo->closestHitShader].bin;
3783
3784 uint32_t intersection_idx = info->pGroups[i].intersectionShader;
3785 assert(intersection_idx < info->stageCount);
3786
3787 /* Only compile this stage if not already found in the cache. */
3788 if (stages[intersection_idx].bin == NULL) {
3789 /* The any-hit and intersection shader have to be combined */
3790 uint32_t any_hit_idx = info->pGroups[i].anyHitShader;
3791 const nir_shader *any_hit = NULL;
3792 if (any_hit_idx < info->stageCount)
3793 any_hit = stages[any_hit_idx].nir;
3794
3795 void *tmp_group_ctx = ralloc_context(tmp_pipeline_ctx);
3796 nir_shader *intersection =
3797 nir_shader_clone(tmp_group_ctx, stages[intersection_idx].nir);
3798
3799 brw_nir_lower_combined_intersection_any_hit(intersection, any_hit,
3800 devinfo);
3801
3802 result = compile_upload_rt_shader(pipeline, cache,
3803 intersection,
3804 &stages[intersection_idx],
3805 tmp_group_ctx);
3806 ralloc_free(tmp_group_ctx);
3807 if (result != VK_SUCCESS)
3808 return result;
3809 }
3810
3811 group->intersection = stages[intersection_idx].bin;
3812 break;
3813 }
3814
3815 default:
3816 unreachable("Invalid ray tracing shader group type");
3817 }
3818 }
3819
3820 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
3821
3822 const VkPipelineCreationFeedbackCreateInfo *create_feedback =
3823 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO);
3824 if (create_feedback) {
3825 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
3826
3827 uint32_t stage_count = create_feedback->pipelineStageCreationFeedbackCount;
3828 assert(stage_count == 0 || info->stageCount == stage_count);
3829 for (uint32_t i = 0; i < stage_count; i++) {
3830 gl_shader_stage s = vk_to_mesa_shader_stage(info->pStages[i].stage);
3831 create_feedback->pPipelineStageCreationFeedbacks[i] = stages[s].feedback;
3832 }
3833 }
3834
3835 return VK_SUCCESS;
3836 }
3837
3838 VkResult
anv_device_init_rt_shaders(struct anv_device * device)3839 anv_device_init_rt_shaders(struct anv_device *device)
3840 {
3841 device->bvh_build_method = ANV_BVH_BUILD_METHOD_NEW_SAH;
3842
3843 if (!device->vk.enabled_extensions.KHR_ray_tracing_pipeline)
3844 return VK_SUCCESS;
3845
3846 bool cache_hit;
3847
3848 struct anv_push_descriptor_info empty_push_desc_info = {};
3849 struct anv_pipeline_bind_map empty_bind_map = {};
3850 struct brw_rt_trampoline {
3851 char name[16];
3852 struct brw_cs_prog_key key;
3853 } trampoline_key = {
3854 .name = "rt-trampoline",
3855 };
3856 device->rt_trampoline =
3857 anv_device_search_for_kernel(device, device->internal_cache,
3858 &trampoline_key, sizeof(trampoline_key),
3859 &cache_hit);
3860 if (device->rt_trampoline == NULL) {
3861
3862 void *tmp_ctx = ralloc_context(NULL);
3863 nir_shader *trampoline_nir =
3864 brw_nir_create_raygen_trampoline(device->physical->compiler, tmp_ctx);
3865
3866 trampoline_nir->info.subgroup_size = SUBGROUP_SIZE_REQUIRE_16;
3867
3868 uint32_t dummy_params[4] = { 0, };
3869 struct brw_cs_prog_data trampoline_prog_data = {
3870 .base.nr_params = 4,
3871 .base.param = dummy_params,
3872 .uses_inline_data = true,
3873 .uses_btd_stack_ids = true,
3874 };
3875 struct brw_compile_cs_params params = {
3876 .base = {
3877 .nir = trampoline_nir,
3878 .log_data = device,
3879 .mem_ctx = tmp_ctx,
3880 },
3881 .key = &trampoline_key.key,
3882 .prog_data = &trampoline_prog_data,
3883 };
3884 const unsigned *tramp_data =
3885 brw_compile_cs(device->physical->compiler, ¶ms);
3886
3887 struct anv_shader_upload_params upload_params = {
3888 .stage = MESA_SHADER_COMPUTE,
3889 .key_data = &trampoline_key,
3890 .key_size = sizeof(trampoline_key),
3891 .kernel_data = tramp_data,
3892 .kernel_size = trampoline_prog_data.base.program_size,
3893 .prog_data = &trampoline_prog_data.base,
3894 .prog_data_size = sizeof(trampoline_prog_data),
3895 .bind_map = &empty_bind_map,
3896 .push_desc_info = &empty_push_desc_info,
3897 };
3898
3899 device->rt_trampoline =
3900 anv_device_upload_kernel(device, device->internal_cache,
3901 &upload_params);
3902
3903 ralloc_free(tmp_ctx);
3904
3905 if (device->rt_trampoline == NULL)
3906 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
3907 }
3908
3909 /* The cache already has a reference and it's not going anywhere so there
3910 * is no need to hold a second reference.
3911 */
3912 anv_shader_bin_unref(device, device->rt_trampoline);
3913
3914 struct brw_rt_trivial_return {
3915 char name[16];
3916 struct brw_bs_prog_key key;
3917 } return_key = {
3918 .name = "rt-trivial-ret",
3919 };
3920 device->rt_trivial_return =
3921 anv_device_search_for_kernel(device, device->internal_cache,
3922 &return_key, sizeof(return_key),
3923 &cache_hit);
3924 if (device->rt_trivial_return == NULL) {
3925 void *tmp_ctx = ralloc_context(NULL);
3926 nir_shader *trivial_return_nir =
3927 brw_nir_create_trivial_return_shader(device->physical->compiler, tmp_ctx);
3928
3929 NIR_PASS_V(trivial_return_nir, brw_nir_lower_rt_intrinsics, device->info);
3930
3931 struct brw_bs_prog_data return_prog_data = { 0, };
3932 struct brw_compile_bs_params params = {
3933 .base = {
3934 .nir = trivial_return_nir,
3935 .log_data = device,
3936 .mem_ctx = tmp_ctx,
3937 },
3938 .key = &return_key.key,
3939 .prog_data = &return_prog_data,
3940 };
3941 const unsigned *return_data =
3942 brw_compile_bs(device->physical->compiler, ¶ms);
3943
3944 struct anv_shader_upload_params upload_params = {
3945 .stage = MESA_SHADER_CALLABLE,
3946 .key_data = &return_key,
3947 .key_size = sizeof(return_key),
3948 .kernel_data = return_data,
3949 .kernel_size = return_prog_data.base.program_size,
3950 .prog_data = &return_prog_data.base,
3951 .prog_data_size = sizeof(return_prog_data),
3952 .bind_map = &empty_bind_map,
3953 .push_desc_info = &empty_push_desc_info,
3954 };
3955
3956 device->rt_trivial_return =
3957 anv_device_upload_kernel(device, device->internal_cache,
3958 &upload_params);
3959
3960 ralloc_free(tmp_ctx);
3961
3962 if (device->rt_trivial_return == NULL)
3963 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
3964 }
3965
3966 /* The cache already has a reference and it's not going anywhere so there
3967 * is no need to hold a second reference.
3968 */
3969 anv_shader_bin_unref(device, device->rt_trivial_return);
3970
3971 return VK_SUCCESS;
3972 }
3973
3974 void
anv_device_finish_rt_shaders(struct anv_device * device)3975 anv_device_finish_rt_shaders(struct anv_device *device)
3976 {
3977 if (!device->vk.enabled_extensions.KHR_ray_tracing_pipeline)
3978 return;
3979 }
3980
3981 static void
anv_ray_tracing_pipeline_init(struct anv_ray_tracing_pipeline * pipeline,struct anv_device * device,struct vk_pipeline_cache * cache,const VkRayTracingPipelineCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * alloc)3982 anv_ray_tracing_pipeline_init(struct anv_ray_tracing_pipeline *pipeline,
3983 struct anv_device *device,
3984 struct vk_pipeline_cache *cache,
3985 const VkRayTracingPipelineCreateInfoKHR *pCreateInfo,
3986 const VkAllocationCallbacks *alloc)
3987 {
3988 util_dynarray_init(&pipeline->shaders, pipeline->base.mem_ctx);
3989
3990 ANV_FROM_HANDLE(anv_pipeline_layout, pipeline_layout, pCreateInfo->layout);
3991 anv_pipeline_init_layout(&pipeline->base, pipeline_layout);
3992
3993 anv_pipeline_setup_l3_config(&pipeline->base, /* needs_slm */ false);
3994 }
3995
3996 static void
assert_rt_stage_index_valid(const VkRayTracingPipelineCreateInfoKHR * pCreateInfo,uint32_t stage_idx,VkShaderStageFlags valid_stages)3997 assert_rt_stage_index_valid(const VkRayTracingPipelineCreateInfoKHR* pCreateInfo,
3998 uint32_t stage_idx,
3999 VkShaderStageFlags valid_stages)
4000 {
4001 if (stage_idx == VK_SHADER_UNUSED_KHR)
4002 return;
4003
4004 assert(stage_idx <= pCreateInfo->stageCount);
4005 assert(util_bitcount(pCreateInfo->pStages[stage_idx].stage) == 1);
4006 assert(pCreateInfo->pStages[stage_idx].stage & valid_stages);
4007 }
4008
4009 static VkResult
anv_ray_tracing_pipeline_create(VkDevice _device,struct vk_pipeline_cache * cache,const VkRayTracingPipelineCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)4010 anv_ray_tracing_pipeline_create(
4011 VkDevice _device,
4012 struct vk_pipeline_cache * cache,
4013 const VkRayTracingPipelineCreateInfoKHR* pCreateInfo,
4014 const VkAllocationCallbacks* pAllocator,
4015 VkPipeline* pPipeline)
4016 {
4017 ANV_FROM_HANDLE(anv_device, device, _device);
4018 VkResult result;
4019
4020 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR);
4021
4022 uint32_t group_count = pCreateInfo->groupCount;
4023 if (pCreateInfo->pLibraryInfo) {
4024 for (uint32_t l = 0; l < pCreateInfo->pLibraryInfo->libraryCount; l++) {
4025 ANV_FROM_HANDLE(anv_pipeline, library,
4026 pCreateInfo->pLibraryInfo->pLibraries[l]);
4027 struct anv_ray_tracing_pipeline *rt_library =
4028 anv_pipeline_to_ray_tracing(library);
4029 group_count += rt_library->group_count;
4030 }
4031 }
4032
4033 VK_MULTIALLOC(ma);
4034 VK_MULTIALLOC_DECL(&ma, struct anv_ray_tracing_pipeline, pipeline, 1);
4035 VK_MULTIALLOC_DECL(&ma, struct anv_rt_shader_group, groups, group_count);
4036 if (!vk_multialloc_zalloc2(&ma, &device->vk.alloc, pAllocator,
4037 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE))
4038 return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
4039
4040 result = anv_pipeline_init(&pipeline->base, device,
4041 ANV_PIPELINE_RAY_TRACING,
4042 vk_rt_pipeline_create_flags(pCreateInfo),
4043 pAllocator);
4044 if (result != VK_SUCCESS) {
4045 vk_free2(&device->vk.alloc, pAllocator, pipeline);
4046 return result;
4047 }
4048
4049 pipeline->group_count = group_count;
4050 pipeline->groups = groups;
4051
4052 ASSERTED const VkShaderStageFlags ray_tracing_stages =
4053 VK_SHADER_STAGE_RAYGEN_BIT_KHR |
4054 VK_SHADER_STAGE_ANY_HIT_BIT_KHR |
4055 VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR |
4056 VK_SHADER_STAGE_MISS_BIT_KHR |
4057 VK_SHADER_STAGE_INTERSECTION_BIT_KHR |
4058 VK_SHADER_STAGE_CALLABLE_BIT_KHR;
4059
4060 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++)
4061 assert((pCreateInfo->pStages[i].stage & ~ray_tracing_stages) == 0);
4062
4063 for (uint32_t i = 0; i < pCreateInfo->groupCount; i++) {
4064 const VkRayTracingShaderGroupCreateInfoKHR *ginfo =
4065 &pCreateInfo->pGroups[i];
4066 assert_rt_stage_index_valid(pCreateInfo, ginfo->generalShader,
4067 VK_SHADER_STAGE_RAYGEN_BIT_KHR |
4068 VK_SHADER_STAGE_MISS_BIT_KHR |
4069 VK_SHADER_STAGE_CALLABLE_BIT_KHR);
4070 assert_rt_stage_index_valid(pCreateInfo, ginfo->closestHitShader,
4071 VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR);
4072 assert_rt_stage_index_valid(pCreateInfo, ginfo->anyHitShader,
4073 VK_SHADER_STAGE_ANY_HIT_BIT_KHR);
4074 assert_rt_stage_index_valid(pCreateInfo, ginfo->intersectionShader,
4075 VK_SHADER_STAGE_INTERSECTION_BIT_KHR);
4076 switch (ginfo->type) {
4077 case VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR:
4078 assert(ginfo->generalShader < pCreateInfo->stageCount);
4079 assert(ginfo->anyHitShader == VK_SHADER_UNUSED_KHR);
4080 assert(ginfo->closestHitShader == VK_SHADER_UNUSED_KHR);
4081 assert(ginfo->intersectionShader == VK_SHADER_UNUSED_KHR);
4082 break;
4083
4084 case VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR:
4085 assert(ginfo->generalShader == VK_SHADER_UNUSED_KHR);
4086 assert(ginfo->intersectionShader == VK_SHADER_UNUSED_KHR);
4087 break;
4088
4089 case VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR:
4090 assert(ginfo->generalShader == VK_SHADER_UNUSED_KHR);
4091 break;
4092
4093 default:
4094 unreachable("Invalid ray-tracing shader group type");
4095 }
4096 }
4097
4098 anv_ray_tracing_pipeline_init(pipeline, device, cache,
4099 pCreateInfo, pAllocator);
4100
4101 void *tmp_ctx = ralloc_context(NULL);
4102
4103 struct anv_pipeline_stage *stages =
4104 anv_pipeline_init_ray_tracing_stages(pipeline, pCreateInfo, tmp_ctx);
4105
4106 result = anv_pipeline_compile_ray_tracing(pipeline, tmp_ctx, stages,
4107 cache, pCreateInfo);
4108 if (result != VK_SUCCESS) {
4109 ralloc_free(tmp_ctx);
4110 util_dynarray_foreach(&pipeline->shaders, struct anv_shader_bin *, shader)
4111 anv_shader_bin_unref(device, *shader);
4112 anv_pipeline_finish(&pipeline->base, device);
4113 vk_free2(&device->vk.alloc, pAllocator, pipeline);
4114 return result;
4115 }
4116
4117 /* Compute the size of the scratch BO (for register spilling) by taking the
4118 * max of all the shaders in the pipeline. Also add the shaders to the list
4119 * of executables.
4120 */
4121 uint32_t stack_max[MESA_VULKAN_SHADER_STAGES] = {};
4122 for (uint32_t s = 0; s < pCreateInfo->stageCount; s++) {
4123 util_dynarray_append(&pipeline->shaders,
4124 struct anv_shader_bin *,
4125 stages[s].bin);
4126
4127 uint32_t stack_size =
4128 brw_bs_prog_data_const(stages[s].bin->prog_data)->max_stack_size;
4129 stack_max[stages[s].stage] = MAX2(stack_max[stages[s].stage], stack_size);
4130
4131 anv_pipeline_account_shader(&pipeline->base, stages[s].bin);
4132 }
4133
4134 anv_pipeline_compute_ray_tracing_stacks(pipeline, pCreateInfo, stack_max);
4135
4136 if (pCreateInfo->pLibraryInfo) {
4137 uint32_t g = pCreateInfo->groupCount;
4138 for (uint32_t l = 0; l < pCreateInfo->pLibraryInfo->libraryCount; l++) {
4139 ANV_FROM_HANDLE(anv_pipeline, library,
4140 pCreateInfo->pLibraryInfo->pLibraries[l]);
4141 struct anv_ray_tracing_pipeline *rt_library =
4142 anv_pipeline_to_ray_tracing(library);
4143 for (uint32_t lg = 0; lg < rt_library->group_count; lg++) {
4144 pipeline->groups[g] = rt_library->groups[lg];
4145 pipeline->groups[g].imported = true;
4146 g++;
4147 }
4148
4149 /* Account for shaders in the library. */
4150 util_dynarray_foreach(&rt_library->shaders,
4151 struct anv_shader_bin *, shader) {
4152 util_dynarray_append(&pipeline->shaders,
4153 struct anv_shader_bin *,
4154 anv_shader_bin_ref(*shader));
4155 anv_pipeline_account_shader(&pipeline->base, *shader);
4156 }
4157
4158 /* Add the library shaders to this pipeline's executables. */
4159 util_dynarray_foreach(&rt_library->base.executables,
4160 struct anv_pipeline_executable, exe) {
4161 util_dynarray_append(&pipeline->base.executables,
4162 struct anv_pipeline_executable, *exe);
4163 }
4164
4165 pipeline->base.active_stages |= rt_library->base.active_stages;
4166 }
4167 }
4168
4169 anv_genX(device->info, ray_tracing_pipeline_emit)(pipeline);
4170
4171 ralloc_free(tmp_ctx);
4172
4173 ANV_RMV(rt_pipeline_create, device, pipeline, false);
4174
4175 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
4176
4177 return pipeline->base.batch.status;
4178 }
4179
4180 VkResult
anv_CreateRayTracingPipelinesKHR(VkDevice _device,VkDeferredOperationKHR deferredOperation,VkPipelineCache pipelineCache,uint32_t createInfoCount,const VkRayTracingPipelineCreateInfoKHR * pCreateInfos,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipelines)4181 anv_CreateRayTracingPipelinesKHR(
4182 VkDevice _device,
4183 VkDeferredOperationKHR deferredOperation,
4184 VkPipelineCache pipelineCache,
4185 uint32_t createInfoCount,
4186 const VkRayTracingPipelineCreateInfoKHR* pCreateInfos,
4187 const VkAllocationCallbacks* pAllocator,
4188 VkPipeline* pPipelines)
4189 {
4190 ANV_FROM_HANDLE(vk_pipeline_cache, pipeline_cache, pipelineCache);
4191
4192 VkResult result = VK_SUCCESS;
4193
4194 unsigned i;
4195 for (i = 0; i < createInfoCount; i++) {
4196 const VkPipelineCreateFlags2KHR flags =
4197 vk_rt_pipeline_create_flags(&pCreateInfos[i]);
4198 VkResult res = anv_ray_tracing_pipeline_create(_device, pipeline_cache,
4199 &pCreateInfos[i],
4200 pAllocator, &pPipelines[i]);
4201
4202 if (res != VK_SUCCESS) {
4203 result = res;
4204 if (flags & VK_PIPELINE_CREATE_2_EARLY_RETURN_ON_FAILURE_BIT_KHR)
4205 break;
4206 pPipelines[i] = VK_NULL_HANDLE;
4207 }
4208 }
4209
4210 for (; i < createInfoCount; i++)
4211 pPipelines[i] = VK_NULL_HANDLE;
4212
4213 return result;
4214 }
4215
4216 #define WRITE_STR(field, ...) ({ \
4217 memset(field, 0, sizeof(field)); \
4218 UNUSED int i = snprintf(field, sizeof(field), __VA_ARGS__); \
4219 assert(i > 0 && i < sizeof(field)); \
4220 })
4221
anv_GetPipelineExecutablePropertiesKHR(VkDevice device,const VkPipelineInfoKHR * pPipelineInfo,uint32_t * pExecutableCount,VkPipelineExecutablePropertiesKHR * pProperties)4222 VkResult anv_GetPipelineExecutablePropertiesKHR(
4223 VkDevice device,
4224 const VkPipelineInfoKHR* pPipelineInfo,
4225 uint32_t* pExecutableCount,
4226 VkPipelineExecutablePropertiesKHR* pProperties)
4227 {
4228 ANV_FROM_HANDLE(anv_pipeline, pipeline, pPipelineInfo->pipeline);
4229 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutablePropertiesKHR, out,
4230 pProperties, pExecutableCount);
4231
4232 util_dynarray_foreach (&pipeline->executables, struct anv_pipeline_executable, exe) {
4233 vk_outarray_append_typed(VkPipelineExecutablePropertiesKHR, &out, props) {
4234 gl_shader_stage stage = exe->stage;
4235 props->stages = mesa_to_vk_shader_stage(stage);
4236
4237 unsigned simd_width = exe->stats.dispatch_width;
4238 if (stage == MESA_SHADER_FRAGMENT) {
4239 if (exe->stats.max_polygons > 1)
4240 WRITE_STR(props->name, "SIMD%dx%d %s",
4241 exe->stats.max_polygons,
4242 simd_width / exe->stats.max_polygons,
4243 _mesa_shader_stage_to_string(stage));
4244 else
4245 WRITE_STR(props->name, "%s%d %s",
4246 simd_width ? "SIMD" : "vec",
4247 simd_width ? simd_width : 4,
4248 _mesa_shader_stage_to_string(stage));
4249 } else {
4250 WRITE_STR(props->name, "%s", _mesa_shader_stage_to_string(stage));
4251 }
4252 WRITE_STR(props->description, "%s%d %s shader",
4253 simd_width ? "SIMD" : "vec",
4254 simd_width ? simd_width : 4,
4255 _mesa_shader_stage_to_string(stage));
4256
4257 /* The compiler gives us a dispatch width of 0 for vec4 but Vulkan
4258 * wants a subgroup size of 1.
4259 */
4260 props->subgroupSize = MAX2(simd_width, 1);
4261 }
4262 }
4263
4264 return vk_outarray_status(&out);
4265 }
4266
4267 static const struct anv_pipeline_executable *
anv_pipeline_get_executable(struct anv_pipeline * pipeline,uint32_t index)4268 anv_pipeline_get_executable(struct anv_pipeline *pipeline, uint32_t index)
4269 {
4270 assert(index < util_dynarray_num_elements(&pipeline->executables,
4271 struct anv_pipeline_executable));
4272 return util_dynarray_element(
4273 &pipeline->executables, struct anv_pipeline_executable, index);
4274 }
4275
anv_GetPipelineExecutableStatisticsKHR(VkDevice device,const VkPipelineExecutableInfoKHR * pExecutableInfo,uint32_t * pStatisticCount,VkPipelineExecutableStatisticKHR * pStatistics)4276 VkResult anv_GetPipelineExecutableStatisticsKHR(
4277 VkDevice device,
4278 const VkPipelineExecutableInfoKHR* pExecutableInfo,
4279 uint32_t* pStatisticCount,
4280 VkPipelineExecutableStatisticKHR* pStatistics)
4281 {
4282 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
4283 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutableStatisticKHR, out,
4284 pStatistics, pStatisticCount);
4285
4286 const struct anv_pipeline_executable *exe =
4287 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
4288
4289 const struct brw_stage_prog_data *prog_data;
4290 switch (pipeline->type) {
4291 case ANV_PIPELINE_GRAPHICS:
4292 case ANV_PIPELINE_GRAPHICS_LIB: {
4293 prog_data = anv_pipeline_to_graphics_base(pipeline)->shaders[exe->stage]->prog_data;
4294 break;
4295 }
4296 case ANV_PIPELINE_COMPUTE: {
4297 prog_data = anv_pipeline_to_compute(pipeline)->cs->prog_data;
4298 break;
4299 }
4300 case ANV_PIPELINE_RAY_TRACING: {
4301 struct anv_shader_bin **shader =
4302 util_dynarray_element(&anv_pipeline_to_ray_tracing(pipeline)->shaders,
4303 struct anv_shader_bin *,
4304 pExecutableInfo->executableIndex);
4305 prog_data = (*shader)->prog_data;
4306 break;
4307 }
4308 default:
4309 unreachable("invalid pipeline type");
4310 }
4311
4312 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4313 WRITE_STR(stat->name, "Instruction Count");
4314 WRITE_STR(stat->description,
4315 "Number of GEN instructions in the final generated "
4316 "shader executable.");
4317 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4318 stat->value.u64 = exe->stats.instructions;
4319 }
4320
4321 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4322 WRITE_STR(stat->name, "SEND Count");
4323 WRITE_STR(stat->description,
4324 "Number of instructions in the final generated shader "
4325 "executable which access external units such as the "
4326 "constant cache or the sampler.");
4327 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4328 stat->value.u64 = exe->stats.sends;
4329 }
4330
4331 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4332 WRITE_STR(stat->name, "Loop Count");
4333 WRITE_STR(stat->description,
4334 "Number of loops (not unrolled) in the final generated "
4335 "shader executable.");
4336 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4337 stat->value.u64 = exe->stats.loops;
4338 }
4339
4340 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4341 WRITE_STR(stat->name, "Cycle Count");
4342 WRITE_STR(stat->description,
4343 "Estimate of the number of EU cycles required to execute "
4344 "the final generated executable. This is an estimate only "
4345 "and may vary greatly from actual run-time performance.");
4346 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4347 stat->value.u64 = exe->stats.cycles;
4348 }
4349
4350 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4351 WRITE_STR(stat->name, "Spill Count");
4352 WRITE_STR(stat->description,
4353 "Number of scratch spill operations. This gives a rough "
4354 "estimate of the cost incurred due to spilling temporary "
4355 "values to memory. If this is non-zero, you may want to "
4356 "adjust your shader to reduce register pressure.");
4357 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4358 stat->value.u64 = exe->stats.spills;
4359 }
4360
4361 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4362 WRITE_STR(stat->name, "Fill Count");
4363 WRITE_STR(stat->description,
4364 "Number of scratch fill operations. This gives a rough "
4365 "estimate of the cost incurred due to spilling temporary "
4366 "values to memory. If this is non-zero, you may want to "
4367 "adjust your shader to reduce register pressure.");
4368 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4369 stat->value.u64 = exe->stats.fills;
4370 }
4371
4372 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4373 WRITE_STR(stat->name, "Scratch Memory Size");
4374 WRITE_STR(stat->description,
4375 "Number of bytes of scratch memory required by the "
4376 "generated shader executable. If this is non-zero, you "
4377 "may want to adjust your shader to reduce register "
4378 "pressure.");
4379 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4380 stat->value.u64 = prog_data->total_scratch;
4381 }
4382
4383 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4384 WRITE_STR(stat->name, "Max dispatch width");
4385 WRITE_STR(stat->description,
4386 "Largest SIMD dispatch width.");
4387 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4388 /* Report the max dispatch width only on the smallest SIMD variant */
4389 if (exe->stage != MESA_SHADER_FRAGMENT || exe->stats.dispatch_width == 8)
4390 stat->value.u64 = exe->stats.max_dispatch_width;
4391 else
4392 stat->value.u64 = 0;
4393 }
4394
4395 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4396 WRITE_STR(stat->name, "Max live registers");
4397 WRITE_STR(stat->description,
4398 "Maximum number of registers used across the entire shader.");
4399 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4400 stat->value.u64 = exe->stats.max_live_registers;
4401 }
4402
4403 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4404 WRITE_STR(stat->name, "Workgroup Memory Size");
4405 WRITE_STR(stat->description,
4406 "Number of bytes of workgroup shared memory used by this "
4407 "shader including any padding.");
4408 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4409 if (gl_shader_stage_uses_workgroup(exe->stage))
4410 stat->value.u64 = prog_data->total_shared;
4411 else
4412 stat->value.u64 = 0;
4413 }
4414
4415 vk_outarray_append_typed(VkPipelineExecutableStatisticKHR, &out, stat) {
4416 uint32_t hash = pipeline->type == ANV_PIPELINE_COMPUTE ?
4417 anv_pipeline_to_compute(pipeline)->source_hash :
4418 (pipeline->type == ANV_PIPELINE_GRAPHICS_LIB ||
4419 pipeline->type == ANV_PIPELINE_GRAPHICS) ?
4420 anv_pipeline_to_graphics_base(pipeline)->source_hashes[exe->stage] :
4421 0 /* No source hash for ray tracing */;
4422 WRITE_STR(stat->name, "Source hash");
4423 WRITE_STR(stat->description,
4424 "hash = 0x%08x. Hash generated from shader source.", hash);
4425 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
4426 stat->value.u64 = hash;
4427 }
4428
4429 return vk_outarray_status(&out);
4430 }
4431
4432 static bool
write_ir_text(VkPipelineExecutableInternalRepresentationKHR * ir,const char * data)4433 write_ir_text(VkPipelineExecutableInternalRepresentationKHR* ir,
4434 const char *data)
4435 {
4436 ir->isText = VK_TRUE;
4437
4438 size_t data_len = strlen(data) + 1;
4439
4440 if (ir->pData == NULL) {
4441 ir->dataSize = data_len;
4442 return true;
4443 }
4444
4445 strncpy(ir->pData, data, ir->dataSize);
4446 if (ir->dataSize < data_len)
4447 return false;
4448
4449 ir->dataSize = data_len;
4450 return true;
4451 }
4452
anv_GetPipelineExecutableInternalRepresentationsKHR(VkDevice device,const VkPipelineExecutableInfoKHR * pExecutableInfo,uint32_t * pInternalRepresentationCount,VkPipelineExecutableInternalRepresentationKHR * pInternalRepresentations)4453 VkResult anv_GetPipelineExecutableInternalRepresentationsKHR(
4454 VkDevice device,
4455 const VkPipelineExecutableInfoKHR* pExecutableInfo,
4456 uint32_t* pInternalRepresentationCount,
4457 VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations)
4458 {
4459 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
4460 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutableInternalRepresentationKHR, out,
4461 pInternalRepresentations, pInternalRepresentationCount);
4462 bool incomplete_text = false;
4463
4464 const struct anv_pipeline_executable *exe =
4465 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
4466
4467 if (exe->nir) {
4468 vk_outarray_append_typed(VkPipelineExecutableInternalRepresentationKHR, &out, ir) {
4469 WRITE_STR(ir->name, "Final NIR");
4470 WRITE_STR(ir->description,
4471 "Final NIR before going into the back-end compiler");
4472
4473 if (!write_ir_text(ir, exe->nir))
4474 incomplete_text = true;
4475 }
4476 }
4477
4478 if (exe->disasm) {
4479 vk_outarray_append_typed(VkPipelineExecutableInternalRepresentationKHR, &out, ir) {
4480 WRITE_STR(ir->name, "GEN Assembly");
4481 WRITE_STR(ir->description,
4482 "Final GEN assembly for the generated shader binary");
4483
4484 if (!write_ir_text(ir, exe->disasm))
4485 incomplete_text = true;
4486 }
4487 }
4488
4489 return incomplete_text ? VK_INCOMPLETE : vk_outarray_status(&out);
4490 }
4491
4492 VkResult
anv_GetRayTracingShaderGroupHandlesKHR(VkDevice _device,VkPipeline _pipeline,uint32_t firstGroup,uint32_t groupCount,size_t dataSize,void * pData)4493 anv_GetRayTracingShaderGroupHandlesKHR(
4494 VkDevice _device,
4495 VkPipeline _pipeline,
4496 uint32_t firstGroup,
4497 uint32_t groupCount,
4498 size_t dataSize,
4499 void* pData)
4500 {
4501 ANV_FROM_HANDLE(anv_device, device, _device);
4502 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
4503
4504 if (pipeline->type != ANV_PIPELINE_RAY_TRACING)
4505 return vk_error(device, VK_ERROR_FEATURE_NOT_PRESENT);
4506
4507 struct anv_ray_tracing_pipeline *rt_pipeline =
4508 anv_pipeline_to_ray_tracing(pipeline);
4509
4510 assert(firstGroup + groupCount <= rt_pipeline->group_count);
4511 for (uint32_t i = 0; i < groupCount; i++) {
4512 struct anv_rt_shader_group *group = &rt_pipeline->groups[firstGroup + i];
4513 memcpy(pData, group->handle, sizeof(group->handle));
4514 pData += sizeof(group->handle);
4515 }
4516
4517 return VK_SUCCESS;
4518 }
4519
4520 VkResult
anv_GetRayTracingCaptureReplayShaderGroupHandlesKHR(VkDevice _device,VkPipeline pipeline,uint32_t firstGroup,uint32_t groupCount,size_t dataSize,void * pData)4521 anv_GetRayTracingCaptureReplayShaderGroupHandlesKHR(
4522 VkDevice _device,
4523 VkPipeline pipeline,
4524 uint32_t firstGroup,
4525 uint32_t groupCount,
4526 size_t dataSize,
4527 void* pData)
4528 {
4529 ANV_FROM_HANDLE(anv_device, device, _device);
4530 unreachable("Unimplemented");
4531 return vk_error(device, VK_ERROR_FEATURE_NOT_PRESENT);
4532 }
4533
4534 VkDeviceSize
anv_GetRayTracingShaderGroupStackSizeKHR(VkDevice device,VkPipeline _pipeline,uint32_t group,VkShaderGroupShaderKHR groupShader)4535 anv_GetRayTracingShaderGroupStackSizeKHR(
4536 VkDevice device,
4537 VkPipeline _pipeline,
4538 uint32_t group,
4539 VkShaderGroupShaderKHR groupShader)
4540 {
4541 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
4542 assert(pipeline->type == ANV_PIPELINE_RAY_TRACING);
4543
4544 struct anv_ray_tracing_pipeline *rt_pipeline =
4545 anv_pipeline_to_ray_tracing(pipeline);
4546
4547 assert(group < rt_pipeline->group_count);
4548
4549 struct anv_shader_bin *bin;
4550 switch (groupShader) {
4551 case VK_SHADER_GROUP_SHADER_GENERAL_KHR:
4552 bin = rt_pipeline->groups[group].general;
4553 break;
4554
4555 case VK_SHADER_GROUP_SHADER_CLOSEST_HIT_KHR:
4556 bin = rt_pipeline->groups[group].closest_hit;
4557 break;
4558
4559 case VK_SHADER_GROUP_SHADER_ANY_HIT_KHR:
4560 bin = rt_pipeline->groups[group].any_hit;
4561 break;
4562
4563 case VK_SHADER_GROUP_SHADER_INTERSECTION_KHR:
4564 bin = rt_pipeline->groups[group].intersection;
4565 break;
4566
4567 default:
4568 unreachable("Invalid VkShaderGroupShader enum");
4569 }
4570
4571 if (bin == NULL)
4572 return 0;
4573
4574 return brw_bs_prog_data_const(bin->prog_data)->max_stack_size;
4575 }
4576