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