anv: Implement VK_NV_compute_shader_derivatives
[mesa.git] / src / intel / vulkan / anv_pipeline.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "util/mesa-sha1.h"
31 #include "util/os_time.h"
32 #include "common/gen_l3_config.h"
33 #include "anv_private.h"
34 #include "compiler/brw_nir.h"
35 #include "anv_nir.h"
36 #include "nir/nir_xfb_info.h"
37 #include "spirv/nir_spirv.h"
38 #include "vk_util.h"
39
40 /* Needed for SWIZZLE macros */
41 #include "program/prog_instruction.h"
42
43 // Shader functions
44
45 VkResult anv_CreateShaderModule(
46 VkDevice _device,
47 const VkShaderModuleCreateInfo* pCreateInfo,
48 const VkAllocationCallbacks* pAllocator,
49 VkShaderModule* pShaderModule)
50 {
51 ANV_FROM_HANDLE(anv_device, device, _device);
52 struct anv_shader_module *module;
53
54 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
55 assert(pCreateInfo->flags == 0);
56
57 module = vk_alloc2(&device->alloc, pAllocator,
58 sizeof(*module) + pCreateInfo->codeSize, 8,
59 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
60 if (module == NULL)
61 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
62
63 module->size = pCreateInfo->codeSize;
64 memcpy(module->data, pCreateInfo->pCode, module->size);
65
66 _mesa_sha1_compute(module->data, module->size, module->sha1);
67
68 *pShaderModule = anv_shader_module_to_handle(module);
69
70 return VK_SUCCESS;
71 }
72
73 void anv_DestroyShaderModule(
74 VkDevice _device,
75 VkShaderModule _module,
76 const VkAllocationCallbacks* pAllocator)
77 {
78 ANV_FROM_HANDLE(anv_device, device, _device);
79 ANV_FROM_HANDLE(anv_shader_module, module, _module);
80
81 if (!module)
82 return;
83
84 vk_free2(&device->alloc, pAllocator, module);
85 }
86
87 #define SPIR_V_MAGIC_NUMBER 0x07230203
88
89 static const uint64_t stage_to_debug[] = {
90 [MESA_SHADER_VERTEX] = DEBUG_VS,
91 [MESA_SHADER_TESS_CTRL] = DEBUG_TCS,
92 [MESA_SHADER_TESS_EVAL] = DEBUG_TES,
93 [MESA_SHADER_GEOMETRY] = DEBUG_GS,
94 [MESA_SHADER_FRAGMENT] = DEBUG_WM,
95 [MESA_SHADER_COMPUTE] = DEBUG_CS,
96 };
97
98 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
99 * we can't do that yet because we don't have the ability to copy nir.
100 */
101 static nir_shader *
102 anv_shader_compile_to_nir(struct anv_device *device,
103 void *mem_ctx,
104 const struct anv_shader_module *module,
105 const char *entrypoint_name,
106 gl_shader_stage stage,
107 const VkSpecializationInfo *spec_info)
108 {
109 const struct anv_physical_device *pdevice =
110 &device->instance->physicalDevice;
111 const struct brw_compiler *compiler = pdevice->compiler;
112 const nir_shader_compiler_options *nir_options =
113 compiler->glsl_compiler_options[stage].NirOptions;
114
115 uint32_t *spirv = (uint32_t *) module->data;
116 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
117 assert(module->size % 4 == 0);
118
119 uint32_t num_spec_entries = 0;
120 struct nir_spirv_specialization *spec_entries = NULL;
121 if (spec_info && spec_info->mapEntryCount > 0) {
122 num_spec_entries = spec_info->mapEntryCount;
123 spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
124 for (uint32_t i = 0; i < num_spec_entries; i++) {
125 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
126 const void *data = spec_info->pData + entry.offset;
127 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
128
129 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
130 if (spec_info->dataSize == 8)
131 spec_entries[i].data64 = *(const uint64_t *)data;
132 else
133 spec_entries[i].data32 = *(const uint32_t *)data;
134 }
135 }
136
137 struct spirv_to_nir_options spirv_options = {
138 .lower_workgroup_access_to_offsets = true,
139 .caps = {
140 .derivative_group = true,
141 .device_group = true,
142 .draw_parameters = true,
143 .float64 = pdevice->info.gen >= 8,
144 .geometry_streams = true,
145 .image_write_without_format = true,
146 .int16 = pdevice->info.gen >= 8,
147 .int64 = pdevice->info.gen >= 8,
148 .min_lod = true,
149 .multiview = true,
150 .physical_storage_buffer_address = pdevice->info.gen >= 8 &&
151 pdevice->use_softpin,
152 .post_depth_coverage = pdevice->info.gen >= 9,
153 .shader_viewport_index_layer = true,
154 .stencil_export = pdevice->info.gen >= 9,
155 .storage_8bit = pdevice->info.gen >= 8,
156 .storage_16bit = pdevice->info.gen >= 8,
157 .subgroup_arithmetic = true,
158 .subgroup_basic = true,
159 .subgroup_ballot = true,
160 .subgroup_quad = true,
161 .subgroup_shuffle = true,
162 .subgroup_vote = true,
163 .tessellation = true,
164 .transform_feedback = pdevice->info.gen >= 8,
165 .variable_pointers = true,
166 },
167 .ubo_ptr_type = glsl_vector_type(GLSL_TYPE_UINT, 2),
168 .ssbo_ptr_type = glsl_vector_type(GLSL_TYPE_UINT, 2),
169 .phys_ssbo_ptr_type = glsl_vector_type(GLSL_TYPE_UINT64, 1),
170 .push_const_ptr_type = glsl_uint_type(),
171 .shared_ptr_type = glsl_uint_type(),
172 };
173
174 nir_function *entry_point =
175 spirv_to_nir(spirv, module->size / 4,
176 spec_entries, num_spec_entries,
177 stage, entrypoint_name, &spirv_options, nir_options);
178 nir_shader *nir = entry_point->shader;
179 assert(nir->info.stage == stage);
180 nir_validate_shader(nir, "after spirv_to_nir");
181 ralloc_steal(mem_ctx, nir);
182
183 free(spec_entries);
184
185 if (unlikely(INTEL_DEBUG & stage_to_debug[stage])) {
186 fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
187 gl_shader_stage_name(stage));
188 nir_print_shader(nir, stderr);
189 }
190
191 /* We have to lower away local constant initializers right before we
192 * inline functions. That way they get properly initialized at the top
193 * of the function and not at the top of its caller.
194 */
195 NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_function_temp);
196 NIR_PASS_V(nir, nir_lower_returns);
197 NIR_PASS_V(nir, nir_inline_functions);
198 NIR_PASS_V(nir, nir_opt_deref);
199
200 /* Pick off the single entrypoint that we want */
201 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
202 if (func != entry_point)
203 exec_node_remove(&func->node);
204 }
205 assert(exec_list_length(&nir->functions) == 1);
206
207 /* Now that we've deleted all but the main function, we can go ahead and
208 * lower the rest of the constant initializers. We do this here so that
209 * nir_remove_dead_variables and split_per_member_structs below see the
210 * corresponding stores.
211 */
212 NIR_PASS_V(nir, nir_lower_constant_initializers, ~0);
213
214 /* Split member structs. We do this before lower_io_to_temporaries so that
215 * it doesn't lower system values to temporaries by accident.
216 */
217 NIR_PASS_V(nir, nir_split_var_copies);
218 NIR_PASS_V(nir, nir_split_per_member_structs);
219
220 NIR_PASS_V(nir, nir_remove_dead_variables,
221 nir_var_shader_in | nir_var_shader_out | nir_var_system_value);
222
223 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_global,
224 nir_address_format_64bit_global);
225
226 NIR_PASS_V(nir, nir_propagate_invariant);
227 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
228 entry_point->impl, true, false);
229
230 NIR_PASS_V(nir, nir_lower_frexp);
231
232 /* Vulkan uses the separate-shader linking model */
233 nir->info.separate_shader = true;
234
235 nir = brw_preprocess_nir(compiler, nir, NULL);
236
237 return nir;
238 }
239
240 void anv_DestroyPipeline(
241 VkDevice _device,
242 VkPipeline _pipeline,
243 const VkAllocationCallbacks* pAllocator)
244 {
245 ANV_FROM_HANDLE(anv_device, device, _device);
246 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
247
248 if (!pipeline)
249 return;
250
251 anv_reloc_list_finish(&pipeline->batch_relocs,
252 pAllocator ? pAllocator : &device->alloc);
253 if (pipeline->blend_state.map)
254 anv_state_pool_free(&device->dynamic_state_pool, pipeline->blend_state);
255
256 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
257 if (pipeline->shaders[s])
258 anv_shader_bin_unref(device, pipeline->shaders[s]);
259 }
260
261 vk_free2(&device->alloc, pAllocator, pipeline);
262 }
263
264 static const uint32_t vk_to_gen_primitive_type[] = {
265 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
266 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
267 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
268 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
269 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
270 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
271 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
272 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
273 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
274 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
275 };
276
277 static void
278 populate_sampler_prog_key(const struct gen_device_info *devinfo,
279 struct brw_sampler_prog_key_data *key)
280 {
281 /* Almost all multisampled textures are compressed. The only time when we
282 * don't compress a multisampled texture is for 16x MSAA with a surface
283 * width greater than 8k which is a bit of an edge case. Since the sampler
284 * just ignores the MCS parameter to ld2ms when MCS is disabled, it's safe
285 * to tell the compiler to always assume compression.
286 */
287 key->compressed_multisample_layout_mask = ~0;
288
289 /* SkyLake added support for 16x MSAA. With this came a new message for
290 * reading from a 16x MSAA surface with compression. The new message was
291 * needed because now the MCS data is 64 bits instead of 32 or lower as is
292 * the case for 8x, 4x, and 2x. The key->msaa_16 bit-field controls which
293 * message we use. Fortunately, the 16x message works for 8x, 4x, and 2x
294 * so we can just use it unconditionally. This may not be quite as
295 * efficient but it saves us from recompiling.
296 */
297 if (devinfo->gen >= 9)
298 key->msaa_16 = ~0;
299
300 /* XXX: Handle texture swizzle on HSW- */
301 for (int i = 0; i < MAX_SAMPLERS; i++) {
302 /* Assume color sampler, no swizzling. (Works for BDW+) */
303 key->swizzles[i] = SWIZZLE_XYZW;
304 }
305 }
306
307 static void
308 populate_vs_prog_key(const struct gen_device_info *devinfo,
309 struct brw_vs_prog_key *key)
310 {
311 memset(key, 0, sizeof(*key));
312
313 populate_sampler_prog_key(devinfo, &key->tex);
314
315 /* XXX: Handle vertex input work-arounds */
316
317 /* XXX: Handle sampler_prog_key */
318 }
319
320 static void
321 populate_tcs_prog_key(const struct gen_device_info *devinfo,
322 unsigned input_vertices,
323 struct brw_tcs_prog_key *key)
324 {
325 memset(key, 0, sizeof(*key));
326
327 populate_sampler_prog_key(devinfo, &key->tex);
328
329 key->input_vertices = input_vertices;
330 }
331
332 static void
333 populate_tes_prog_key(const struct gen_device_info *devinfo,
334 struct brw_tes_prog_key *key)
335 {
336 memset(key, 0, sizeof(*key));
337
338 populate_sampler_prog_key(devinfo, &key->tex);
339 }
340
341 static void
342 populate_gs_prog_key(const struct gen_device_info *devinfo,
343 struct brw_gs_prog_key *key)
344 {
345 memset(key, 0, sizeof(*key));
346
347 populate_sampler_prog_key(devinfo, &key->tex);
348 }
349
350 static void
351 populate_wm_prog_key(const struct gen_device_info *devinfo,
352 const struct anv_subpass *subpass,
353 const VkPipelineMultisampleStateCreateInfo *ms_info,
354 struct brw_wm_prog_key *key)
355 {
356 memset(key, 0, sizeof(*key));
357
358 populate_sampler_prog_key(devinfo, &key->tex);
359
360 /* We set this to 0 here and set to the actual value before we call
361 * brw_compile_fs.
362 */
363 key->input_slots_valid = 0;
364
365 /* Vulkan doesn't specify a default */
366 key->high_quality_derivatives = false;
367
368 /* XXX Vulkan doesn't appear to specify */
369 key->clamp_fragment_color = false;
370
371 assert(subpass->color_count <= MAX_RTS);
372 for (uint32_t i = 0; i < subpass->color_count; i++) {
373 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
374 key->color_outputs_valid |= (1 << i);
375 }
376
377 key->nr_color_regions = util_bitcount(key->color_outputs_valid);
378
379 /* To reduce possible shader recompilations we would need to know if
380 * there is a SampleMask output variable to compute if we should emit
381 * code to workaround the issue that hardware disables alpha to coverage
382 * when there is SampleMask output.
383 */
384 key->alpha_to_coverage = ms_info && ms_info->alphaToCoverageEnable;
385
386 /* Vulkan doesn't support fixed-function alpha test */
387 key->alpha_test_replicate_alpha = false;
388
389 if (ms_info) {
390 /* We should probably pull this out of the shader, but it's fairly
391 * harmless to compute it and then let dead-code take care of it.
392 */
393 if (ms_info->rasterizationSamples > 1) {
394 key->persample_interp =
395 (ms_info->minSampleShading * ms_info->rasterizationSamples) > 1;
396 key->multisample_fbo = true;
397 }
398
399 key->frag_coord_adds_sample_pos = ms_info->sampleShadingEnable;
400 }
401 }
402
403 static void
404 populate_cs_prog_key(const struct gen_device_info *devinfo,
405 struct brw_cs_prog_key *key)
406 {
407 memset(key, 0, sizeof(*key));
408
409 populate_sampler_prog_key(devinfo, &key->tex);
410 }
411
412 struct anv_pipeline_stage {
413 gl_shader_stage stage;
414
415 const struct anv_shader_module *module;
416 const char *entrypoint;
417 const VkSpecializationInfo *spec_info;
418
419 unsigned char shader_sha1[20];
420
421 union brw_any_prog_key key;
422
423 struct {
424 gl_shader_stage stage;
425 unsigned char sha1[20];
426 } cache_key;
427
428 nir_shader *nir;
429
430 struct anv_pipeline_binding surface_to_descriptor[256];
431 struct anv_pipeline_binding sampler_to_descriptor[256];
432 struct anv_pipeline_bind_map bind_map;
433
434 union brw_any_prog_data prog_data;
435
436 VkPipelineCreationFeedbackEXT feedback;
437 };
438
439 static void
440 anv_pipeline_hash_shader(const struct anv_shader_module *module,
441 const char *entrypoint,
442 gl_shader_stage stage,
443 const VkSpecializationInfo *spec_info,
444 unsigned char *sha1_out)
445 {
446 struct mesa_sha1 ctx;
447 _mesa_sha1_init(&ctx);
448
449 _mesa_sha1_update(&ctx, module->sha1, sizeof(module->sha1));
450 _mesa_sha1_update(&ctx, entrypoint, strlen(entrypoint));
451 _mesa_sha1_update(&ctx, &stage, sizeof(stage));
452 if (spec_info) {
453 _mesa_sha1_update(&ctx, spec_info->pMapEntries,
454 spec_info->mapEntryCount *
455 sizeof(*spec_info->pMapEntries));
456 _mesa_sha1_update(&ctx, spec_info->pData,
457 spec_info->dataSize);
458 }
459
460 _mesa_sha1_final(&ctx, sha1_out);
461 }
462
463 static void
464 anv_pipeline_hash_graphics(struct anv_pipeline *pipeline,
465 struct anv_pipeline_layout *layout,
466 struct anv_pipeline_stage *stages,
467 unsigned char *sha1_out)
468 {
469 struct mesa_sha1 ctx;
470 _mesa_sha1_init(&ctx);
471
472 _mesa_sha1_update(&ctx, &pipeline->subpass->view_mask,
473 sizeof(pipeline->subpass->view_mask));
474
475 if (layout)
476 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
477
478 const bool rba = pipeline->device->robust_buffer_access;
479 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
480
481 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
482 if (stages[s].entrypoint) {
483 _mesa_sha1_update(&ctx, stages[s].shader_sha1,
484 sizeof(stages[s].shader_sha1));
485 _mesa_sha1_update(&ctx, &stages[s].key, brw_prog_key_size(s));
486 }
487 }
488
489 _mesa_sha1_final(&ctx, sha1_out);
490 }
491
492 static void
493 anv_pipeline_hash_compute(struct anv_pipeline *pipeline,
494 struct anv_pipeline_layout *layout,
495 struct anv_pipeline_stage *stage,
496 unsigned char *sha1_out)
497 {
498 struct mesa_sha1 ctx;
499 _mesa_sha1_init(&ctx);
500
501 if (layout)
502 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
503
504 const bool rba = pipeline->device->robust_buffer_access;
505 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
506
507 _mesa_sha1_update(&ctx, stage->shader_sha1,
508 sizeof(stage->shader_sha1));
509 _mesa_sha1_update(&ctx, &stage->key.cs, sizeof(stage->key.cs));
510
511 _mesa_sha1_final(&ctx, sha1_out);
512 }
513
514 static nir_shader *
515 anv_pipeline_stage_get_nir(struct anv_pipeline *pipeline,
516 struct anv_pipeline_cache *cache,
517 void *mem_ctx,
518 struct anv_pipeline_stage *stage)
519 {
520 const struct brw_compiler *compiler =
521 pipeline->device->instance->physicalDevice.compiler;
522 const nir_shader_compiler_options *nir_options =
523 compiler->glsl_compiler_options[stage->stage].NirOptions;
524 nir_shader *nir;
525
526 nir = anv_device_search_for_nir(pipeline->device, cache,
527 nir_options,
528 stage->shader_sha1,
529 mem_ctx);
530 if (nir) {
531 assert(nir->info.stage == stage->stage);
532 return nir;
533 }
534
535 nir = anv_shader_compile_to_nir(pipeline->device,
536 mem_ctx,
537 stage->module,
538 stage->entrypoint,
539 stage->stage,
540 stage->spec_info);
541 if (nir) {
542 anv_device_upload_nir(pipeline->device, cache, nir, stage->shader_sha1);
543 return nir;
544 }
545
546 return NULL;
547 }
548
549 static void
550 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
551 void *mem_ctx,
552 struct anv_pipeline_stage *stage,
553 struct anv_pipeline_layout *layout)
554 {
555 const struct brw_compiler *compiler =
556 pipeline->device->instance->physicalDevice.compiler;
557
558 struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
559 nir_shader *nir = stage->nir;
560
561 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
562 NIR_PASS_V(nir, nir_lower_wpos_center, pipeline->sample_shading_enable);
563 NIR_PASS_V(nir, anv_nir_lower_input_attachments);
564 }
565
566 NIR_PASS_V(nir, anv_nir_lower_ycbcr_textures, layout);
567
568 NIR_PASS_V(nir, anv_nir_lower_push_constants);
569
570 if (nir->info.stage != MESA_SHADER_COMPUTE)
571 NIR_PASS_V(nir, anv_nir_lower_multiview, pipeline->subpass->view_mask);
572
573 if (nir->info.stage == MESA_SHADER_COMPUTE)
574 prog_data->total_shared = nir->num_shared;
575
576 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
577
578 if (nir->num_uniforms > 0) {
579 assert(prog_data->nr_params == 0);
580
581 /* If the shader uses any push constants at all, we'll just give
582 * them the maximum possible number
583 */
584 assert(nir->num_uniforms <= MAX_PUSH_CONSTANTS_SIZE);
585 nir->num_uniforms = MAX_PUSH_CONSTANTS_SIZE;
586 prog_data->nr_params += MAX_PUSH_CONSTANTS_SIZE / sizeof(float);
587 prog_data->param = ralloc_array(mem_ctx, uint32_t, prog_data->nr_params);
588
589 /* We now set the param values to be offsets into a
590 * anv_push_constant_data structure. Since the compiler doesn't
591 * actually dereference any of the gl_constant_value pointers in the
592 * params array, it doesn't really matter what we put here.
593 */
594 struct anv_push_constants *null_data = NULL;
595 /* Fill out the push constants section of the param array */
596 for (unsigned i = 0; i < MAX_PUSH_CONSTANTS_SIZE / sizeof(float); i++) {
597 prog_data->param[i] = ANV_PARAM_PUSH(
598 (uintptr_t)&null_data->client_data[i * sizeof(float)]);
599 }
600 }
601
602 if (nir->info.num_ssbos > 0 || nir->info.num_images > 0)
603 pipeline->needs_data_cache = true;
604
605 NIR_PASS_V(nir, brw_nir_lower_image_load_store, compiler->devinfo);
606
607 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
608 if (layout) {
609 anv_nir_apply_pipeline_layout(&pipeline->device->instance->physicalDevice,
610 pipeline->device->robust_buffer_access,
611 layout, nir, prog_data,
612 &stage->bind_map);
613
614 NIR_PASS_V(nir, nir_lower_explicit_io,
615 nir_var_mem_ubo | nir_var_mem_ssbo,
616 nir_address_format_32bit_index_offset);
617
618 NIR_PASS_V(nir, nir_opt_constant_folding);
619 }
620
621 if (nir->info.stage != MESA_SHADER_COMPUTE)
622 brw_nir_analyze_ubo_ranges(compiler, nir, NULL, prog_data->ubo_ranges);
623
624 assert(nir->num_uniforms == prog_data->nr_params * 4);
625
626 stage->nir = nir;
627 }
628
629 static void
630 anv_pipeline_link_vs(const struct brw_compiler *compiler,
631 struct anv_pipeline_stage *vs_stage,
632 struct anv_pipeline_stage *next_stage)
633 {
634 if (next_stage)
635 brw_nir_link_shaders(compiler, &vs_stage->nir, &next_stage->nir);
636 }
637
638 static const unsigned *
639 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
640 void *mem_ctx,
641 struct anv_device *device,
642 struct anv_pipeline_stage *vs_stage)
643 {
644 brw_compute_vue_map(compiler->devinfo,
645 &vs_stage->prog_data.vs.base.vue_map,
646 vs_stage->nir->info.outputs_written,
647 vs_stage->nir->info.separate_shader);
648
649 return brw_compile_vs(compiler, device, mem_ctx, &vs_stage->key.vs,
650 &vs_stage->prog_data.vs, vs_stage->nir, -1, NULL);
651 }
652
653 static void
654 merge_tess_info(struct shader_info *tes_info,
655 const struct shader_info *tcs_info)
656 {
657 /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
658 *
659 * "PointMode. Controls generation of points rather than triangles
660 * or lines. This functionality defaults to disabled, and is
661 * enabled if either shader stage includes the execution mode.
662 *
663 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
664 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
665 * and OutputVertices, it says:
666 *
667 * "One mode must be set in at least one of the tessellation
668 * shader stages."
669 *
670 * So, the fields can be set in either the TCS or TES, but they must
671 * agree if set in both. Our backend looks at TES, so bitwise-or in
672 * the values from the TCS.
673 */
674 assert(tcs_info->tess.tcs_vertices_out == 0 ||
675 tes_info->tess.tcs_vertices_out == 0 ||
676 tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
677 tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
678
679 assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
680 tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
681 tcs_info->tess.spacing == tes_info->tess.spacing);
682 tes_info->tess.spacing |= tcs_info->tess.spacing;
683
684 assert(tcs_info->tess.primitive_mode == 0 ||
685 tes_info->tess.primitive_mode == 0 ||
686 tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
687 tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
688 tes_info->tess.ccw |= tcs_info->tess.ccw;
689 tes_info->tess.point_mode |= tcs_info->tess.point_mode;
690 }
691
692 static void
693 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
694 struct anv_pipeline_stage *tcs_stage,
695 struct anv_pipeline_stage *tes_stage)
696 {
697 assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
698
699 brw_nir_link_shaders(compiler, &tcs_stage->nir, &tes_stage->nir);
700
701 nir_lower_patch_vertices(tes_stage->nir,
702 tcs_stage->nir->info.tess.tcs_vertices_out,
703 NULL);
704
705 /* Copy TCS info into the TES info */
706 merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
707
708 /* Whacking the key after cache lookup is a bit sketchy, but all of
709 * this comes from the SPIR-V, which is part of the hash used for the
710 * pipeline cache. So it should be safe.
711 */
712 tcs_stage->key.tcs.tes_primitive_mode =
713 tes_stage->nir->info.tess.primitive_mode;
714 tcs_stage->key.tcs.quads_workaround =
715 compiler->devinfo->gen < 9 &&
716 tes_stage->nir->info.tess.primitive_mode == 7 /* GL_QUADS */ &&
717 tes_stage->nir->info.tess.spacing == TESS_SPACING_EQUAL;
718 }
719
720 static const unsigned *
721 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
722 void *mem_ctx,
723 struct anv_device *device,
724 struct anv_pipeline_stage *tcs_stage,
725 struct anv_pipeline_stage *prev_stage)
726 {
727 tcs_stage->key.tcs.outputs_written =
728 tcs_stage->nir->info.outputs_written;
729 tcs_stage->key.tcs.patch_outputs_written =
730 tcs_stage->nir->info.patch_outputs_written;
731
732 return brw_compile_tcs(compiler, device, mem_ctx, &tcs_stage->key.tcs,
733 &tcs_stage->prog_data.tcs, tcs_stage->nir,
734 -1, NULL);
735 }
736
737 static void
738 anv_pipeline_link_tes(const struct brw_compiler *compiler,
739 struct anv_pipeline_stage *tes_stage,
740 struct anv_pipeline_stage *next_stage)
741 {
742 if (next_stage)
743 brw_nir_link_shaders(compiler, &tes_stage->nir, &next_stage->nir);
744 }
745
746 static const unsigned *
747 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
748 void *mem_ctx,
749 struct anv_device *device,
750 struct anv_pipeline_stage *tes_stage,
751 struct anv_pipeline_stage *tcs_stage)
752 {
753 tes_stage->key.tes.inputs_read =
754 tcs_stage->nir->info.outputs_written;
755 tes_stage->key.tes.patch_inputs_read =
756 tcs_stage->nir->info.patch_outputs_written;
757
758 return brw_compile_tes(compiler, device, mem_ctx, &tes_stage->key.tes,
759 &tcs_stage->prog_data.tcs.base.vue_map,
760 &tes_stage->prog_data.tes, tes_stage->nir,
761 NULL, -1, NULL);
762 }
763
764 static void
765 anv_pipeline_link_gs(const struct brw_compiler *compiler,
766 struct anv_pipeline_stage *gs_stage,
767 struct anv_pipeline_stage *next_stage)
768 {
769 if (next_stage)
770 brw_nir_link_shaders(compiler, &gs_stage->nir, &next_stage->nir);
771 }
772
773 static const unsigned *
774 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
775 void *mem_ctx,
776 struct anv_device *device,
777 struct anv_pipeline_stage *gs_stage,
778 struct anv_pipeline_stage *prev_stage)
779 {
780 brw_compute_vue_map(compiler->devinfo,
781 &gs_stage->prog_data.gs.base.vue_map,
782 gs_stage->nir->info.outputs_written,
783 gs_stage->nir->info.separate_shader);
784
785 return brw_compile_gs(compiler, device, mem_ctx, &gs_stage->key.gs,
786 &gs_stage->prog_data.gs, gs_stage->nir,
787 NULL, -1, NULL);
788 }
789
790 static void
791 anv_pipeline_link_fs(const struct brw_compiler *compiler,
792 struct anv_pipeline_stage *stage)
793 {
794 unsigned num_rts = 0;
795 const int max_rt = FRAG_RESULT_DATA7 - FRAG_RESULT_DATA0 + 1;
796 struct anv_pipeline_binding rt_bindings[max_rt];
797 nir_function_impl *impl = nir_shader_get_entrypoint(stage->nir);
798 int rt_to_bindings[max_rt];
799 memset(rt_to_bindings, -1, sizeof(rt_to_bindings));
800 bool rt_used[max_rt];
801 memset(rt_used, 0, sizeof(rt_used));
802
803 /* Flag used render targets */
804 nir_foreach_variable_safe(var, &stage->nir->outputs) {
805 if (var->data.location < FRAG_RESULT_DATA0)
806 continue;
807
808 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
809 /* Unused or out-of-bounds */
810 if (rt >= MAX_RTS || !(stage->key.wm.color_outputs_valid & (1 << rt)))
811 continue;
812
813 const unsigned array_len =
814 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
815 assert(rt + array_len <= max_rt);
816
817 for (unsigned i = 0; i < array_len; i++)
818 rt_used[rt + i] = true;
819 }
820
821 /* Set new, compacted, location */
822 for (unsigned i = 0; i < max_rt; i++) {
823 if (!rt_used[i])
824 continue;
825
826 rt_to_bindings[i] = num_rts;
827 rt_bindings[rt_to_bindings[i]] = (struct anv_pipeline_binding) {
828 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
829 .binding = 0,
830 .index = i,
831 };
832 num_rts++;
833 }
834
835 bool deleted_output = false;
836 nir_foreach_variable_safe(var, &stage->nir->outputs) {
837 if (var->data.location < FRAG_RESULT_DATA0)
838 continue;
839
840 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
841 if (rt >= MAX_RTS ||
842 !(stage->key.wm.color_outputs_valid & (1 << rt))) {
843 /* Unused or out-of-bounds, throw it away */
844 deleted_output = true;
845 var->data.mode = nir_var_function_temp;
846 exec_node_remove(&var->node);
847 exec_list_push_tail(&impl->locals, &var->node);
848 continue;
849 }
850
851 /* Give it the new location */
852 assert(rt_to_bindings[rt] != -1);
853 var->data.location = rt_to_bindings[rt] + FRAG_RESULT_DATA0;
854 }
855
856 if (deleted_output)
857 nir_fixup_deref_modes(stage->nir);
858
859 if (num_rts == 0) {
860 /* If we have no render targets, we need a null render target */
861 rt_bindings[0] = (struct anv_pipeline_binding) {
862 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
863 .binding = 0,
864 .index = UINT32_MAX,
865 };
866 num_rts = 1;
867 }
868
869 /* Now that we've determined the actual number of render targets, adjust
870 * the key accordingly.
871 */
872 stage->key.wm.nr_color_regions = num_rts;
873 stage->key.wm.color_outputs_valid = (1 << num_rts) - 1;
874
875 assert(num_rts <= max_rt);
876 assert(stage->bind_map.surface_count == 0);
877 typed_memcpy(stage->bind_map.surface_to_descriptor,
878 rt_bindings, num_rts);
879 stage->bind_map.surface_count += num_rts;
880 }
881
882 static const unsigned *
883 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
884 void *mem_ctx,
885 struct anv_device *device,
886 struct anv_pipeline_stage *fs_stage,
887 struct anv_pipeline_stage *prev_stage)
888 {
889 /* TODO: we could set this to 0 based on the information in nir_shader, but
890 * we need this before we call spirv_to_nir.
891 */
892 assert(prev_stage);
893 fs_stage->key.wm.input_slots_valid =
894 prev_stage->prog_data.vue.vue_map.slots_valid;
895
896 const unsigned *code =
897 brw_compile_fs(compiler, device, mem_ctx, &fs_stage->key.wm,
898 &fs_stage->prog_data.wm, fs_stage->nir,
899 NULL, -1, -1, -1, true, false, NULL, NULL);
900
901 if (fs_stage->key.wm.nr_color_regions == 0 &&
902 !fs_stage->prog_data.wm.has_side_effects &&
903 !fs_stage->prog_data.wm.uses_kill &&
904 fs_stage->prog_data.wm.computed_depth_mode == BRW_PSCDEPTH_OFF &&
905 !fs_stage->prog_data.wm.computed_stencil) {
906 /* This fragment shader has no outputs and no side effects. Go ahead
907 * and return the code pointer so we don't accidentally think the
908 * compile failed but zero out prog_data which will set program_size to
909 * zero and disable the stage.
910 */
911 memset(&fs_stage->prog_data, 0, sizeof(fs_stage->prog_data));
912 }
913
914 return code;
915 }
916
917 static VkResult
918 anv_pipeline_compile_graphics(struct anv_pipeline *pipeline,
919 struct anv_pipeline_cache *cache,
920 const VkGraphicsPipelineCreateInfo *info)
921 {
922 VkPipelineCreationFeedbackEXT pipeline_feedback = {
923 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
924 };
925 int64_t pipeline_start = os_time_get_nano();
926
927 const struct brw_compiler *compiler =
928 pipeline->device->instance->physicalDevice.compiler;
929 struct anv_pipeline_stage stages[MESA_SHADER_STAGES] = {};
930
931 pipeline->active_stages = 0;
932
933 VkResult result;
934 for (uint32_t i = 0; i < info->stageCount; i++) {
935 const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
936 gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
937
938 pipeline->active_stages |= sinfo->stage;
939
940 int64_t stage_start = os_time_get_nano();
941
942 stages[stage].stage = stage;
943 stages[stage].module = anv_shader_module_from_handle(sinfo->module);
944 stages[stage].entrypoint = sinfo->pName;
945 stages[stage].spec_info = sinfo->pSpecializationInfo;
946 anv_pipeline_hash_shader(stages[stage].module,
947 stages[stage].entrypoint,
948 stage,
949 stages[stage].spec_info,
950 stages[stage].shader_sha1);
951
952 const struct gen_device_info *devinfo = &pipeline->device->info;
953 switch (stage) {
954 case MESA_SHADER_VERTEX:
955 populate_vs_prog_key(devinfo, &stages[stage].key.vs);
956 break;
957 case MESA_SHADER_TESS_CTRL:
958 populate_tcs_prog_key(devinfo,
959 info->pTessellationState->patchControlPoints,
960 &stages[stage].key.tcs);
961 break;
962 case MESA_SHADER_TESS_EVAL:
963 populate_tes_prog_key(devinfo, &stages[stage].key.tes);
964 break;
965 case MESA_SHADER_GEOMETRY:
966 populate_gs_prog_key(devinfo, &stages[stage].key.gs);
967 break;
968 case MESA_SHADER_FRAGMENT:
969 populate_wm_prog_key(devinfo, pipeline->subpass,
970 info->pMultisampleState,
971 &stages[stage].key.wm);
972 break;
973 default:
974 unreachable("Invalid graphics shader stage");
975 }
976
977 stages[stage].feedback.duration += os_time_get_nano() - stage_start;
978 stages[stage].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT;
979 }
980
981 if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
982 pipeline->active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
983
984 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
985
986 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
987
988 unsigned char sha1[20];
989 anv_pipeline_hash_graphics(pipeline, layout, stages, sha1);
990
991 unsigned found = 0;
992 unsigned cache_hits = 0;
993 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
994 if (!stages[s].entrypoint)
995 continue;
996
997 int64_t stage_start = os_time_get_nano();
998
999 stages[s].cache_key.stage = s;
1000 memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
1001
1002 bool cache_hit;
1003 struct anv_shader_bin *bin =
1004 anv_device_search_for_kernel(pipeline->device, cache,
1005 &stages[s].cache_key,
1006 sizeof(stages[s].cache_key), &cache_hit);
1007 if (bin) {
1008 found++;
1009 pipeline->shaders[s] = bin;
1010 }
1011
1012 if (cache_hit) {
1013 cache_hits++;
1014 stages[s].feedback.flags |=
1015 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1016 }
1017 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1018 }
1019
1020 if (found == __builtin_popcount(pipeline->active_stages)) {
1021 if (cache_hits == found) {
1022 pipeline_feedback.flags |=
1023 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1024 }
1025 /* We found all our shaders in the cache. We're done. */
1026 goto done;
1027 } else if (found > 0) {
1028 /* We found some but not all of our shaders. This shouldn't happen
1029 * most of the time but it can if we have a partially populated
1030 * pipeline cache.
1031 */
1032 assert(found < __builtin_popcount(pipeline->active_stages));
1033
1034 vk_debug_report(&pipeline->device->instance->debug_report_callbacks,
1035 VK_DEBUG_REPORT_WARNING_BIT_EXT |
1036 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
1037 VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,
1038 (uint64_t)(uintptr_t)cache,
1039 0, 0, "anv",
1040 "Found a partial pipeline in the cache. This is "
1041 "most likely caused by an incomplete pipeline cache "
1042 "import or export");
1043
1044 /* We're going to have to recompile anyway, so just throw away our
1045 * references to the shaders in the cache. We'll get them out of the
1046 * cache again as part of the compilation process.
1047 */
1048 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1049 stages[s].feedback.flags = 0;
1050 if (pipeline->shaders[s]) {
1051 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
1052 pipeline->shaders[s] = NULL;
1053 }
1054 }
1055 }
1056
1057 void *pipeline_ctx = ralloc_context(NULL);
1058
1059 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1060 if (!stages[s].entrypoint)
1061 continue;
1062
1063 int64_t stage_start = os_time_get_nano();
1064
1065 assert(stages[s].stage == s);
1066 assert(pipeline->shaders[s] == NULL);
1067
1068 stages[s].bind_map = (struct anv_pipeline_bind_map) {
1069 .surface_to_descriptor = stages[s].surface_to_descriptor,
1070 .sampler_to_descriptor = stages[s].sampler_to_descriptor
1071 };
1072
1073 stages[s].nir = anv_pipeline_stage_get_nir(pipeline, cache,
1074 pipeline_ctx,
1075 &stages[s]);
1076 if (stages[s].nir == NULL) {
1077 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1078 goto fail;
1079 }
1080
1081 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1082 }
1083
1084 /* Walk backwards to link */
1085 struct anv_pipeline_stage *next_stage = NULL;
1086 for (int s = MESA_SHADER_STAGES - 1; s >= 0; s--) {
1087 if (!stages[s].entrypoint)
1088 continue;
1089
1090 switch (s) {
1091 case MESA_SHADER_VERTEX:
1092 anv_pipeline_link_vs(compiler, &stages[s], next_stage);
1093 break;
1094 case MESA_SHADER_TESS_CTRL:
1095 anv_pipeline_link_tcs(compiler, &stages[s], next_stage);
1096 break;
1097 case MESA_SHADER_TESS_EVAL:
1098 anv_pipeline_link_tes(compiler, &stages[s], next_stage);
1099 break;
1100 case MESA_SHADER_GEOMETRY:
1101 anv_pipeline_link_gs(compiler, &stages[s], next_stage);
1102 break;
1103 case MESA_SHADER_FRAGMENT:
1104 anv_pipeline_link_fs(compiler, &stages[s]);
1105 break;
1106 default:
1107 unreachable("Invalid graphics shader stage");
1108 }
1109
1110 next_stage = &stages[s];
1111 }
1112
1113 struct anv_pipeline_stage *prev_stage = NULL;
1114 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1115 if (!stages[s].entrypoint)
1116 continue;
1117
1118 int64_t stage_start = os_time_get_nano();
1119
1120 void *stage_ctx = ralloc_context(NULL);
1121
1122 nir_xfb_info *xfb_info = NULL;
1123 if (s == MESA_SHADER_VERTEX ||
1124 s == MESA_SHADER_TESS_EVAL ||
1125 s == MESA_SHADER_GEOMETRY)
1126 xfb_info = nir_gather_xfb_info(stages[s].nir, stage_ctx);
1127
1128 anv_pipeline_lower_nir(pipeline, stage_ctx, &stages[s], layout);
1129
1130 const unsigned *code;
1131 switch (s) {
1132 case MESA_SHADER_VERTEX:
1133 code = anv_pipeline_compile_vs(compiler, stage_ctx, pipeline->device,
1134 &stages[s]);
1135 break;
1136 case MESA_SHADER_TESS_CTRL:
1137 code = anv_pipeline_compile_tcs(compiler, stage_ctx, pipeline->device,
1138 &stages[s], prev_stage);
1139 break;
1140 case MESA_SHADER_TESS_EVAL:
1141 code = anv_pipeline_compile_tes(compiler, stage_ctx, pipeline->device,
1142 &stages[s], prev_stage);
1143 break;
1144 case MESA_SHADER_GEOMETRY:
1145 code = anv_pipeline_compile_gs(compiler, stage_ctx, pipeline->device,
1146 &stages[s], prev_stage);
1147 break;
1148 case MESA_SHADER_FRAGMENT:
1149 code = anv_pipeline_compile_fs(compiler, stage_ctx, pipeline->device,
1150 &stages[s], prev_stage);
1151 break;
1152 default:
1153 unreachable("Invalid graphics shader stage");
1154 }
1155 if (code == NULL) {
1156 ralloc_free(stage_ctx);
1157 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1158 goto fail;
1159 }
1160
1161 struct anv_shader_bin *bin =
1162 anv_device_upload_kernel(pipeline->device, cache,
1163 &stages[s].cache_key,
1164 sizeof(stages[s].cache_key),
1165 code, stages[s].prog_data.base.program_size,
1166 stages[s].nir->constant_data,
1167 stages[s].nir->constant_data_size,
1168 &stages[s].prog_data.base,
1169 brw_prog_data_size(s),
1170 xfb_info, &stages[s].bind_map);
1171 if (!bin) {
1172 ralloc_free(stage_ctx);
1173 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1174 goto fail;
1175 }
1176
1177 pipeline->shaders[s] = bin;
1178 ralloc_free(stage_ctx);
1179
1180 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1181
1182 prev_stage = &stages[s];
1183 }
1184
1185 ralloc_free(pipeline_ctx);
1186
1187 done:
1188
1189 if (pipeline->shaders[MESA_SHADER_FRAGMENT] &&
1190 pipeline->shaders[MESA_SHADER_FRAGMENT]->prog_data->program_size == 0) {
1191 /* This can happen if we decided to implicitly disable the fragment
1192 * shader. See anv_pipeline_compile_fs().
1193 */
1194 anv_shader_bin_unref(pipeline->device,
1195 pipeline->shaders[MESA_SHADER_FRAGMENT]);
1196 pipeline->shaders[MESA_SHADER_FRAGMENT] = NULL;
1197 pipeline->active_stages &= ~VK_SHADER_STAGE_FRAGMENT_BIT;
1198 }
1199
1200 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1201
1202 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1203 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1204 if (create_feedback) {
1205 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1206
1207 assert(info->stageCount == create_feedback->pipelineStageCreationFeedbackCount);
1208 for (uint32_t i = 0; i < info->stageCount; i++) {
1209 gl_shader_stage s = vk_to_mesa_shader_stage(info->pStages[i].stage);
1210 create_feedback->pPipelineStageCreationFeedbacks[i] = stages[s].feedback;
1211 }
1212 }
1213
1214 return VK_SUCCESS;
1215
1216 fail:
1217 ralloc_free(pipeline_ctx);
1218
1219 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1220 if (pipeline->shaders[s])
1221 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
1222 }
1223
1224 return result;
1225 }
1226
1227 VkResult
1228 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
1229 struct anv_pipeline_cache *cache,
1230 const VkComputePipelineCreateInfo *info,
1231 const struct anv_shader_module *module,
1232 const char *entrypoint,
1233 const VkSpecializationInfo *spec_info)
1234 {
1235 VkPipelineCreationFeedbackEXT pipeline_feedback = {
1236 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1237 };
1238 int64_t pipeline_start = os_time_get_nano();
1239
1240 const struct brw_compiler *compiler =
1241 pipeline->device->instance->physicalDevice.compiler;
1242
1243 struct anv_pipeline_stage stage = {
1244 .stage = MESA_SHADER_COMPUTE,
1245 .module = module,
1246 .entrypoint = entrypoint,
1247 .spec_info = spec_info,
1248 .cache_key = {
1249 .stage = MESA_SHADER_COMPUTE,
1250 },
1251 .feedback = {
1252 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1253 },
1254 };
1255 anv_pipeline_hash_shader(stage.module,
1256 stage.entrypoint,
1257 MESA_SHADER_COMPUTE,
1258 stage.spec_info,
1259 stage.shader_sha1);
1260
1261 struct anv_shader_bin *bin = NULL;
1262
1263 populate_cs_prog_key(&pipeline->device->info, &stage.key.cs);
1264
1265 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1266
1267 anv_pipeline_hash_compute(pipeline, layout, &stage, stage.cache_key.sha1);
1268 bool cache_hit;
1269 bin = anv_device_search_for_kernel(pipeline->device, cache, &stage.cache_key,
1270 sizeof(stage.cache_key), &cache_hit);
1271
1272 if (bin == NULL) {
1273 int64_t stage_start = os_time_get_nano();
1274
1275 stage.bind_map = (struct anv_pipeline_bind_map) {
1276 .surface_to_descriptor = stage.surface_to_descriptor,
1277 .sampler_to_descriptor = stage.sampler_to_descriptor
1278 };
1279
1280 /* Set up a binding for the gl_NumWorkGroups */
1281 stage.bind_map.surface_count = 1;
1282 stage.bind_map.surface_to_descriptor[0] = (struct anv_pipeline_binding) {
1283 .set = ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS,
1284 };
1285
1286 void *mem_ctx = ralloc_context(NULL);
1287
1288 stage.nir = anv_pipeline_stage_get_nir(pipeline, cache, mem_ctx, &stage);
1289 if (stage.nir == NULL) {
1290 ralloc_free(mem_ctx);
1291 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1292 }
1293
1294 anv_pipeline_lower_nir(pipeline, mem_ctx, &stage, layout);
1295
1296 NIR_PASS_V(stage.nir, anv_nir_add_base_work_group_id,
1297 &stage.prog_data.cs);
1298
1299 const unsigned *shader_code =
1300 brw_compile_cs(compiler, pipeline->device, mem_ctx, &stage.key.cs,
1301 &stage.prog_data.cs, stage.nir, -1, NULL);
1302 if (shader_code == NULL) {
1303 ralloc_free(mem_ctx);
1304 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1305 }
1306
1307 const unsigned code_size = stage.prog_data.base.program_size;
1308 bin = anv_device_upload_kernel(pipeline->device, cache,
1309 &stage.cache_key, sizeof(stage.cache_key),
1310 shader_code, code_size,
1311 stage.nir->constant_data,
1312 stage.nir->constant_data_size,
1313 &stage.prog_data.base,
1314 sizeof(stage.prog_data.cs),
1315 NULL, &stage.bind_map);
1316 if (!bin) {
1317 ralloc_free(mem_ctx);
1318 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1319 }
1320
1321 ralloc_free(mem_ctx);
1322
1323 stage.feedback.duration = os_time_get_nano() - stage_start;
1324 }
1325
1326 if (cache_hit) {
1327 stage.feedback.flags |=
1328 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1329 pipeline_feedback.flags |=
1330 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1331 }
1332 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1333
1334 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1335 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1336 if (create_feedback) {
1337 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1338
1339 assert(create_feedback->pipelineStageCreationFeedbackCount == 1);
1340 create_feedback->pPipelineStageCreationFeedbacks[0] = stage.feedback;
1341 }
1342
1343 pipeline->active_stages = VK_SHADER_STAGE_COMPUTE_BIT;
1344 pipeline->shaders[MESA_SHADER_COMPUTE] = bin;
1345
1346 return VK_SUCCESS;
1347 }
1348
1349 /**
1350 * Copy pipeline state not marked as dynamic.
1351 * Dynamic state is pipeline state which hasn't been provided at pipeline
1352 * creation time, but is dynamically provided afterwards using various
1353 * vkCmdSet* functions.
1354 *
1355 * The set of state considered "non_dynamic" is determined by the pieces of
1356 * state that have their corresponding VkDynamicState enums omitted from
1357 * VkPipelineDynamicStateCreateInfo::pDynamicStates.
1358 *
1359 * @param[out] pipeline Destination non_dynamic state.
1360 * @param[in] pCreateInfo Source of non_dynamic state to be copied.
1361 */
1362 static void
1363 copy_non_dynamic_state(struct anv_pipeline *pipeline,
1364 const VkGraphicsPipelineCreateInfo *pCreateInfo)
1365 {
1366 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
1367 struct anv_subpass *subpass = pipeline->subpass;
1368
1369 pipeline->dynamic_state = default_dynamic_state;
1370
1371 if (pCreateInfo->pDynamicState) {
1372 /* Remove all of the states that are marked as dynamic */
1373 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1374 for (uint32_t s = 0; s < count; s++)
1375 states &= ~(1 << pCreateInfo->pDynamicState->pDynamicStates[s]);
1376 }
1377
1378 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
1379
1380 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1381 *
1382 * pViewportState is [...] NULL if the pipeline
1383 * has rasterization disabled.
1384 */
1385 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1386 assert(pCreateInfo->pViewportState);
1387
1388 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1389 if (states & (1 << VK_DYNAMIC_STATE_VIEWPORT)) {
1390 typed_memcpy(dynamic->viewport.viewports,
1391 pCreateInfo->pViewportState->pViewports,
1392 pCreateInfo->pViewportState->viewportCount);
1393 }
1394
1395 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1396 if (states & (1 << VK_DYNAMIC_STATE_SCISSOR)) {
1397 typed_memcpy(dynamic->scissor.scissors,
1398 pCreateInfo->pViewportState->pScissors,
1399 pCreateInfo->pViewportState->scissorCount);
1400 }
1401 }
1402
1403 if (states & (1 << VK_DYNAMIC_STATE_LINE_WIDTH)) {
1404 assert(pCreateInfo->pRasterizationState);
1405 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1406 }
1407
1408 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BIAS)) {
1409 assert(pCreateInfo->pRasterizationState);
1410 dynamic->depth_bias.bias =
1411 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1412 dynamic->depth_bias.clamp =
1413 pCreateInfo->pRasterizationState->depthBiasClamp;
1414 dynamic->depth_bias.slope =
1415 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1416 }
1417
1418 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1419 *
1420 * pColorBlendState is [...] NULL if the pipeline has rasterization
1421 * disabled or if the subpass of the render pass the pipeline is
1422 * created against does not use any color attachments.
1423 */
1424 bool uses_color_att = false;
1425 for (unsigned i = 0; i < subpass->color_count; ++i) {
1426 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1427 uses_color_att = true;
1428 break;
1429 }
1430 }
1431
1432 if (uses_color_att &&
1433 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1434 assert(pCreateInfo->pColorBlendState);
1435
1436 if (states & (1 << VK_DYNAMIC_STATE_BLEND_CONSTANTS))
1437 typed_memcpy(dynamic->blend_constants,
1438 pCreateInfo->pColorBlendState->blendConstants, 4);
1439 }
1440
1441 /* If there is no depthstencil attachment, then don't read
1442 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1443 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1444 * no need to override the depthstencil defaults in
1445 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
1446 *
1447 * Section 9.2 of the Vulkan 1.0.15 spec says:
1448 *
1449 * pDepthStencilState is [...] NULL if the pipeline has rasterization
1450 * disabled or if the subpass of the render pass the pipeline is created
1451 * against does not use a depth/stencil attachment.
1452 */
1453 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1454 subpass->depth_stencil_attachment) {
1455 assert(pCreateInfo->pDepthStencilState);
1456
1457 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BOUNDS)) {
1458 dynamic->depth_bounds.min =
1459 pCreateInfo->pDepthStencilState->minDepthBounds;
1460 dynamic->depth_bounds.max =
1461 pCreateInfo->pDepthStencilState->maxDepthBounds;
1462 }
1463
1464 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
1465 dynamic->stencil_compare_mask.front =
1466 pCreateInfo->pDepthStencilState->front.compareMask;
1467 dynamic->stencil_compare_mask.back =
1468 pCreateInfo->pDepthStencilState->back.compareMask;
1469 }
1470
1471 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
1472 dynamic->stencil_write_mask.front =
1473 pCreateInfo->pDepthStencilState->front.writeMask;
1474 dynamic->stencil_write_mask.back =
1475 pCreateInfo->pDepthStencilState->back.writeMask;
1476 }
1477
1478 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_REFERENCE)) {
1479 dynamic->stencil_reference.front =
1480 pCreateInfo->pDepthStencilState->front.reference;
1481 dynamic->stencil_reference.back =
1482 pCreateInfo->pDepthStencilState->back.reference;
1483 }
1484 }
1485
1486 pipeline->dynamic_state_mask = states;
1487 }
1488
1489 static void
1490 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
1491 {
1492 #ifdef DEBUG
1493 struct anv_render_pass *renderpass = NULL;
1494 struct anv_subpass *subpass = NULL;
1495
1496 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
1497 * present. See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
1498 */
1499 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1500
1501 renderpass = anv_render_pass_from_handle(info->renderPass);
1502 assert(renderpass);
1503
1504 assert(info->subpass < renderpass->subpass_count);
1505 subpass = &renderpass->subpasses[info->subpass];
1506
1507 assert(info->stageCount >= 1);
1508 assert(info->pVertexInputState);
1509 assert(info->pInputAssemblyState);
1510 assert(info->pRasterizationState);
1511 if (!info->pRasterizationState->rasterizerDiscardEnable) {
1512 assert(info->pViewportState);
1513 assert(info->pMultisampleState);
1514
1515 if (subpass && subpass->depth_stencil_attachment)
1516 assert(info->pDepthStencilState);
1517
1518 if (subpass && subpass->color_count > 0) {
1519 bool all_color_unused = true;
1520 for (int i = 0; i < subpass->color_count; i++) {
1521 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
1522 all_color_unused = false;
1523 }
1524 /* pColorBlendState is ignored if the pipeline has rasterization
1525 * disabled or if the subpass of the render pass the pipeline is
1526 * created against does not use any color attachments.
1527 */
1528 assert(info->pColorBlendState || all_color_unused);
1529 }
1530 }
1531
1532 for (uint32_t i = 0; i < info->stageCount; ++i) {
1533 switch (info->pStages[i].stage) {
1534 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
1535 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
1536 assert(info->pTessellationState);
1537 break;
1538 default:
1539 break;
1540 }
1541 }
1542 #endif
1543 }
1544
1545 /**
1546 * Calculate the desired L3 partitioning based on the current state of the
1547 * pipeline. For now this simply returns the conservative defaults calculated
1548 * by get_default_l3_weights(), but we could probably do better by gathering
1549 * more statistics from the pipeline state (e.g. guess of expected URB usage
1550 * and bound surfaces), or by using feed-back from performance counters.
1551 */
1552 void
1553 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
1554 {
1555 const struct gen_device_info *devinfo = &pipeline->device->info;
1556
1557 const struct gen_l3_weights w =
1558 gen_get_default_l3_weights(devinfo, pipeline->needs_data_cache, needs_slm);
1559
1560 pipeline->urb.l3_config = gen_get_l3_config(devinfo, w);
1561 pipeline->urb.total_size =
1562 gen_get_l3_config_urb_size(devinfo, pipeline->urb.l3_config);
1563 }
1564
1565 VkResult
1566 anv_pipeline_init(struct anv_pipeline *pipeline,
1567 struct anv_device *device,
1568 struct anv_pipeline_cache *cache,
1569 const VkGraphicsPipelineCreateInfo *pCreateInfo,
1570 const VkAllocationCallbacks *alloc)
1571 {
1572 VkResult result;
1573
1574 anv_pipeline_validate_create_info(pCreateInfo);
1575
1576 if (alloc == NULL)
1577 alloc = &device->alloc;
1578
1579 pipeline->device = device;
1580
1581 ANV_FROM_HANDLE(anv_render_pass, render_pass, pCreateInfo->renderPass);
1582 assert(pCreateInfo->subpass < render_pass->subpass_count);
1583 pipeline->subpass = &render_pass->subpasses[pCreateInfo->subpass];
1584
1585 result = anv_reloc_list_init(&pipeline->batch_relocs, alloc);
1586 if (result != VK_SUCCESS)
1587 return result;
1588
1589 pipeline->batch.alloc = alloc;
1590 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1591 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1592 pipeline->batch.relocs = &pipeline->batch_relocs;
1593 pipeline->batch.status = VK_SUCCESS;
1594
1595 copy_non_dynamic_state(pipeline, pCreateInfo);
1596 pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState &&
1597 pCreateInfo->pRasterizationState->depthClampEnable;
1598
1599 /* Previously we enabled depth clipping when !depthClampEnable.
1600 * DepthClipStateCreateInfo now makes depth clipping explicit so if the
1601 * clipping info is available, use its enable value to determine clipping,
1602 * otherwise fallback to the previous !depthClampEnable logic.
1603 */
1604 const VkPipelineRasterizationDepthClipStateCreateInfoEXT *clip_info =
1605 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
1606 PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
1607 pipeline->depth_clip_enable = clip_info ? clip_info->depthClipEnable : !pipeline->depth_clamp_enable;
1608
1609 pipeline->sample_shading_enable = pCreateInfo->pMultisampleState &&
1610 pCreateInfo->pMultisampleState->sampleShadingEnable;
1611
1612 pipeline->needs_data_cache = false;
1613
1614 /* When we free the pipeline, we detect stages based on the NULL status
1615 * of various prog_data pointers. Make them NULL by default.
1616 */
1617 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1618
1619 result = anv_pipeline_compile_graphics(pipeline, cache, pCreateInfo);
1620 if (result != VK_SUCCESS) {
1621 anv_reloc_list_finish(&pipeline->batch_relocs, alloc);
1622 return result;
1623 }
1624
1625 assert(pipeline->shaders[MESA_SHADER_VERTEX]);
1626
1627 anv_pipeline_setup_l3_config(pipeline, false);
1628
1629 const VkPipelineVertexInputStateCreateInfo *vi_info =
1630 pCreateInfo->pVertexInputState;
1631
1632 const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
1633
1634 pipeline->vb_used = 0;
1635 for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
1636 const VkVertexInputAttributeDescription *desc =
1637 &vi_info->pVertexAttributeDescriptions[i];
1638
1639 if (inputs_read & (1ull << (VERT_ATTRIB_GENERIC0 + desc->location)))
1640 pipeline->vb_used |= 1 << desc->binding;
1641 }
1642
1643 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1644 const VkVertexInputBindingDescription *desc =
1645 &vi_info->pVertexBindingDescriptions[i];
1646
1647 pipeline->vb[desc->binding].stride = desc->stride;
1648
1649 /* Step rate is programmed per vertex element (attribute), not
1650 * binding. Set up a map of which bindings step per instance, for
1651 * reference by vertex element setup. */
1652 switch (desc->inputRate) {
1653 default:
1654 case VK_VERTEX_INPUT_RATE_VERTEX:
1655 pipeline->vb[desc->binding].instanced = false;
1656 break;
1657 case VK_VERTEX_INPUT_RATE_INSTANCE:
1658 pipeline->vb[desc->binding].instanced = true;
1659 break;
1660 }
1661
1662 pipeline->vb[desc->binding].instance_divisor = 1;
1663 }
1664
1665 const VkPipelineVertexInputDivisorStateCreateInfoEXT *vi_div_state =
1666 vk_find_struct_const(vi_info->pNext,
1667 PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
1668 if (vi_div_state) {
1669 for (uint32_t i = 0; i < vi_div_state->vertexBindingDivisorCount; i++) {
1670 const VkVertexInputBindingDivisorDescriptionEXT *desc =
1671 &vi_div_state->pVertexBindingDivisors[i];
1672
1673 pipeline->vb[desc->binding].instance_divisor = desc->divisor;
1674 }
1675 }
1676
1677 /* Our implementation of VK_KHR_multiview uses instancing to draw the
1678 * different views. If the client asks for instancing, we need to multiply
1679 * the instance divisor by the number of views ensure that we repeat the
1680 * client's per-instance data once for each view.
1681 */
1682 if (pipeline->subpass->view_mask) {
1683 const uint32_t view_count = anv_subpass_view_count(pipeline->subpass);
1684 for (uint32_t vb = 0; vb < MAX_VBS; vb++) {
1685 if (pipeline->vb[vb].instanced)
1686 pipeline->vb[vb].instance_divisor *= view_count;
1687 }
1688 }
1689
1690 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1691 pCreateInfo->pInputAssemblyState;
1692 const VkPipelineTessellationStateCreateInfo *tess_info =
1693 pCreateInfo->pTessellationState;
1694 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1695
1696 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1697 pipeline->topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
1698 else
1699 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1700
1701 return VK_SUCCESS;
1702 }