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