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