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