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