anv: Keep the shader stage in anv_shader_bin
[mesa.git] / src / intel / vulkan / anv_pipeline.c
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/gen_l3_config.h"
33 #include "common/gen_disasm.h"
34 #include "anv_private.h"
35 #include "compiler/brw_nir.h"
36 #include "anv_nir.h"
37 #include "nir/nir_xfb_info.h"
38 #include "spirv/nir_spirv.h"
39 #include "vk_util.h"
40
41 /* Needed for SWIZZLE macros */
42 #include "program/prog_instruction.h"
43
44 // Shader functions
45
46 VkResult anv_CreateShaderModule(
47 VkDevice _device,
48 const VkShaderModuleCreateInfo* pCreateInfo,
49 const VkAllocationCallbacks* pAllocator,
50 VkShaderModule* pShaderModule)
51 {
52 ANV_FROM_HANDLE(anv_device, device, _device);
53 struct anv_shader_module *module;
54
55 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
56 assert(pCreateInfo->flags == 0);
57
58 module = vk_alloc2(&device->alloc, pAllocator,
59 sizeof(*module) + pCreateInfo->codeSize, 8,
60 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
61 if (module == NULL)
62 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
63
64 module->size = pCreateInfo->codeSize;
65 memcpy(module->data, pCreateInfo->pCode, module->size);
66
67 _mesa_sha1_compute(module->data, module->size, module->sha1);
68
69 *pShaderModule = anv_shader_module_to_handle(module);
70
71 return VK_SUCCESS;
72 }
73
74 void anv_DestroyShaderModule(
75 VkDevice _device,
76 VkShaderModule _module,
77 const VkAllocationCallbacks* pAllocator)
78 {
79 ANV_FROM_HANDLE(anv_device, device, _device);
80 ANV_FROM_HANDLE(anv_shader_module, module, _module);
81
82 if (!module)
83 return;
84
85 vk_free2(&device->alloc, pAllocator, module);
86 }
87
88 #define SPIR_V_MAGIC_NUMBER 0x07230203
89
90 struct anv_spirv_debug_data {
91 struct anv_device *device;
92 const struct anv_shader_module *module;
93 };
94
95 static void anv_spirv_nir_debug(void *private_data,
96 enum nir_spirv_debug_level level,
97 size_t spirv_offset,
98 const char *message)
99 {
100 struct anv_spirv_debug_data *debug_data = private_data;
101 struct anv_instance *instance = debug_data->device->physical->instance;
102
103 static const VkDebugReportFlagsEXT vk_flags[] = {
104 [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
105 [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
106 [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
107 };
108 char buffer[256];
109
110 snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long) spirv_offset, message);
111
112 vk_debug_report(&instance->debug_report_callbacks,
113 vk_flags[level],
114 VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
115 (uint64_t) (uintptr_t) debug_data->module,
116 0, 0, "anv", buffer);
117 }
118
119 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
120 * we can't do that yet because we don't have the ability to copy nir.
121 */
122 static nir_shader *
123 anv_shader_compile_to_nir(struct anv_device *device,
124 void *mem_ctx,
125 const struct anv_shader_module *module,
126 const char *entrypoint_name,
127 gl_shader_stage stage,
128 const VkSpecializationInfo *spec_info)
129 {
130 const struct anv_physical_device *pdevice = device->physical;
131 const struct brw_compiler *compiler = pdevice->compiler;
132 const nir_shader_compiler_options *nir_options =
133 compiler->glsl_compiler_options[stage].NirOptions;
134
135 uint32_t *spirv = (uint32_t *) module->data;
136 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
137 assert(module->size % 4 == 0);
138
139 uint32_t num_spec_entries = 0;
140 struct nir_spirv_specialization *spec_entries = NULL;
141 if (spec_info && spec_info->mapEntryCount > 0) {
142 num_spec_entries = spec_info->mapEntryCount;
143 spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
144 for (uint32_t i = 0; i < num_spec_entries; i++) {
145 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
146 const void *data = spec_info->pData + entry.offset;
147 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
148
149 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
150 if (spec_info->dataSize == 8)
151 spec_entries[i].data64 = *(const uint64_t *)data;
152 else
153 spec_entries[i].data32 = *(const uint32_t *)data;
154 }
155 }
156
157 struct anv_spirv_debug_data spirv_debug_data = {
158 .device = device,
159 .module = module,
160 };
161 struct spirv_to_nir_options spirv_options = {
162 .frag_coord_is_sysval = true,
163 .caps = {
164 .demote_to_helper_invocation = true,
165 .derivative_group = true,
166 .descriptor_array_dynamic_indexing = true,
167 .descriptor_array_non_uniform_indexing = true,
168 .descriptor_indexing = true,
169 .device_group = true,
170 .draw_parameters = true,
171 .float16 = pdevice->info.gen >= 8,
172 .float64 = pdevice->info.gen >= 8,
173 .fragment_shader_sample_interlock = pdevice->info.gen >= 9,
174 .fragment_shader_pixel_interlock = pdevice->info.gen >= 9,
175 .geometry_streams = true,
176 .image_write_without_format = true,
177 .int8 = pdevice->info.gen >= 8,
178 .int16 = pdevice->info.gen >= 8,
179 .int64 = pdevice->info.gen >= 8,
180 .int64_atomics = pdevice->info.gen >= 9 && pdevice->use_softpin,
181 .integer_functions2 = pdevice->info.gen >= 8,
182 .min_lod = true,
183 .multiview = true,
184 .physical_storage_buffer_address = pdevice->has_a64_buffer_access,
185 .post_depth_coverage = pdevice->info.gen >= 9,
186 .runtime_descriptor_array = true,
187 .float_controls = pdevice->info.gen >= 8,
188 .shader_clock = true,
189 .shader_viewport_index_layer = true,
190 .stencil_export = pdevice->info.gen >= 9,
191 .storage_8bit = pdevice->info.gen >= 8,
192 .storage_16bit = pdevice->info.gen >= 8,
193 .subgroup_arithmetic = true,
194 .subgroup_basic = true,
195 .subgroup_ballot = true,
196 .subgroup_quad = true,
197 .subgroup_shuffle = true,
198 .subgroup_vote = true,
199 .tessellation = true,
200 .transform_feedback = pdevice->info.gen >= 8,
201 .variable_pointers = true,
202 .vk_memory_model = true,
203 .vk_memory_model_device_scope = true,
204 },
205 .ubo_addr_format = nir_address_format_32bit_index_offset,
206 .ssbo_addr_format =
207 anv_nir_ssbo_addr_format(pdevice, device->robust_buffer_access),
208 .phys_ssbo_addr_format = nir_address_format_64bit_global,
209 .push_const_addr_format = nir_address_format_logical,
210
211 /* TODO: Consider changing this to an address format that has the NULL
212 * pointer equals to 0. That might be a better format to play nice
213 * with certain code / code generators.
214 */
215 .shared_addr_format = nir_address_format_32bit_offset,
216 .debug = {
217 .func = anv_spirv_nir_debug,
218 .private_data = &spirv_debug_data,
219 },
220 };
221
222
223 nir_shader *nir =
224 spirv_to_nir(spirv, module->size / 4,
225 spec_entries, num_spec_entries,
226 stage, entrypoint_name, &spirv_options, nir_options);
227 assert(nir->info.stage == stage);
228 nir_validate_shader(nir, "after spirv_to_nir");
229 ralloc_steal(mem_ctx, nir);
230
231 free(spec_entries);
232
233 if (unlikely(INTEL_DEBUG & intel_debug_flag_for_shader_stage(stage))) {
234 fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
235 gl_shader_stage_name(stage));
236 nir_print_shader(nir, stderr);
237 }
238
239 /* We have to lower away local constant initializers right before we
240 * inline functions. That way they get properly initialized at the top
241 * of the function and not at the top of its caller.
242 */
243 NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_function_temp);
244 NIR_PASS_V(nir, nir_lower_returns);
245 NIR_PASS_V(nir, nir_inline_functions);
246 NIR_PASS_V(nir, nir_opt_deref);
247
248 /* Pick off the single entrypoint that we want */
249 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
250 if (!func->is_entrypoint)
251 exec_node_remove(&func->node);
252 }
253 assert(exec_list_length(&nir->functions) == 1);
254
255 /* Now that we've deleted all but the main function, we can go ahead and
256 * lower the rest of the constant initializers. We do this here so that
257 * nir_remove_dead_variables and split_per_member_structs below see the
258 * corresponding stores.
259 */
260 NIR_PASS_V(nir, nir_lower_variable_initializers, ~0);
261
262 /* Split member structs. We do this before lower_io_to_temporaries so that
263 * it doesn't lower system values to temporaries by accident.
264 */
265 NIR_PASS_V(nir, nir_split_var_copies);
266 NIR_PASS_V(nir, nir_split_per_member_structs);
267
268 NIR_PASS_V(nir, nir_remove_dead_variables,
269 nir_var_shader_in | nir_var_shader_out | nir_var_system_value);
270
271 NIR_PASS_V(nir, nir_propagate_invariant);
272 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
273 nir_shader_get_entrypoint(nir), true, false);
274
275 NIR_PASS_V(nir, nir_lower_frexp);
276
277 /* Vulkan uses the separate-shader linking model */
278 nir->info.separate_shader = true;
279
280 brw_preprocess_nir(compiler, nir, NULL);
281
282 return nir;
283 }
284
285 void anv_DestroyPipeline(
286 VkDevice _device,
287 VkPipeline _pipeline,
288 const VkAllocationCallbacks* pAllocator)
289 {
290 ANV_FROM_HANDLE(anv_device, device, _device);
291 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
292
293 if (!pipeline)
294 return;
295
296 anv_reloc_list_finish(&pipeline->batch_relocs,
297 pAllocator ? pAllocator : &device->alloc);
298
299 ralloc_free(pipeline->mem_ctx);
300
301 if (pipeline->blend_state.map)
302 anv_state_pool_free(&device->dynamic_state_pool, pipeline->blend_state);
303
304 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
305 if (pipeline->shaders[s])
306 anv_shader_bin_unref(device, pipeline->shaders[s]);
307 }
308
309 vk_free2(&device->alloc, pAllocator, pipeline);
310 }
311
312 static const uint32_t vk_to_gen_primitive_type[] = {
313 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
314 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
315 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
316 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
317 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
318 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
319 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
320 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
321 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
322 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
323 };
324
325 static void
326 populate_sampler_prog_key(const struct gen_device_info *devinfo,
327 struct brw_sampler_prog_key_data *key)
328 {
329 /* Almost all multisampled textures are compressed. The only time when we
330 * don't compress a multisampled texture is for 16x MSAA with a surface
331 * width greater than 8k which is a bit of an edge case. Since the sampler
332 * just ignores the MCS parameter to ld2ms when MCS is disabled, it's safe
333 * to tell the compiler to always assume compression.
334 */
335 key->compressed_multisample_layout_mask = ~0;
336
337 /* SkyLake added support for 16x MSAA. With this came a new message for
338 * reading from a 16x MSAA surface with compression. The new message was
339 * needed because now the MCS data is 64 bits instead of 32 or lower as is
340 * the case for 8x, 4x, and 2x. The key->msaa_16 bit-field controls which
341 * message we use. Fortunately, the 16x message works for 8x, 4x, and 2x
342 * so we can just use it unconditionally. This may not be quite as
343 * efficient but it saves us from recompiling.
344 */
345 if (devinfo->gen >= 9)
346 key->msaa_16 = ~0;
347
348 /* XXX: Handle texture swizzle on HSW- */
349 for (int i = 0; i < MAX_SAMPLERS; i++) {
350 /* Assume color sampler, no swizzling. (Works for BDW+) */
351 key->swizzles[i] = SWIZZLE_XYZW;
352 }
353 }
354
355 static void
356 populate_base_prog_key(const struct gen_device_info *devinfo,
357 VkPipelineShaderStageCreateFlags flags,
358 struct brw_base_prog_key *key)
359 {
360 if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
361 key->subgroup_size_type = BRW_SUBGROUP_SIZE_VARYING;
362 else
363 key->subgroup_size_type = BRW_SUBGROUP_SIZE_API_CONSTANT;
364
365 populate_sampler_prog_key(devinfo, &key->tex);
366 }
367
368 static void
369 populate_vs_prog_key(const struct gen_device_info *devinfo,
370 VkPipelineShaderStageCreateFlags flags,
371 struct brw_vs_prog_key *key)
372 {
373 memset(key, 0, sizeof(*key));
374
375 populate_base_prog_key(devinfo, flags, &key->base);
376
377 /* XXX: Handle vertex input work-arounds */
378
379 /* XXX: Handle sampler_prog_key */
380 }
381
382 static void
383 populate_tcs_prog_key(const struct gen_device_info *devinfo,
384 VkPipelineShaderStageCreateFlags flags,
385 unsigned input_vertices,
386 struct brw_tcs_prog_key *key)
387 {
388 memset(key, 0, sizeof(*key));
389
390 populate_base_prog_key(devinfo, flags, &key->base);
391
392 key->input_vertices = input_vertices;
393 }
394
395 static void
396 populate_tes_prog_key(const struct gen_device_info *devinfo,
397 VkPipelineShaderStageCreateFlags flags,
398 struct brw_tes_prog_key *key)
399 {
400 memset(key, 0, sizeof(*key));
401
402 populate_base_prog_key(devinfo, flags, &key->base);
403 }
404
405 static void
406 populate_gs_prog_key(const struct gen_device_info *devinfo,
407 VkPipelineShaderStageCreateFlags flags,
408 struct brw_gs_prog_key *key)
409 {
410 memset(key, 0, sizeof(*key));
411
412 populate_base_prog_key(devinfo, flags, &key->base);
413 }
414
415 static void
416 populate_wm_prog_key(const struct gen_device_info *devinfo,
417 VkPipelineShaderStageCreateFlags flags,
418 const struct anv_subpass *subpass,
419 const VkPipelineMultisampleStateCreateInfo *ms_info,
420 struct brw_wm_prog_key *key)
421 {
422 memset(key, 0, sizeof(*key));
423
424 populate_base_prog_key(devinfo, flags, &key->base);
425
426 /* We set this to 0 here and set to the actual value before we call
427 * brw_compile_fs.
428 */
429 key->input_slots_valid = 0;
430
431 /* Vulkan doesn't specify a default */
432 key->high_quality_derivatives = false;
433
434 /* XXX Vulkan doesn't appear to specify */
435 key->clamp_fragment_color = false;
436
437 assert(subpass->color_count <= MAX_RTS);
438 for (uint32_t i = 0; i < subpass->color_count; i++) {
439 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
440 key->color_outputs_valid |= (1 << i);
441 }
442
443 key->nr_color_regions = subpass->color_count;
444
445 /* To reduce possible shader recompilations we would need to know if
446 * there is a SampleMask output variable to compute if we should emit
447 * code to workaround the issue that hardware disables alpha to coverage
448 * when there is SampleMask output.
449 */
450 key->alpha_to_coverage = ms_info && ms_info->alphaToCoverageEnable;
451
452 /* Vulkan doesn't support fixed-function alpha test */
453 key->alpha_test_replicate_alpha = false;
454
455 if (ms_info) {
456 /* We should probably pull this out of the shader, but it's fairly
457 * harmless to compute it and then let dead-code take care of it.
458 */
459 if (ms_info->rasterizationSamples > 1) {
460 key->persample_interp = ms_info->sampleShadingEnable &&
461 (ms_info->minSampleShading * ms_info->rasterizationSamples) > 1;
462 key->multisample_fbo = true;
463 }
464
465 key->frag_coord_adds_sample_pos = key->persample_interp;
466 }
467 }
468
469 static void
470 populate_cs_prog_key(const struct gen_device_info *devinfo,
471 VkPipelineShaderStageCreateFlags flags,
472 const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info,
473 struct brw_cs_prog_key *key)
474 {
475 memset(key, 0, sizeof(*key));
476
477 populate_base_prog_key(devinfo, flags, &key->base);
478
479 if (rss_info) {
480 assert(key->base.subgroup_size_type != BRW_SUBGROUP_SIZE_VARYING);
481
482 /* These enum values are expressly chosen to be equal to the subgroup
483 * size that they require.
484 */
485 assert(rss_info->requiredSubgroupSize == 8 ||
486 rss_info->requiredSubgroupSize == 16 ||
487 rss_info->requiredSubgroupSize == 32);
488 key->base.subgroup_size_type = rss_info->requiredSubgroupSize;
489 } else if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT) {
490 /* If the client expressly requests full subgroups and they don't
491 * specify a subgroup size, we need to pick one. If they're requested
492 * varying subgroup sizes, we set it to UNIFORM and let the back-end
493 * compiler pick. Otherwise, we specify the API value of 32.
494 * Performance will likely be terrible in this case but there's nothing
495 * we can do about that. The client should have chosen a size.
496 */
497 if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
498 key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_UNIFORM;
499 else
500 key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_REQUIRE_32;
501 }
502 }
503
504 struct anv_pipeline_stage {
505 gl_shader_stage stage;
506
507 const struct anv_shader_module *module;
508 const char *entrypoint;
509 const VkSpecializationInfo *spec_info;
510
511 unsigned char shader_sha1[20];
512
513 union brw_any_prog_key key;
514
515 struct {
516 gl_shader_stage stage;
517 unsigned char sha1[20];
518 } cache_key;
519
520 nir_shader *nir;
521
522 struct anv_pipeline_binding surface_to_descriptor[256];
523 struct anv_pipeline_binding sampler_to_descriptor[256];
524 struct anv_pipeline_bind_map bind_map;
525
526 union brw_any_prog_data prog_data;
527
528 uint32_t num_stats;
529 struct brw_compile_stats stats[3];
530 char *disasm[3];
531
532 VkPipelineCreationFeedbackEXT feedback;
533
534 const unsigned *code;
535 };
536
537 static void
538 anv_pipeline_hash_shader(const struct anv_shader_module *module,
539 const char *entrypoint,
540 gl_shader_stage stage,
541 const VkSpecializationInfo *spec_info,
542 unsigned char *sha1_out)
543 {
544 struct mesa_sha1 ctx;
545 _mesa_sha1_init(&ctx);
546
547 _mesa_sha1_update(&ctx, module->sha1, sizeof(module->sha1));
548 _mesa_sha1_update(&ctx, entrypoint, strlen(entrypoint));
549 _mesa_sha1_update(&ctx, &stage, sizeof(stage));
550 if (spec_info) {
551 _mesa_sha1_update(&ctx, spec_info->pMapEntries,
552 spec_info->mapEntryCount *
553 sizeof(*spec_info->pMapEntries));
554 _mesa_sha1_update(&ctx, spec_info->pData,
555 spec_info->dataSize);
556 }
557
558 _mesa_sha1_final(&ctx, sha1_out);
559 }
560
561 static void
562 anv_pipeline_hash_graphics(struct anv_pipeline *pipeline,
563 struct anv_pipeline_layout *layout,
564 struct anv_pipeline_stage *stages,
565 unsigned char *sha1_out)
566 {
567 struct mesa_sha1 ctx;
568 _mesa_sha1_init(&ctx);
569
570 _mesa_sha1_update(&ctx, &pipeline->subpass->view_mask,
571 sizeof(pipeline->subpass->view_mask));
572
573 if (layout)
574 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
575
576 const bool rba = pipeline->device->robust_buffer_access;
577 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
578
579 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
580 if (stages[s].entrypoint) {
581 _mesa_sha1_update(&ctx, stages[s].shader_sha1,
582 sizeof(stages[s].shader_sha1));
583 _mesa_sha1_update(&ctx, &stages[s].key, brw_prog_key_size(s));
584 }
585 }
586
587 _mesa_sha1_final(&ctx, sha1_out);
588 }
589
590 static void
591 anv_pipeline_hash_compute(struct anv_pipeline *pipeline,
592 struct anv_pipeline_layout *layout,
593 struct anv_pipeline_stage *stage,
594 unsigned char *sha1_out)
595 {
596 struct mesa_sha1 ctx;
597 _mesa_sha1_init(&ctx);
598
599 if (layout)
600 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
601
602 const bool rba = pipeline->device->robust_buffer_access;
603 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
604
605 _mesa_sha1_update(&ctx, stage->shader_sha1,
606 sizeof(stage->shader_sha1));
607 _mesa_sha1_update(&ctx, &stage->key.cs, sizeof(stage->key.cs));
608
609 _mesa_sha1_final(&ctx, sha1_out);
610 }
611
612 static nir_shader *
613 anv_pipeline_stage_get_nir(struct anv_pipeline *pipeline,
614 struct anv_pipeline_cache *cache,
615 void *mem_ctx,
616 struct anv_pipeline_stage *stage)
617 {
618 const struct brw_compiler *compiler =
619 pipeline->device->physical->compiler;
620 const nir_shader_compiler_options *nir_options =
621 compiler->glsl_compiler_options[stage->stage].NirOptions;
622 nir_shader *nir;
623
624 nir = anv_device_search_for_nir(pipeline->device, cache,
625 nir_options,
626 stage->shader_sha1,
627 mem_ctx);
628 if (nir) {
629 assert(nir->info.stage == stage->stage);
630 return nir;
631 }
632
633 nir = anv_shader_compile_to_nir(pipeline->device,
634 mem_ctx,
635 stage->module,
636 stage->entrypoint,
637 stage->stage,
638 stage->spec_info);
639 if (nir) {
640 anv_device_upload_nir(pipeline->device, cache, nir, stage->shader_sha1);
641 return nir;
642 }
643
644 return NULL;
645 }
646
647 static void
648 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
649 void *mem_ctx,
650 struct anv_pipeline_stage *stage,
651 struct anv_pipeline_layout *layout)
652 {
653 const struct anv_physical_device *pdevice = pipeline->device->physical;
654 const struct brw_compiler *compiler = pdevice->compiler;
655
656 struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
657 nir_shader *nir = stage->nir;
658
659 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
660 NIR_PASS_V(nir, nir_lower_wpos_center, pipeline->sample_shading_enable);
661 NIR_PASS_V(nir, nir_lower_input_attachments, true);
662 }
663
664 NIR_PASS_V(nir, anv_nir_lower_ycbcr_textures, layout);
665
666 if (pipeline->type == ANV_PIPELINE_GRAPHICS)
667 NIR_PASS_V(nir, anv_nir_lower_multiview, pipeline->subpass->view_mask);
668
669 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
670
671 NIR_PASS_V(nir, brw_nir_lower_image_load_store, compiler->devinfo);
672
673 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_global,
674 nir_address_format_64bit_global);
675
676 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
677 anv_nir_apply_pipeline_layout(pdevice,
678 pipeline->device->robust_buffer_access,
679 layout, nir, &stage->bind_map);
680
681 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ubo,
682 nir_address_format_32bit_index_offset);
683 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ssbo,
684 anv_nir_ssbo_addr_format(pdevice,
685 pipeline->device->robust_buffer_access));
686
687 NIR_PASS_V(nir, nir_opt_constant_folding);
688
689 /* We don't support non-uniform UBOs and non-uniform SSBO access is
690 * handled naturally by falling back to A64 messages.
691 */
692 NIR_PASS_V(nir, nir_lower_non_uniform_access,
693 nir_lower_non_uniform_texture_access |
694 nir_lower_non_uniform_image_access);
695
696 anv_nir_compute_push_layout(pdevice, pipeline->device->robust_buffer_access,
697 nir, prog_data, &stage->bind_map, mem_ctx);
698
699 stage->nir = nir;
700 }
701
702 static void
703 anv_pipeline_link_vs(const struct brw_compiler *compiler,
704 struct anv_pipeline_stage *vs_stage,
705 struct anv_pipeline_stage *next_stage)
706 {
707 if (next_stage)
708 brw_nir_link_shaders(compiler, vs_stage->nir, next_stage->nir);
709 }
710
711 static void
712 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
713 void *mem_ctx,
714 struct anv_device *device,
715 struct anv_pipeline_stage *vs_stage)
716 {
717 brw_compute_vue_map(compiler->devinfo,
718 &vs_stage->prog_data.vs.base.vue_map,
719 vs_stage->nir->info.outputs_written,
720 vs_stage->nir->info.separate_shader);
721
722 vs_stage->num_stats = 1;
723 vs_stage->code = brw_compile_vs(compiler, device, mem_ctx,
724 &vs_stage->key.vs,
725 &vs_stage->prog_data.vs,
726 vs_stage->nir, -1,
727 vs_stage->stats, NULL);
728 }
729
730 static void
731 merge_tess_info(struct shader_info *tes_info,
732 const struct shader_info *tcs_info)
733 {
734 /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
735 *
736 * "PointMode. Controls generation of points rather than triangles
737 * or lines. This functionality defaults to disabled, and is
738 * enabled if either shader stage includes the execution mode.
739 *
740 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
741 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
742 * and OutputVertices, it says:
743 *
744 * "One mode must be set in at least one of the tessellation
745 * shader stages."
746 *
747 * So, the fields can be set in either the TCS or TES, but they must
748 * agree if set in both. Our backend looks at TES, so bitwise-or in
749 * the values from the TCS.
750 */
751 assert(tcs_info->tess.tcs_vertices_out == 0 ||
752 tes_info->tess.tcs_vertices_out == 0 ||
753 tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
754 tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
755
756 assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
757 tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
758 tcs_info->tess.spacing == tes_info->tess.spacing);
759 tes_info->tess.spacing |= tcs_info->tess.spacing;
760
761 assert(tcs_info->tess.primitive_mode == 0 ||
762 tes_info->tess.primitive_mode == 0 ||
763 tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
764 tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
765 tes_info->tess.ccw |= tcs_info->tess.ccw;
766 tes_info->tess.point_mode |= tcs_info->tess.point_mode;
767 }
768
769 static void
770 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
771 struct anv_pipeline_stage *tcs_stage,
772 struct anv_pipeline_stage *tes_stage)
773 {
774 assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
775
776 brw_nir_link_shaders(compiler, tcs_stage->nir, tes_stage->nir);
777
778 nir_lower_patch_vertices(tes_stage->nir,
779 tcs_stage->nir->info.tess.tcs_vertices_out,
780 NULL);
781
782 /* Copy TCS info into the TES info */
783 merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
784
785 /* Whacking the key after cache lookup is a bit sketchy, but all of
786 * this comes from the SPIR-V, which is part of the hash used for the
787 * pipeline cache. So it should be safe.
788 */
789 tcs_stage->key.tcs.tes_primitive_mode =
790 tes_stage->nir->info.tess.primitive_mode;
791 tcs_stage->key.tcs.quads_workaround =
792 compiler->devinfo->gen < 9 &&
793 tes_stage->nir->info.tess.primitive_mode == 7 /* GL_QUADS */ &&
794 tes_stage->nir->info.tess.spacing == TESS_SPACING_EQUAL;
795 }
796
797 static void
798 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
799 void *mem_ctx,
800 struct anv_device *device,
801 struct anv_pipeline_stage *tcs_stage,
802 struct anv_pipeline_stage *prev_stage)
803 {
804 tcs_stage->key.tcs.outputs_written =
805 tcs_stage->nir->info.outputs_written;
806 tcs_stage->key.tcs.patch_outputs_written =
807 tcs_stage->nir->info.patch_outputs_written;
808
809 tcs_stage->num_stats = 1;
810 tcs_stage->code = brw_compile_tcs(compiler, device, mem_ctx,
811 &tcs_stage->key.tcs,
812 &tcs_stage->prog_data.tcs,
813 tcs_stage->nir, -1,
814 tcs_stage->stats, NULL);
815 }
816
817 static void
818 anv_pipeline_link_tes(const struct brw_compiler *compiler,
819 struct anv_pipeline_stage *tes_stage,
820 struct anv_pipeline_stage *next_stage)
821 {
822 if (next_stage)
823 brw_nir_link_shaders(compiler, tes_stage->nir, next_stage->nir);
824 }
825
826 static void
827 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
828 void *mem_ctx,
829 struct anv_device *device,
830 struct anv_pipeline_stage *tes_stage,
831 struct anv_pipeline_stage *tcs_stage)
832 {
833 tes_stage->key.tes.inputs_read =
834 tcs_stage->nir->info.outputs_written;
835 tes_stage->key.tes.patch_inputs_read =
836 tcs_stage->nir->info.patch_outputs_written;
837
838 tes_stage->num_stats = 1;
839 tes_stage->code = brw_compile_tes(compiler, device, mem_ctx,
840 &tes_stage->key.tes,
841 &tcs_stage->prog_data.tcs.base.vue_map,
842 &tes_stage->prog_data.tes,
843 tes_stage->nir, -1,
844 tes_stage->stats, NULL);
845 }
846
847 static void
848 anv_pipeline_link_gs(const struct brw_compiler *compiler,
849 struct anv_pipeline_stage *gs_stage,
850 struct anv_pipeline_stage *next_stage)
851 {
852 if (next_stage)
853 brw_nir_link_shaders(compiler, gs_stage->nir, next_stage->nir);
854 }
855
856 static void
857 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
858 void *mem_ctx,
859 struct anv_device *device,
860 struct anv_pipeline_stage *gs_stage,
861 struct anv_pipeline_stage *prev_stage)
862 {
863 brw_compute_vue_map(compiler->devinfo,
864 &gs_stage->prog_data.gs.base.vue_map,
865 gs_stage->nir->info.outputs_written,
866 gs_stage->nir->info.separate_shader);
867
868 gs_stage->num_stats = 1;
869 gs_stage->code = brw_compile_gs(compiler, device, mem_ctx,
870 &gs_stage->key.gs,
871 &gs_stage->prog_data.gs,
872 gs_stage->nir, NULL, -1,
873 gs_stage->stats, NULL);
874 }
875
876 static void
877 anv_pipeline_link_fs(const struct brw_compiler *compiler,
878 struct anv_pipeline_stage *stage)
879 {
880 unsigned num_rt_bindings;
881 struct anv_pipeline_binding rt_bindings[MAX_RTS];
882 if (stage->key.wm.nr_color_regions > 0) {
883 assert(stage->key.wm.nr_color_regions <= MAX_RTS);
884 for (unsigned rt = 0; rt < stage->key.wm.nr_color_regions; rt++) {
885 if (stage->key.wm.color_outputs_valid & BITFIELD_BIT(rt)) {
886 rt_bindings[rt] = (struct anv_pipeline_binding) {
887 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
888 .index = rt,
889 };
890 } else {
891 /* Setup a null render target */
892 rt_bindings[rt] = (struct anv_pipeline_binding) {
893 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
894 .index = UINT32_MAX,
895 };
896 }
897 }
898 num_rt_bindings = stage->key.wm.nr_color_regions;
899 } else {
900 /* Setup a null render target */
901 rt_bindings[0] = (struct anv_pipeline_binding) {
902 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
903 .index = UINT32_MAX,
904 };
905 num_rt_bindings = 1;
906 }
907
908 assert(num_rt_bindings <= MAX_RTS);
909 assert(stage->bind_map.surface_count == 0);
910 typed_memcpy(stage->bind_map.surface_to_descriptor,
911 rt_bindings, num_rt_bindings);
912 stage->bind_map.surface_count += num_rt_bindings;
913
914 /* Now that we've set up the color attachments, we can go through and
915 * eliminate any shader outputs that map to VK_ATTACHMENT_UNUSED in the
916 * hopes that dead code can clean them up in this and any earlier shader
917 * stages.
918 */
919 nir_function_impl *impl = nir_shader_get_entrypoint(stage->nir);
920 bool deleted_output = false;
921 nir_foreach_variable_safe(var, &stage->nir->outputs) {
922 /* TODO: We don't delete depth/stencil writes. We probably could if the
923 * subpass doesn't have a depth/stencil attachment.
924 */
925 if (var->data.location < FRAG_RESULT_DATA0)
926 continue;
927
928 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
929
930 /* If this is the RT at location 0 and we have alpha to coverage
931 * enabled we still need that write because it will affect the coverage
932 * mask even if it's never written to a color target.
933 */
934 if (rt == 0 && stage->key.wm.alpha_to_coverage)
935 continue;
936
937 const unsigned array_len =
938 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
939 assert(rt + array_len <= MAX_RTS);
940
941 if (rt >= MAX_RTS || !(stage->key.wm.color_outputs_valid &
942 BITFIELD_RANGE(rt, array_len))) {
943 deleted_output = true;
944 var->data.mode = nir_var_function_temp;
945 exec_node_remove(&var->node);
946 exec_list_push_tail(&impl->locals, &var->node);
947 }
948 }
949
950 if (deleted_output)
951 nir_fixup_deref_modes(stage->nir);
952
953 /* We stored the number of subpass color attachments in nr_color_regions
954 * when calculating the key for caching. Now that we've computed the bind
955 * map, we can reduce this to the actual max before we go into the back-end
956 * compiler.
957 */
958 stage->key.wm.nr_color_regions =
959 util_last_bit(stage->key.wm.color_outputs_valid);
960 }
961
962 static void
963 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
964 void *mem_ctx,
965 struct anv_device *device,
966 struct anv_pipeline_stage *fs_stage,
967 struct anv_pipeline_stage *prev_stage)
968 {
969 /* TODO: we could set this to 0 based on the information in nir_shader, but
970 * we need this before we call spirv_to_nir.
971 */
972 assert(prev_stage);
973 fs_stage->key.wm.input_slots_valid =
974 prev_stage->prog_data.vue.vue_map.slots_valid;
975
976 fs_stage->code = brw_compile_fs(compiler, device, mem_ctx,
977 &fs_stage->key.wm,
978 &fs_stage->prog_data.wm,
979 fs_stage->nir, -1, -1, -1,
980 true, false, NULL,
981 fs_stage->stats, NULL);
982
983 fs_stage->num_stats = (uint32_t)fs_stage->prog_data.wm.dispatch_8 +
984 (uint32_t)fs_stage->prog_data.wm.dispatch_16 +
985 (uint32_t)fs_stage->prog_data.wm.dispatch_32;
986
987 if (fs_stage->key.wm.color_outputs_valid == 0 &&
988 !fs_stage->prog_data.wm.has_side_effects &&
989 !fs_stage->prog_data.wm.uses_omask &&
990 !fs_stage->key.wm.alpha_to_coverage &&
991 !fs_stage->prog_data.wm.uses_kill &&
992 fs_stage->prog_data.wm.computed_depth_mode == BRW_PSCDEPTH_OFF &&
993 !fs_stage->prog_data.wm.computed_stencil) {
994 /* This fragment shader has no outputs and no side effects. Go ahead
995 * and return the code pointer so we don't accidentally think the
996 * compile failed but zero out prog_data which will set program_size to
997 * zero and disable the stage.
998 */
999 memset(&fs_stage->prog_data, 0, sizeof(fs_stage->prog_data));
1000 }
1001 }
1002
1003 static void
1004 anv_pipeline_add_executable(struct anv_pipeline *pipeline,
1005 struct anv_pipeline_stage *stage,
1006 struct brw_compile_stats *stats,
1007 uint32_t code_offset)
1008 {
1009 char *nir = NULL;
1010 if (stage->nir &&
1011 (pipeline->flags &
1012 VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1013 char *stream_data = NULL;
1014 size_t stream_size = 0;
1015 FILE *stream = open_memstream(&stream_data, &stream_size);
1016
1017 nir_print_shader(stage->nir, stream);
1018
1019 fclose(stream);
1020
1021 /* Copy it to a ralloc'd thing */
1022 nir = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1023 memcpy(nir, stream_data, stream_size);
1024 nir[stream_size] = 0;
1025
1026 free(stream_data);
1027 }
1028
1029 char *disasm = NULL;
1030 if (stage->code &&
1031 (pipeline->flags &
1032 VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1033 char *stream_data = NULL;
1034 size_t stream_size = 0;
1035 FILE *stream = open_memstream(&stream_data, &stream_size);
1036
1037 /* Creating this is far cheaper than it looks. It's perfectly fine to
1038 * do it for every binary.
1039 */
1040 struct gen_disasm *d = gen_disasm_create(&pipeline->device->info);
1041 gen_disasm_disassemble(d, stage->code, code_offset, stream);
1042 gen_disasm_destroy(d);
1043
1044 fclose(stream);
1045
1046 /* Copy it to a ralloc'd thing */
1047 disasm = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1048 memcpy(disasm, stream_data, stream_size);
1049 disasm[stream_size] = 0;
1050
1051 free(stream_data);
1052 }
1053
1054 const struct anv_pipeline_executable exe = {
1055 .stage = stage->stage,
1056 .stats = *stats,
1057 .nir = nir,
1058 .disasm = disasm,
1059 };
1060 util_dynarray_append(&pipeline->executables,
1061 struct anv_pipeline_executable, exe);
1062 }
1063
1064 static void
1065 anv_pipeline_add_executables(struct anv_pipeline *pipeline,
1066 struct anv_pipeline_stage *stage,
1067 struct anv_shader_bin *bin)
1068 {
1069 if (stage->stage == MESA_SHADER_FRAGMENT) {
1070 /* We pull the prog data and stats out of the anv_shader_bin because
1071 * the anv_pipeline_stage may not be fully populated if we successfully
1072 * looked up the shader in a cache.
1073 */
1074 const struct brw_wm_prog_data *wm_prog_data =
1075 (const struct brw_wm_prog_data *)bin->prog_data;
1076 struct brw_compile_stats *stats = bin->stats;
1077
1078 if (wm_prog_data->dispatch_8) {
1079 anv_pipeline_add_executable(pipeline, stage, stats++, 0);
1080 }
1081
1082 if (wm_prog_data->dispatch_16) {
1083 anv_pipeline_add_executable(pipeline, stage, stats++,
1084 wm_prog_data->prog_offset_16);
1085 }
1086
1087 if (wm_prog_data->dispatch_32) {
1088 anv_pipeline_add_executable(pipeline, stage, stats++,
1089 wm_prog_data->prog_offset_32);
1090 }
1091 } else {
1092 anv_pipeline_add_executable(pipeline, stage, bin->stats, 0);
1093 }
1094 }
1095
1096 static VkResult
1097 anv_pipeline_compile_graphics(struct anv_pipeline *pipeline,
1098 struct anv_pipeline_cache *cache,
1099 const VkGraphicsPipelineCreateInfo *info)
1100 {
1101 VkPipelineCreationFeedbackEXT pipeline_feedback = {
1102 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1103 };
1104 int64_t pipeline_start = os_time_get_nano();
1105
1106 const struct brw_compiler *compiler = pipeline->device->physical->compiler;
1107 struct anv_pipeline_stage stages[MESA_SHADER_STAGES] = {};
1108
1109 pipeline->active_stages = 0;
1110
1111 VkResult result;
1112 for (uint32_t i = 0; i < info->stageCount; i++) {
1113 const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
1114 gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
1115
1116 pipeline->active_stages |= sinfo->stage;
1117
1118 int64_t stage_start = os_time_get_nano();
1119
1120 stages[stage].stage = stage;
1121 stages[stage].module = anv_shader_module_from_handle(sinfo->module);
1122 stages[stage].entrypoint = sinfo->pName;
1123 stages[stage].spec_info = sinfo->pSpecializationInfo;
1124 anv_pipeline_hash_shader(stages[stage].module,
1125 stages[stage].entrypoint,
1126 stage,
1127 stages[stage].spec_info,
1128 stages[stage].shader_sha1);
1129
1130 const struct gen_device_info *devinfo = &pipeline->device->info;
1131 switch (stage) {
1132 case MESA_SHADER_VERTEX:
1133 populate_vs_prog_key(devinfo, sinfo->flags, &stages[stage].key.vs);
1134 break;
1135 case MESA_SHADER_TESS_CTRL:
1136 populate_tcs_prog_key(devinfo, sinfo->flags,
1137 info->pTessellationState->patchControlPoints,
1138 &stages[stage].key.tcs);
1139 break;
1140 case MESA_SHADER_TESS_EVAL:
1141 populate_tes_prog_key(devinfo, sinfo->flags, &stages[stage].key.tes);
1142 break;
1143 case MESA_SHADER_GEOMETRY:
1144 populate_gs_prog_key(devinfo, sinfo->flags, &stages[stage].key.gs);
1145 break;
1146 case MESA_SHADER_FRAGMENT: {
1147 const bool raster_enabled =
1148 !info->pRasterizationState->rasterizerDiscardEnable;
1149 populate_wm_prog_key(devinfo, sinfo->flags,
1150 pipeline->subpass,
1151 raster_enabled ? info->pMultisampleState : NULL,
1152 &stages[stage].key.wm);
1153 break;
1154 }
1155 default:
1156 unreachable("Invalid graphics shader stage");
1157 }
1158
1159 stages[stage].feedback.duration += os_time_get_nano() - stage_start;
1160 stages[stage].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT;
1161 }
1162
1163 if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
1164 pipeline->active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
1165
1166 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1167
1168 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1169
1170 unsigned char sha1[20];
1171 anv_pipeline_hash_graphics(pipeline, layout, stages, sha1);
1172
1173 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1174 if (!stages[s].entrypoint)
1175 continue;
1176
1177 stages[s].cache_key.stage = s;
1178 memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
1179 }
1180
1181 const bool skip_cache_lookup =
1182 (pipeline->flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1183
1184 if (!skip_cache_lookup) {
1185 unsigned found = 0;
1186 unsigned cache_hits = 0;
1187 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1188 if (!stages[s].entrypoint)
1189 continue;
1190
1191 int64_t stage_start = os_time_get_nano();
1192
1193 bool cache_hit;
1194 struct anv_shader_bin *bin =
1195 anv_device_search_for_kernel(pipeline->device, cache,
1196 &stages[s].cache_key,
1197 sizeof(stages[s].cache_key), &cache_hit);
1198 if (bin) {
1199 found++;
1200 pipeline->shaders[s] = bin;
1201 }
1202
1203 if (cache_hit) {
1204 cache_hits++;
1205 stages[s].feedback.flags |=
1206 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1207 }
1208 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1209 }
1210
1211 if (found == __builtin_popcount(pipeline->active_stages)) {
1212 if (cache_hits == found) {
1213 pipeline_feedback.flags |=
1214 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1215 }
1216 /* We found all our shaders in the cache. We're done. */
1217 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1218 if (!stages[s].entrypoint)
1219 continue;
1220
1221 anv_pipeline_add_executables(pipeline, &stages[s],
1222 pipeline->shaders[s]);
1223 }
1224 goto done;
1225 } else if (found > 0) {
1226 /* We found some but not all of our shaders. This shouldn't happen
1227 * most of the time but it can if we have a partially populated
1228 * pipeline cache.
1229 */
1230 assert(found < __builtin_popcount(pipeline->active_stages));
1231
1232 vk_debug_report(&pipeline->device->physical->instance->debug_report_callbacks,
1233 VK_DEBUG_REPORT_WARNING_BIT_EXT |
1234 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
1235 VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,
1236 (uint64_t)(uintptr_t)cache,
1237 0, 0, "anv",
1238 "Found a partial pipeline in the cache. This is "
1239 "most likely caused by an incomplete pipeline cache "
1240 "import or export");
1241
1242 /* We're going to have to recompile anyway, so just throw away our
1243 * references to the shaders in the cache. We'll get them out of the
1244 * cache again as part of the compilation process.
1245 */
1246 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1247 stages[s].feedback.flags = 0;
1248 if (pipeline->shaders[s]) {
1249 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
1250 pipeline->shaders[s] = NULL;
1251 }
1252 }
1253 }
1254 }
1255
1256 void *pipeline_ctx = ralloc_context(NULL);
1257
1258 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1259 if (!stages[s].entrypoint)
1260 continue;
1261
1262 int64_t stage_start = os_time_get_nano();
1263
1264 assert(stages[s].stage == s);
1265 assert(pipeline->shaders[s] == NULL);
1266
1267 stages[s].bind_map = (struct anv_pipeline_bind_map) {
1268 .surface_to_descriptor = stages[s].surface_to_descriptor,
1269 .sampler_to_descriptor = stages[s].sampler_to_descriptor
1270 };
1271
1272 stages[s].nir = anv_pipeline_stage_get_nir(pipeline, cache,
1273 pipeline_ctx,
1274 &stages[s]);
1275 if (stages[s].nir == NULL) {
1276 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1277 goto fail;
1278 }
1279
1280 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1281 }
1282
1283 /* Walk backwards to link */
1284 struct anv_pipeline_stage *next_stage = NULL;
1285 for (int s = MESA_SHADER_STAGES - 1; s >= 0; s--) {
1286 if (!stages[s].entrypoint)
1287 continue;
1288
1289 switch (s) {
1290 case MESA_SHADER_VERTEX:
1291 anv_pipeline_link_vs(compiler, &stages[s], next_stage);
1292 break;
1293 case MESA_SHADER_TESS_CTRL:
1294 anv_pipeline_link_tcs(compiler, &stages[s], next_stage);
1295 break;
1296 case MESA_SHADER_TESS_EVAL:
1297 anv_pipeline_link_tes(compiler, &stages[s], next_stage);
1298 break;
1299 case MESA_SHADER_GEOMETRY:
1300 anv_pipeline_link_gs(compiler, &stages[s], next_stage);
1301 break;
1302 case MESA_SHADER_FRAGMENT:
1303 anv_pipeline_link_fs(compiler, &stages[s]);
1304 break;
1305 default:
1306 unreachable("Invalid graphics shader stage");
1307 }
1308
1309 next_stage = &stages[s];
1310 }
1311
1312 struct anv_pipeline_stage *prev_stage = NULL;
1313 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1314 if (!stages[s].entrypoint)
1315 continue;
1316
1317 int64_t stage_start = os_time_get_nano();
1318
1319 void *stage_ctx = ralloc_context(NULL);
1320
1321 nir_xfb_info *xfb_info = NULL;
1322 if (s == MESA_SHADER_VERTEX ||
1323 s == MESA_SHADER_TESS_EVAL ||
1324 s == MESA_SHADER_GEOMETRY)
1325 xfb_info = nir_gather_xfb_info(stages[s].nir, stage_ctx);
1326
1327 anv_pipeline_lower_nir(pipeline, stage_ctx, &stages[s], layout);
1328
1329 switch (s) {
1330 case MESA_SHADER_VERTEX:
1331 anv_pipeline_compile_vs(compiler, stage_ctx, pipeline->device,
1332 &stages[s]);
1333 break;
1334 case MESA_SHADER_TESS_CTRL:
1335 anv_pipeline_compile_tcs(compiler, stage_ctx, pipeline->device,
1336 &stages[s], prev_stage);
1337 break;
1338 case MESA_SHADER_TESS_EVAL:
1339 anv_pipeline_compile_tes(compiler, stage_ctx, pipeline->device,
1340 &stages[s], prev_stage);
1341 break;
1342 case MESA_SHADER_GEOMETRY:
1343 anv_pipeline_compile_gs(compiler, stage_ctx, pipeline->device,
1344 &stages[s], prev_stage);
1345 break;
1346 case MESA_SHADER_FRAGMENT:
1347 anv_pipeline_compile_fs(compiler, stage_ctx, pipeline->device,
1348 &stages[s], prev_stage);
1349 break;
1350 default:
1351 unreachable("Invalid graphics shader stage");
1352 }
1353 if (stages[s].code == NULL) {
1354 ralloc_free(stage_ctx);
1355 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1356 goto fail;
1357 }
1358
1359 anv_nir_validate_push_layout(&stages[s].prog_data.base,
1360 &stages[s].bind_map);
1361
1362 struct anv_shader_bin *bin =
1363 anv_device_upload_kernel(pipeline->device, cache, s,
1364 &stages[s].cache_key,
1365 sizeof(stages[s].cache_key),
1366 stages[s].code,
1367 stages[s].prog_data.base.program_size,
1368 stages[s].nir->constant_data,
1369 stages[s].nir->constant_data_size,
1370 &stages[s].prog_data.base,
1371 brw_prog_data_size(s),
1372 stages[s].stats, stages[s].num_stats,
1373 xfb_info, &stages[s].bind_map);
1374 if (!bin) {
1375 ralloc_free(stage_ctx);
1376 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1377 goto fail;
1378 }
1379
1380 anv_pipeline_add_executables(pipeline, &stages[s], bin);
1381
1382 pipeline->shaders[s] = bin;
1383 ralloc_free(stage_ctx);
1384
1385 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1386
1387 prev_stage = &stages[s];
1388 }
1389
1390 ralloc_free(pipeline_ctx);
1391
1392 done:
1393
1394 if (pipeline->shaders[MESA_SHADER_FRAGMENT] &&
1395 pipeline->shaders[MESA_SHADER_FRAGMENT]->prog_data->program_size == 0) {
1396 /* This can happen if we decided to implicitly disable the fragment
1397 * shader. See anv_pipeline_compile_fs().
1398 */
1399 anv_shader_bin_unref(pipeline->device,
1400 pipeline->shaders[MESA_SHADER_FRAGMENT]);
1401 pipeline->shaders[MESA_SHADER_FRAGMENT] = NULL;
1402 pipeline->active_stages &= ~VK_SHADER_STAGE_FRAGMENT_BIT;
1403 }
1404
1405 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1406
1407 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1408 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1409 if (create_feedback) {
1410 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1411
1412 assert(info->stageCount == create_feedback->pipelineStageCreationFeedbackCount);
1413 for (uint32_t i = 0; i < info->stageCount; i++) {
1414 gl_shader_stage s = vk_to_mesa_shader_stage(info->pStages[i].stage);
1415 create_feedback->pPipelineStageCreationFeedbacks[i] = stages[s].feedback;
1416 }
1417 }
1418
1419 return VK_SUCCESS;
1420
1421 fail:
1422 ralloc_free(pipeline_ctx);
1423
1424 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1425 if (pipeline->shaders[s])
1426 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
1427 }
1428
1429 return result;
1430 }
1431
1432 static void
1433 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
1434 {
1435 assert(glsl_type_is_vector_or_scalar(type));
1436
1437 uint32_t comp_size = glsl_type_is_boolean(type)
1438 ? 4 : glsl_get_bit_size(type) / 8;
1439 unsigned length = glsl_get_vector_elements(type);
1440 *size = comp_size * length,
1441 *align = comp_size * (length == 3 ? 4 : length);
1442 }
1443
1444 VkResult
1445 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
1446 struct anv_pipeline_cache *cache,
1447 const VkComputePipelineCreateInfo *info,
1448 const struct anv_shader_module *module,
1449 const char *entrypoint,
1450 const VkSpecializationInfo *spec_info)
1451 {
1452 VkPipelineCreationFeedbackEXT pipeline_feedback = {
1453 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1454 };
1455 int64_t pipeline_start = os_time_get_nano();
1456
1457 const struct brw_compiler *compiler = pipeline->device->physical->compiler;
1458
1459 struct anv_pipeline_stage stage = {
1460 .stage = MESA_SHADER_COMPUTE,
1461 .module = module,
1462 .entrypoint = entrypoint,
1463 .spec_info = spec_info,
1464 .cache_key = {
1465 .stage = MESA_SHADER_COMPUTE,
1466 },
1467 .feedback = {
1468 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1469 },
1470 };
1471 anv_pipeline_hash_shader(stage.module,
1472 stage.entrypoint,
1473 MESA_SHADER_COMPUTE,
1474 stage.spec_info,
1475 stage.shader_sha1);
1476
1477 struct anv_shader_bin *bin = NULL;
1478
1479 const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info =
1480 vk_find_struct_const(info->stage.pNext,
1481 PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT);
1482
1483 populate_cs_prog_key(&pipeline->device->info, info->stage.flags,
1484 rss_info, &stage.key.cs);
1485
1486 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1487
1488 const bool skip_cache_lookup =
1489 (pipeline->flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1490
1491 anv_pipeline_hash_compute(pipeline, layout, &stage, stage.cache_key.sha1);
1492
1493 bool cache_hit = false;
1494 if (!skip_cache_lookup) {
1495 bin = anv_device_search_for_kernel(pipeline->device, cache,
1496 &stage.cache_key,
1497 sizeof(stage.cache_key),
1498 &cache_hit);
1499 }
1500
1501 void *mem_ctx = ralloc_context(NULL);
1502 if (bin == NULL) {
1503 int64_t stage_start = os_time_get_nano();
1504
1505 stage.bind_map = (struct anv_pipeline_bind_map) {
1506 .surface_to_descriptor = stage.surface_to_descriptor,
1507 .sampler_to_descriptor = stage.sampler_to_descriptor
1508 };
1509
1510 /* Set up a binding for the gl_NumWorkGroups */
1511 stage.bind_map.surface_count = 1;
1512 stage.bind_map.surface_to_descriptor[0] = (struct anv_pipeline_binding) {
1513 .set = ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS,
1514 };
1515
1516 stage.nir = anv_pipeline_stage_get_nir(pipeline, cache, mem_ctx, &stage);
1517 if (stage.nir == NULL) {
1518 ralloc_free(mem_ctx);
1519 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1520 }
1521
1522 NIR_PASS_V(stage.nir, anv_nir_add_base_work_group_id);
1523
1524 anv_pipeline_lower_nir(pipeline, mem_ctx, &stage, layout);
1525
1526 NIR_PASS_V(stage.nir, nir_lower_vars_to_explicit_types,
1527 nir_var_mem_shared, shared_type_info);
1528 NIR_PASS_V(stage.nir, nir_lower_explicit_io,
1529 nir_var_mem_shared, nir_address_format_32bit_offset);
1530
1531 stage.num_stats = 1;
1532 stage.code = brw_compile_cs(compiler, pipeline->device, mem_ctx,
1533 &stage.key.cs, &stage.prog_data.cs,
1534 stage.nir, -1, stage.stats, NULL);
1535 if (stage.code == NULL) {
1536 ralloc_free(mem_ctx);
1537 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1538 }
1539
1540 anv_nir_validate_push_layout(&stage.prog_data.base, &stage.bind_map);
1541
1542 if (!stage.prog_data.cs.uses_num_work_groups) {
1543 assert(stage.bind_map.surface_to_descriptor[0].set ==
1544 ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS);
1545 stage.bind_map.surface_to_descriptor[0].set = ANV_DESCRIPTOR_SET_NULL;
1546 }
1547
1548 const unsigned code_size = stage.prog_data.base.program_size;
1549 bin = anv_device_upload_kernel(pipeline->device, cache,
1550 MESA_SHADER_COMPUTE,
1551 &stage.cache_key, sizeof(stage.cache_key),
1552 stage.code, code_size,
1553 stage.nir->constant_data,
1554 stage.nir->constant_data_size,
1555 &stage.prog_data.base,
1556 sizeof(stage.prog_data.cs),
1557 stage.stats, stage.num_stats,
1558 NULL, &stage.bind_map);
1559 if (!bin) {
1560 ralloc_free(mem_ctx);
1561 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1562 }
1563
1564 stage.feedback.duration = os_time_get_nano() - stage_start;
1565 }
1566
1567 anv_pipeline_add_executables(pipeline, &stage, bin);
1568
1569 ralloc_free(mem_ctx);
1570
1571 if (cache_hit) {
1572 stage.feedback.flags |=
1573 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1574 pipeline_feedback.flags |=
1575 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1576 }
1577 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1578
1579 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1580 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1581 if (create_feedback) {
1582 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1583
1584 assert(create_feedback->pipelineStageCreationFeedbackCount == 1);
1585 create_feedback->pPipelineStageCreationFeedbacks[0] = stage.feedback;
1586 }
1587
1588 pipeline->active_stages = VK_SHADER_STAGE_COMPUTE_BIT;
1589 pipeline->shaders[MESA_SHADER_COMPUTE] = bin;
1590
1591 return VK_SUCCESS;
1592 }
1593
1594 /**
1595 * Copy pipeline state not marked as dynamic.
1596 * Dynamic state is pipeline state which hasn't been provided at pipeline
1597 * creation time, but is dynamically provided afterwards using various
1598 * vkCmdSet* functions.
1599 *
1600 * The set of state considered "non_dynamic" is determined by the pieces of
1601 * state that have their corresponding VkDynamicState enums omitted from
1602 * VkPipelineDynamicStateCreateInfo::pDynamicStates.
1603 *
1604 * @param[out] pipeline Destination non_dynamic state.
1605 * @param[in] pCreateInfo Source of non_dynamic state to be copied.
1606 */
1607 static void
1608 copy_non_dynamic_state(struct anv_pipeline *pipeline,
1609 const VkGraphicsPipelineCreateInfo *pCreateInfo)
1610 {
1611 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
1612 struct anv_subpass *subpass = pipeline->subpass;
1613
1614 pipeline->dynamic_state = default_dynamic_state;
1615
1616 if (pCreateInfo->pDynamicState) {
1617 /* Remove all of the states that are marked as dynamic */
1618 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1619 for (uint32_t s = 0; s < count; s++) {
1620 states &= ~anv_cmd_dirty_bit_for_vk_dynamic_state(
1621 pCreateInfo->pDynamicState->pDynamicStates[s]);
1622 }
1623 }
1624
1625 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
1626
1627 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1628 *
1629 * pViewportState is [...] NULL if the pipeline
1630 * has rasterization disabled.
1631 */
1632 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1633 assert(pCreateInfo->pViewportState);
1634
1635 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1636 if (states & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT) {
1637 typed_memcpy(dynamic->viewport.viewports,
1638 pCreateInfo->pViewportState->pViewports,
1639 pCreateInfo->pViewportState->viewportCount);
1640 }
1641
1642 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1643 if (states & ANV_CMD_DIRTY_DYNAMIC_SCISSOR) {
1644 typed_memcpy(dynamic->scissor.scissors,
1645 pCreateInfo->pViewportState->pScissors,
1646 pCreateInfo->pViewportState->scissorCount);
1647 }
1648 }
1649
1650 if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_WIDTH) {
1651 assert(pCreateInfo->pRasterizationState);
1652 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1653 }
1654
1655 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS) {
1656 assert(pCreateInfo->pRasterizationState);
1657 dynamic->depth_bias.bias =
1658 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1659 dynamic->depth_bias.clamp =
1660 pCreateInfo->pRasterizationState->depthBiasClamp;
1661 dynamic->depth_bias.slope =
1662 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1663 }
1664
1665 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1666 *
1667 * pColorBlendState is [...] NULL if the pipeline has rasterization
1668 * disabled or if the subpass of the render pass the pipeline is
1669 * created against does not use any color attachments.
1670 */
1671 bool uses_color_att = false;
1672 for (unsigned i = 0; i < subpass->color_count; ++i) {
1673 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1674 uses_color_att = true;
1675 break;
1676 }
1677 }
1678
1679 if (uses_color_att &&
1680 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1681 assert(pCreateInfo->pColorBlendState);
1682
1683 if (states & ANV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS)
1684 typed_memcpy(dynamic->blend_constants,
1685 pCreateInfo->pColorBlendState->blendConstants, 4);
1686 }
1687
1688 /* If there is no depthstencil attachment, then don't read
1689 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1690 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1691 * no need to override the depthstencil defaults in
1692 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
1693 *
1694 * Section 9.2 of the Vulkan 1.0.15 spec says:
1695 *
1696 * pDepthStencilState is [...] NULL if the pipeline has rasterization
1697 * disabled or if the subpass of the render pass the pipeline is created
1698 * against does not use a depth/stencil attachment.
1699 */
1700 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1701 subpass->depth_stencil_attachment) {
1702 assert(pCreateInfo->pDepthStencilState);
1703
1704 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS) {
1705 dynamic->depth_bounds.min =
1706 pCreateInfo->pDepthStencilState->minDepthBounds;
1707 dynamic->depth_bounds.max =
1708 pCreateInfo->pDepthStencilState->maxDepthBounds;
1709 }
1710
1711 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK) {
1712 dynamic->stencil_compare_mask.front =
1713 pCreateInfo->pDepthStencilState->front.compareMask;
1714 dynamic->stencil_compare_mask.back =
1715 pCreateInfo->pDepthStencilState->back.compareMask;
1716 }
1717
1718 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK) {
1719 dynamic->stencil_write_mask.front =
1720 pCreateInfo->pDepthStencilState->front.writeMask;
1721 dynamic->stencil_write_mask.back =
1722 pCreateInfo->pDepthStencilState->back.writeMask;
1723 }
1724
1725 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE) {
1726 dynamic->stencil_reference.front =
1727 pCreateInfo->pDepthStencilState->front.reference;
1728 dynamic->stencil_reference.back =
1729 pCreateInfo->pDepthStencilState->back.reference;
1730 }
1731 }
1732
1733 const VkPipelineRasterizationLineStateCreateInfoEXT *line_state =
1734 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
1735 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
1736 if (line_state) {
1737 if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_STIPPLE) {
1738 dynamic->line_stipple.factor = line_state->lineStippleFactor;
1739 dynamic->line_stipple.pattern = line_state->lineStipplePattern;
1740 }
1741 }
1742
1743 pipeline->dynamic_state_mask = states;
1744 }
1745
1746 static void
1747 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
1748 {
1749 #ifdef DEBUG
1750 struct anv_render_pass *renderpass = NULL;
1751 struct anv_subpass *subpass = NULL;
1752
1753 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
1754 * present. See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
1755 */
1756 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1757
1758 renderpass = anv_render_pass_from_handle(info->renderPass);
1759 assert(renderpass);
1760
1761 assert(info->subpass < renderpass->subpass_count);
1762 subpass = &renderpass->subpasses[info->subpass];
1763
1764 assert(info->stageCount >= 1);
1765 assert(info->pVertexInputState);
1766 assert(info->pInputAssemblyState);
1767 assert(info->pRasterizationState);
1768 if (!info->pRasterizationState->rasterizerDiscardEnable) {
1769 assert(info->pViewportState);
1770 assert(info->pMultisampleState);
1771
1772 if (subpass && subpass->depth_stencil_attachment)
1773 assert(info->pDepthStencilState);
1774
1775 if (subpass && subpass->color_count > 0) {
1776 bool all_color_unused = true;
1777 for (int i = 0; i < subpass->color_count; i++) {
1778 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
1779 all_color_unused = false;
1780 }
1781 /* pColorBlendState is ignored if the pipeline has rasterization
1782 * disabled or if the subpass of the render pass the pipeline is
1783 * created against does not use any color attachments.
1784 */
1785 assert(info->pColorBlendState || all_color_unused);
1786 }
1787 }
1788
1789 for (uint32_t i = 0; i < info->stageCount; ++i) {
1790 switch (info->pStages[i].stage) {
1791 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
1792 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
1793 assert(info->pTessellationState);
1794 break;
1795 default:
1796 break;
1797 }
1798 }
1799 #endif
1800 }
1801
1802 /**
1803 * Calculate the desired L3 partitioning based on the current state of the
1804 * pipeline. For now this simply returns the conservative defaults calculated
1805 * by get_default_l3_weights(), but we could probably do better by gathering
1806 * more statistics from the pipeline state (e.g. guess of expected URB usage
1807 * and bound surfaces), or by using feed-back from performance counters.
1808 */
1809 void
1810 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
1811 {
1812 const struct gen_device_info *devinfo = &pipeline->device->info;
1813
1814 const struct gen_l3_weights w =
1815 gen_get_default_l3_weights(devinfo, true, needs_slm);
1816
1817 pipeline->l3_config = gen_get_l3_config(devinfo, w);
1818 }
1819
1820 VkResult
1821 anv_pipeline_init(struct anv_pipeline *pipeline,
1822 struct anv_device *device,
1823 struct anv_pipeline_cache *cache,
1824 const VkGraphicsPipelineCreateInfo *pCreateInfo,
1825 const VkAllocationCallbacks *alloc)
1826 {
1827 VkResult result;
1828
1829 anv_pipeline_validate_create_info(pCreateInfo);
1830
1831 if (alloc == NULL)
1832 alloc = &device->alloc;
1833
1834 pipeline->device = device;
1835 pipeline->type = ANV_PIPELINE_GRAPHICS;
1836
1837 ANV_FROM_HANDLE(anv_render_pass, render_pass, pCreateInfo->renderPass);
1838 assert(pCreateInfo->subpass < render_pass->subpass_count);
1839 pipeline->subpass = &render_pass->subpasses[pCreateInfo->subpass];
1840
1841 result = anv_reloc_list_init(&pipeline->batch_relocs, alloc);
1842 if (result != VK_SUCCESS)
1843 return result;
1844
1845 pipeline->batch.alloc = alloc;
1846 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1847 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1848 pipeline->batch.relocs = &pipeline->batch_relocs;
1849 pipeline->batch.status = VK_SUCCESS;
1850
1851 pipeline->mem_ctx = ralloc_context(NULL);
1852 pipeline->flags = pCreateInfo->flags;
1853
1854 assert(pCreateInfo->pRasterizationState);
1855
1856 copy_non_dynamic_state(pipeline, pCreateInfo);
1857 pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState->depthClampEnable;
1858
1859 /* Previously we enabled depth clipping when !depthClampEnable.
1860 * DepthClipStateCreateInfo now makes depth clipping explicit so if the
1861 * clipping info is available, use its enable value to determine clipping,
1862 * otherwise fallback to the previous !depthClampEnable logic.
1863 */
1864 const VkPipelineRasterizationDepthClipStateCreateInfoEXT *clip_info =
1865 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
1866 PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
1867 pipeline->depth_clip_enable = clip_info ? clip_info->depthClipEnable : !pipeline->depth_clamp_enable;
1868
1869 pipeline->sample_shading_enable =
1870 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1871 pCreateInfo->pMultisampleState &&
1872 pCreateInfo->pMultisampleState->sampleShadingEnable;
1873
1874 /* When we free the pipeline, we detect stages based on the NULL status
1875 * of various prog_data pointers. Make them NULL by default.
1876 */
1877 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1878
1879 util_dynarray_init(&pipeline->executables, pipeline->mem_ctx);
1880
1881 result = anv_pipeline_compile_graphics(pipeline, cache, pCreateInfo);
1882 if (result != VK_SUCCESS) {
1883 ralloc_free(pipeline->mem_ctx);
1884 anv_reloc_list_finish(&pipeline->batch_relocs, alloc);
1885 return result;
1886 }
1887
1888 assert(pipeline->shaders[MESA_SHADER_VERTEX]);
1889
1890 anv_pipeline_setup_l3_config(pipeline, false);
1891
1892 const VkPipelineVertexInputStateCreateInfo *vi_info =
1893 pCreateInfo->pVertexInputState;
1894
1895 const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
1896
1897 pipeline->vb_used = 0;
1898 for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
1899 const VkVertexInputAttributeDescription *desc =
1900 &vi_info->pVertexAttributeDescriptions[i];
1901
1902 if (inputs_read & (1ull << (VERT_ATTRIB_GENERIC0 + desc->location)))
1903 pipeline->vb_used |= 1 << desc->binding;
1904 }
1905
1906 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1907 const VkVertexInputBindingDescription *desc =
1908 &vi_info->pVertexBindingDescriptions[i];
1909
1910 pipeline->vb[desc->binding].stride = desc->stride;
1911
1912 /* Step rate is programmed per vertex element (attribute), not
1913 * binding. Set up a map of which bindings step per instance, for
1914 * reference by vertex element setup. */
1915 switch (desc->inputRate) {
1916 default:
1917 case VK_VERTEX_INPUT_RATE_VERTEX:
1918 pipeline->vb[desc->binding].instanced = false;
1919 break;
1920 case VK_VERTEX_INPUT_RATE_INSTANCE:
1921 pipeline->vb[desc->binding].instanced = true;
1922 break;
1923 }
1924
1925 pipeline->vb[desc->binding].instance_divisor = 1;
1926 }
1927
1928 const VkPipelineVertexInputDivisorStateCreateInfoEXT *vi_div_state =
1929 vk_find_struct_const(vi_info->pNext,
1930 PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
1931 if (vi_div_state) {
1932 for (uint32_t i = 0; i < vi_div_state->vertexBindingDivisorCount; i++) {
1933 const VkVertexInputBindingDivisorDescriptionEXT *desc =
1934 &vi_div_state->pVertexBindingDivisors[i];
1935
1936 pipeline->vb[desc->binding].instance_divisor = desc->divisor;
1937 }
1938 }
1939
1940 /* Our implementation of VK_KHR_multiview uses instancing to draw the
1941 * different views. If the client asks for instancing, we need to multiply
1942 * the instance divisor by the number of views ensure that we repeat the
1943 * client's per-instance data once for each view.
1944 */
1945 if (pipeline->subpass->view_mask) {
1946 const uint32_t view_count = anv_subpass_view_count(pipeline->subpass);
1947 for (uint32_t vb = 0; vb < MAX_VBS; vb++) {
1948 if (pipeline->vb[vb].instanced)
1949 pipeline->vb[vb].instance_divisor *= view_count;
1950 }
1951 }
1952
1953 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1954 pCreateInfo->pInputAssemblyState;
1955 const VkPipelineTessellationStateCreateInfo *tess_info =
1956 pCreateInfo->pTessellationState;
1957 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1958
1959 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1960 pipeline->topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
1961 else
1962 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1963
1964 return VK_SUCCESS;
1965 }
1966
1967 #define WRITE_STR(field, ...) ({ \
1968 memset(field, 0, sizeof(field)); \
1969 UNUSED int i = snprintf(field, sizeof(field), __VA_ARGS__); \
1970 assert(i > 0 && i < sizeof(field)); \
1971 })
1972
1973 VkResult anv_GetPipelineExecutablePropertiesKHR(
1974 VkDevice device,
1975 const VkPipelineInfoKHR* pPipelineInfo,
1976 uint32_t* pExecutableCount,
1977 VkPipelineExecutablePropertiesKHR* pProperties)
1978 {
1979 ANV_FROM_HANDLE(anv_pipeline, pipeline, pPipelineInfo->pipeline);
1980 VK_OUTARRAY_MAKE(out, pProperties, pExecutableCount);
1981
1982 util_dynarray_foreach (&pipeline->executables, struct anv_pipeline_executable, exe) {
1983 vk_outarray_append(&out, props) {
1984 gl_shader_stage stage = exe->stage;
1985 props->stages = mesa_to_vk_shader_stage(stage);
1986
1987 unsigned simd_width = exe->stats.dispatch_width;
1988 if (stage == MESA_SHADER_FRAGMENT) {
1989 WRITE_STR(props->name, "%s%d %s",
1990 simd_width ? "SIMD" : "vec",
1991 simd_width ? simd_width : 4,
1992 _mesa_shader_stage_to_string(stage));
1993 } else {
1994 WRITE_STR(props->name, "%s", _mesa_shader_stage_to_string(stage));
1995 }
1996 WRITE_STR(props->description, "%s%d %s shader",
1997 simd_width ? "SIMD" : "vec",
1998 simd_width ? simd_width : 4,
1999 _mesa_shader_stage_to_string(stage));
2000
2001 /* The compiler gives us a dispatch width of 0 for vec4 but Vulkan
2002 * wants a subgroup size of 1.
2003 */
2004 props->subgroupSize = MAX2(simd_width, 1);
2005 }
2006 }
2007
2008 return vk_outarray_status(&out);
2009 }
2010
2011 static const struct anv_pipeline_executable *
2012 anv_pipeline_get_executable(struct anv_pipeline *pipeline, uint32_t index)
2013 {
2014 assert(index < util_dynarray_num_elements(&pipeline->executables,
2015 struct anv_pipeline_executable));
2016 return util_dynarray_element(
2017 &pipeline->executables, struct anv_pipeline_executable, index);
2018 }
2019
2020 VkResult anv_GetPipelineExecutableStatisticsKHR(
2021 VkDevice device,
2022 const VkPipelineExecutableInfoKHR* pExecutableInfo,
2023 uint32_t* pStatisticCount,
2024 VkPipelineExecutableStatisticKHR* pStatistics)
2025 {
2026 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2027 VK_OUTARRAY_MAKE(out, pStatistics, pStatisticCount);
2028
2029 const struct anv_pipeline_executable *exe =
2030 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2031 const struct brw_stage_prog_data *prog_data =
2032 pipeline->shaders[exe->stage]->prog_data;
2033
2034 vk_outarray_append(&out, stat) {
2035 WRITE_STR(stat->name, "Instruction Count");
2036 WRITE_STR(stat->description,
2037 "Number of GEN instructions in the final generated "
2038 "shader executable.");
2039 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2040 stat->value.u64 = exe->stats.instructions;
2041 }
2042
2043 vk_outarray_append(&out, stat) {
2044 WRITE_STR(stat->name, "Loop Count");
2045 WRITE_STR(stat->description,
2046 "Number of loops (not unrolled) in the final generated "
2047 "shader executable.");
2048 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2049 stat->value.u64 = exe->stats.loops;
2050 }
2051
2052 vk_outarray_append(&out, stat) {
2053 WRITE_STR(stat->name, "Cycle Count");
2054 WRITE_STR(stat->description,
2055 "Estimate of the number of EU cycles required to execute "
2056 "the final generated executable. This is an estimate only "
2057 "and may vary greatly from actual run-time performance.");
2058 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2059 stat->value.u64 = exe->stats.cycles;
2060 }
2061
2062 vk_outarray_append(&out, stat) {
2063 WRITE_STR(stat->name, "Spill Count");
2064 WRITE_STR(stat->description,
2065 "Number of scratch spill operations. This gives a rough "
2066 "estimate of the cost incurred due to spilling temporary "
2067 "values to memory. If this is non-zero, you may want to "
2068 "adjust your shader to reduce register pressure.");
2069 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2070 stat->value.u64 = exe->stats.spills;
2071 }
2072
2073 vk_outarray_append(&out, stat) {
2074 WRITE_STR(stat->name, "Fill Count");
2075 WRITE_STR(stat->description,
2076 "Number of scratch fill operations. This gives a rough "
2077 "estimate of the cost incurred due to spilling temporary "
2078 "values to memory. If this is non-zero, you may want to "
2079 "adjust your shader to reduce register pressure.");
2080 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2081 stat->value.u64 = exe->stats.fills;
2082 }
2083
2084 vk_outarray_append(&out, stat) {
2085 WRITE_STR(stat->name, "Scratch Memory Size");
2086 WRITE_STR(stat->description,
2087 "Number of bytes of scratch memory required by the "
2088 "generated shader executable. If this is non-zero, you "
2089 "may want to adjust your shader to reduce register "
2090 "pressure.");
2091 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2092 stat->value.u64 = prog_data->total_scratch;
2093 }
2094
2095 if (exe->stage == MESA_SHADER_COMPUTE) {
2096 vk_outarray_append(&out, stat) {
2097 WRITE_STR(stat->name, "Workgroup Memory Size");
2098 WRITE_STR(stat->description,
2099 "Number of bytes of workgroup shared memory used by this "
2100 "compute shader including any padding.");
2101 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2102 stat->value.u64 = prog_data->total_scratch;
2103 }
2104 }
2105
2106 return vk_outarray_status(&out);
2107 }
2108
2109 static bool
2110 write_ir_text(VkPipelineExecutableInternalRepresentationKHR* ir,
2111 const char *data)
2112 {
2113 ir->isText = VK_TRUE;
2114
2115 size_t data_len = strlen(data) + 1;
2116
2117 if (ir->pData == NULL) {
2118 ir->dataSize = data_len;
2119 return true;
2120 }
2121
2122 strncpy(ir->pData, data, ir->dataSize);
2123 if (ir->dataSize < data_len)
2124 return false;
2125
2126 ir->dataSize = data_len;
2127 return true;
2128 }
2129
2130 VkResult anv_GetPipelineExecutableInternalRepresentationsKHR(
2131 VkDevice device,
2132 const VkPipelineExecutableInfoKHR* pExecutableInfo,
2133 uint32_t* pInternalRepresentationCount,
2134 VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations)
2135 {
2136 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2137 VK_OUTARRAY_MAKE(out, pInternalRepresentations,
2138 pInternalRepresentationCount);
2139 bool incomplete_text = false;
2140
2141 const struct anv_pipeline_executable *exe =
2142 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2143
2144 if (exe->nir) {
2145 vk_outarray_append(&out, ir) {
2146 WRITE_STR(ir->name, "Final NIR");
2147 WRITE_STR(ir->description,
2148 "Final NIR before going into the back-end compiler");
2149
2150 if (!write_ir_text(ir, exe->nir))
2151 incomplete_text = true;
2152 }
2153 }
2154
2155 if (exe->disasm) {
2156 vk_outarray_append(&out, ir) {
2157 WRITE_STR(ir->name, "GEN Assembly");
2158 WRITE_STR(ir->description,
2159 "Final GEN assembly for the generated shader binary");
2160
2161 if (!write_ir_text(ir, exe->disasm))
2162 incomplete_text = true;
2163 }
2164 }
2165
2166 return incomplete_text ? VK_INCOMPLETE : vk_outarray_status(&out);
2167 }