anv: set input_slots_valid on brw_wm_prog_key
[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 "brw_nir.h"
34 #include "anv_nir.h"
35 #include "spirv/nir_spirv.h"
36
37 /* Needed for SWIZZLE macros */
38 #include "program/prog_instruction.h"
39
40 // Shader functions
41
42 VkResult anv_CreateShaderModule(
43 VkDevice _device,
44 const VkShaderModuleCreateInfo* pCreateInfo,
45 const VkAllocationCallbacks* pAllocator,
46 VkShaderModule* pShaderModule)
47 {
48 ANV_FROM_HANDLE(anv_device, device, _device);
49 struct anv_shader_module *module;
50
51 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
52 assert(pCreateInfo->flags == 0);
53
54 module = vk_alloc2(&device->alloc, pAllocator,
55 sizeof(*module) + pCreateInfo->codeSize, 8,
56 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
57 if (module == NULL)
58 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
59
60 module->size = pCreateInfo->codeSize;
61 memcpy(module->data, pCreateInfo->pCode, module->size);
62
63 _mesa_sha1_compute(module->data, module->size, module->sha1);
64
65 *pShaderModule = anv_shader_module_to_handle(module);
66
67 return VK_SUCCESS;
68 }
69
70 void anv_DestroyShaderModule(
71 VkDevice _device,
72 VkShaderModule _module,
73 const VkAllocationCallbacks* pAllocator)
74 {
75 ANV_FROM_HANDLE(anv_device, device, _device);
76 ANV_FROM_HANDLE(anv_shader_module, module, _module);
77
78 if (!module)
79 return;
80
81 vk_free2(&device->alloc, pAllocator, module);
82 }
83
84 #define SPIR_V_MAGIC_NUMBER 0x07230203
85
86 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
87 * we can't do that yet because we don't have the ability to copy nir.
88 */
89 static nir_shader *
90 anv_shader_compile_to_nir(struct anv_device *device,
91 struct anv_shader_module *module,
92 const char *entrypoint_name,
93 gl_shader_stage stage,
94 const VkSpecializationInfo *spec_info)
95 {
96 if (strcmp(entrypoint_name, "main") != 0) {
97 anv_finishme("Multiple shaders per module not really supported");
98 }
99
100 const struct brw_compiler *compiler =
101 device->instance->physicalDevice.compiler;
102 const nir_shader_compiler_options *nir_options =
103 compiler->glsl_compiler_options[stage].NirOptions;
104
105 uint32_t *spirv = (uint32_t *) module->data;
106 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
107 assert(module->size % 4 == 0);
108
109 uint32_t num_spec_entries = 0;
110 struct nir_spirv_specialization *spec_entries = NULL;
111 if (spec_info && spec_info->mapEntryCount > 0) {
112 num_spec_entries = spec_info->mapEntryCount;
113 spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
114 for (uint32_t i = 0; i < num_spec_entries; i++) {
115 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
116 const void *data = spec_info->pData + entry.offset;
117 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
118
119 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
120 if (spec_info->dataSize == 8)
121 spec_entries[i].data64 = *(const uint64_t *)data;
122 else
123 spec_entries[i].data32 = *(const uint32_t *)data;
124 }
125 }
126
127 const struct nir_spirv_supported_extensions supported_ext = {
128 .float64 = device->instance->physicalDevice.info.gen >= 8,
129 };
130
131 nir_function *entry_point =
132 spirv_to_nir(spirv, module->size / 4,
133 spec_entries, num_spec_entries,
134 stage, entrypoint_name, &supported_ext, nir_options);
135 nir_shader *nir = entry_point->shader;
136 assert(nir->stage == stage);
137 nir_validate_shader(nir);
138
139 free(spec_entries);
140
141 if (stage == MESA_SHADER_FRAGMENT)
142 NIR_PASS_V(nir, nir_lower_wpos_center);
143
144 /* We have to lower away local constant initializers right before we
145 * inline functions. That way they get properly initialized at the top
146 * of the function and not at the top of its caller.
147 */
148 NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_local);
149 NIR_PASS_V(nir, nir_lower_returns);
150 NIR_PASS_V(nir, nir_inline_functions);
151
152 /* Pick off the single entrypoint that we want */
153 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
154 if (func != entry_point)
155 exec_node_remove(&func->node);
156 }
157 assert(exec_list_length(&nir->functions) == 1);
158 entry_point->name = ralloc_strdup(entry_point, "main");
159
160 NIR_PASS_V(nir, nir_remove_dead_variables,
161 nir_var_shader_in | nir_var_shader_out | nir_var_system_value);
162
163 /* Now that we've deleted all but the main function, we can go ahead and
164 * lower the rest of the constant initializers.
165 */
166 NIR_PASS_V(nir, nir_lower_constant_initializers, ~0);
167 NIR_PASS_V(nir, nir_propagate_invariant);
168 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
169 entry_point->impl, true, false);
170 NIR_PASS_V(nir, nir_lower_system_values);
171
172 /* Vulkan uses the separate-shader linking model */
173 nir->info->separate_shader = true;
174
175 nir = brw_preprocess_nir(compiler, nir);
176
177 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
178
179 if (stage == MESA_SHADER_FRAGMENT)
180 NIR_PASS_V(nir, anv_nir_lower_input_attachments);
181
182 nir_shader_gather_info(nir, entry_point->impl);
183
184 return nir;
185 }
186
187 void anv_DestroyPipeline(
188 VkDevice _device,
189 VkPipeline _pipeline,
190 const VkAllocationCallbacks* pAllocator)
191 {
192 ANV_FROM_HANDLE(anv_device, device, _device);
193 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
194
195 if (!pipeline)
196 return;
197
198 anv_reloc_list_finish(&pipeline->batch_relocs,
199 pAllocator ? pAllocator : &device->alloc);
200 if (pipeline->blend_state.map)
201 anv_state_pool_free(&device->dynamic_state_pool, pipeline->blend_state);
202
203 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
204 if (pipeline->shaders[s])
205 anv_shader_bin_unref(device, pipeline->shaders[s]);
206 }
207
208 vk_free2(&device->alloc, pAllocator, pipeline);
209 }
210
211 static const uint32_t vk_to_gen_primitive_type[] = {
212 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
213 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
214 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
215 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
216 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
217 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
218 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
219 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
220 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
221 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
222 /* [VK_PRIMITIVE_TOPOLOGY_PATCH_LIST] = _3DPRIM_PATCHLIST_1 */
223 };
224
225 static void
226 populate_sampler_prog_key(const struct gen_device_info *devinfo,
227 struct brw_sampler_prog_key_data *key)
228 {
229 /* XXX: Handle texture swizzle on HSW- */
230 for (int i = 0; i < MAX_SAMPLERS; i++) {
231 /* Assume color sampler, no swizzling. (Works for BDW+) */
232 key->swizzles[i] = SWIZZLE_XYZW;
233 }
234 }
235
236 static void
237 populate_vs_prog_key(const struct gen_device_info *devinfo,
238 struct brw_vs_prog_key *key)
239 {
240 memset(key, 0, sizeof(*key));
241
242 populate_sampler_prog_key(devinfo, &key->tex);
243
244 /* XXX: Handle vertex input work-arounds */
245
246 /* XXX: Handle sampler_prog_key */
247 }
248
249 static void
250 populate_gs_prog_key(const struct gen_device_info *devinfo,
251 struct brw_gs_prog_key *key)
252 {
253 memset(key, 0, sizeof(*key));
254
255 populate_sampler_prog_key(devinfo, &key->tex);
256 }
257
258 static void
259 populate_wm_prog_key(const struct anv_pipeline *pipeline,
260 const VkGraphicsPipelineCreateInfo *info,
261 struct brw_wm_prog_key *key)
262 {
263 const struct gen_device_info *devinfo = &pipeline->device->info;
264 ANV_FROM_HANDLE(anv_render_pass, render_pass, info->renderPass);
265
266 memset(key, 0, sizeof(*key));
267
268 populate_sampler_prog_key(devinfo, &key->tex);
269
270 /* TODO: we could set this to 0 based on the information in nir_shader, but
271 * this function is called before spirv_to_nir. */
272 const struct brw_vue_map *vue_map =
273 anv_pipeline_get_fs_input_map(pipeline);
274 key->input_slots_valid = vue_map->slots_valid;
275
276 /* Vulkan doesn't specify a default */
277 key->high_quality_derivatives = false;
278
279 /* XXX Vulkan doesn't appear to specify */
280 key->clamp_fragment_color = false;
281
282 key->nr_color_regions =
283 render_pass->subpasses[info->subpass].color_count;
284
285 key->replicate_alpha = key->nr_color_regions > 1 &&
286 info->pMultisampleState &&
287 info->pMultisampleState->alphaToCoverageEnable;
288
289 if (info->pMultisampleState && info->pMultisampleState->rasterizationSamples > 1) {
290 /* We should probably pull this out of the shader, but it's fairly
291 * harmless to compute it and then let dead-code take care of it.
292 */
293 key->persample_interp =
294 (info->pMultisampleState->minSampleShading *
295 info->pMultisampleState->rasterizationSamples) > 1;
296 key->multisample_fbo = true;
297 }
298 }
299
300 static void
301 populate_cs_prog_key(const struct gen_device_info *devinfo,
302 struct brw_cs_prog_key *key)
303 {
304 memset(key, 0, sizeof(*key));
305
306 populate_sampler_prog_key(devinfo, &key->tex);
307 }
308
309 static nir_shader *
310 anv_pipeline_compile(struct anv_pipeline *pipeline,
311 struct anv_shader_module *module,
312 const char *entrypoint,
313 gl_shader_stage stage,
314 const VkSpecializationInfo *spec_info,
315 struct brw_stage_prog_data *prog_data,
316 struct anv_pipeline_bind_map *map)
317 {
318 nir_shader *nir = anv_shader_compile_to_nir(pipeline->device,
319 module, entrypoint, stage,
320 spec_info);
321 if (nir == NULL)
322 return NULL;
323
324 NIR_PASS_V(nir, anv_nir_lower_push_constants);
325
326 /* Figure out the number of parameters */
327 prog_data->nr_params = 0;
328
329 if (nir->num_uniforms > 0) {
330 /* If the shader uses any push constants at all, we'll just give
331 * them the maximum possible number
332 */
333 assert(nir->num_uniforms <= MAX_PUSH_CONSTANTS_SIZE);
334 prog_data->nr_params += MAX_PUSH_CONSTANTS_SIZE / sizeof(float);
335 }
336
337 if (pipeline->layout && pipeline->layout->stage[stage].has_dynamic_offsets)
338 prog_data->nr_params += MAX_DYNAMIC_BUFFERS * 2;
339
340 if (nir->info->num_images > 0) {
341 prog_data->nr_params += nir->info->num_images * BRW_IMAGE_PARAM_SIZE;
342 pipeline->needs_data_cache = true;
343 }
344
345 if (stage == MESA_SHADER_COMPUTE)
346 ((struct brw_cs_prog_data *)prog_data)->thread_local_id_index =
347 prog_data->nr_params++; /* The CS Thread ID uniform */
348
349 if (nir->info->num_ssbos > 0)
350 pipeline->needs_data_cache = true;
351
352 if (prog_data->nr_params > 0) {
353 /* XXX: I think we're leaking this */
354 prog_data->param = (const union gl_constant_value **)
355 malloc(prog_data->nr_params * sizeof(union gl_constant_value *));
356
357 /* We now set the param values to be offsets into a
358 * anv_push_constant_data structure. Since the compiler doesn't
359 * actually dereference any of the gl_constant_value pointers in the
360 * params array, it doesn't really matter what we put here.
361 */
362 struct anv_push_constants *null_data = NULL;
363 if (nir->num_uniforms > 0) {
364 /* Fill out the push constants section of the param array */
365 for (unsigned i = 0; i < MAX_PUSH_CONSTANTS_SIZE / sizeof(float); i++)
366 prog_data->param[i] = (const union gl_constant_value *)
367 &null_data->client_data[i * sizeof(float)];
368 }
369 }
370
371 /* Set up dynamic offsets */
372 anv_nir_apply_dynamic_offsets(pipeline, nir, prog_data);
373
374 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
375 if (pipeline->layout)
376 anv_nir_apply_pipeline_layout(pipeline, nir, prog_data, map);
377
378 /* nir_lower_io will only handle the push constants; we need to set this
379 * to the full number of possible uniforms.
380 */
381 nir->num_uniforms = prog_data->nr_params * 4;
382
383 return nir;
384 }
385
386 static void
387 anv_fill_binding_table(struct brw_stage_prog_data *prog_data, unsigned bias)
388 {
389 prog_data->binding_table.size_bytes = 0;
390 prog_data->binding_table.texture_start = bias;
391 prog_data->binding_table.gather_texture_start = bias;
392 prog_data->binding_table.ubo_start = bias;
393 prog_data->binding_table.ssbo_start = bias;
394 prog_data->binding_table.image_start = bias;
395 }
396
397 static struct anv_shader_bin *
398 anv_pipeline_upload_kernel(struct anv_pipeline *pipeline,
399 struct anv_pipeline_cache *cache,
400 const void *key_data, uint32_t key_size,
401 const void *kernel_data, uint32_t kernel_size,
402 const struct brw_stage_prog_data *prog_data,
403 uint32_t prog_data_size,
404 const struct anv_pipeline_bind_map *bind_map)
405 {
406 if (cache) {
407 return anv_pipeline_cache_upload_kernel(cache, key_data, key_size,
408 kernel_data, kernel_size,
409 prog_data, prog_data_size,
410 bind_map);
411 } else {
412 return anv_shader_bin_create(pipeline->device, key_data, key_size,
413 kernel_data, kernel_size,
414 prog_data, prog_data_size,
415 prog_data->param, bind_map);
416 }
417 }
418
419
420 static void
421 anv_pipeline_add_compiled_stage(struct anv_pipeline *pipeline,
422 gl_shader_stage stage,
423 struct anv_shader_bin *shader)
424 {
425 pipeline->shaders[stage] = shader;
426 pipeline->active_stages |= mesa_to_vk_shader_stage(stage);
427 }
428
429 static VkResult
430 anv_pipeline_compile_vs(struct anv_pipeline *pipeline,
431 struct anv_pipeline_cache *cache,
432 const VkGraphicsPipelineCreateInfo *info,
433 struct anv_shader_module *module,
434 const char *entrypoint,
435 const VkSpecializationInfo *spec_info)
436 {
437 const struct brw_compiler *compiler =
438 pipeline->device->instance->physicalDevice.compiler;
439 struct anv_pipeline_bind_map map;
440 struct brw_vs_prog_key key;
441 struct anv_shader_bin *bin = NULL;
442 unsigned char sha1[20];
443
444 populate_vs_prog_key(&pipeline->device->info, &key);
445
446 if (cache) {
447 anv_hash_shader(sha1, &key, sizeof(key), module, entrypoint,
448 pipeline->layout, spec_info);
449 bin = anv_pipeline_cache_search(cache, sha1, 20);
450 }
451
452 if (bin == NULL) {
453 struct brw_vs_prog_data prog_data = { 0, };
454 struct anv_pipeline_binding surface_to_descriptor[256];
455 struct anv_pipeline_binding sampler_to_descriptor[256];
456
457 map = (struct anv_pipeline_bind_map) {
458 .surface_to_descriptor = surface_to_descriptor,
459 .sampler_to_descriptor = sampler_to_descriptor
460 };
461
462 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
463 MESA_SHADER_VERTEX, spec_info,
464 &prog_data.base.base, &map);
465 if (nir == NULL)
466 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
467
468 anv_fill_binding_table(&prog_data.base.base, 0);
469
470 void *mem_ctx = ralloc_context(NULL);
471
472 ralloc_steal(mem_ctx, nir);
473
474 prog_data.inputs_read = nir->info->inputs_read;
475 prog_data.double_inputs_read = nir->info->double_inputs_read;
476
477 brw_compute_vue_map(&pipeline->device->info,
478 &prog_data.base.vue_map,
479 nir->info->outputs_written,
480 nir->info->separate_shader);
481
482 unsigned code_size;
483 const unsigned *shader_code =
484 brw_compile_vs(compiler, NULL, mem_ctx, &key, &prog_data, nir,
485 NULL, false, -1, &code_size, NULL);
486 if (shader_code == NULL) {
487 ralloc_free(mem_ctx);
488 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
489 }
490
491 bin = anv_pipeline_upload_kernel(pipeline, cache, sha1, 20,
492 shader_code, code_size,
493 &prog_data.base.base, sizeof(prog_data),
494 &map);
495 if (!bin) {
496 ralloc_free(mem_ctx);
497 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
498 }
499
500 ralloc_free(mem_ctx);
501 }
502
503 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_VERTEX, bin);
504
505 return VK_SUCCESS;
506 }
507
508 static VkResult
509 anv_pipeline_compile_gs(struct anv_pipeline *pipeline,
510 struct anv_pipeline_cache *cache,
511 const VkGraphicsPipelineCreateInfo *info,
512 struct anv_shader_module *module,
513 const char *entrypoint,
514 const VkSpecializationInfo *spec_info)
515 {
516 const struct brw_compiler *compiler =
517 pipeline->device->instance->physicalDevice.compiler;
518 struct anv_pipeline_bind_map map;
519 struct brw_gs_prog_key key;
520 struct anv_shader_bin *bin = NULL;
521 unsigned char sha1[20];
522
523 populate_gs_prog_key(&pipeline->device->info, &key);
524
525 if (cache) {
526 anv_hash_shader(sha1, &key, sizeof(key), module, entrypoint,
527 pipeline->layout, spec_info);
528 bin = anv_pipeline_cache_search(cache, sha1, 20);
529 }
530
531 if (bin == NULL) {
532 struct brw_gs_prog_data prog_data = { 0, };
533 struct anv_pipeline_binding surface_to_descriptor[256];
534 struct anv_pipeline_binding sampler_to_descriptor[256];
535
536 map = (struct anv_pipeline_bind_map) {
537 .surface_to_descriptor = surface_to_descriptor,
538 .sampler_to_descriptor = sampler_to_descriptor
539 };
540
541 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
542 MESA_SHADER_GEOMETRY, spec_info,
543 &prog_data.base.base, &map);
544 if (nir == NULL)
545 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
546
547 anv_fill_binding_table(&prog_data.base.base, 0);
548
549 void *mem_ctx = ralloc_context(NULL);
550
551 ralloc_steal(mem_ctx, nir);
552
553 brw_compute_vue_map(&pipeline->device->info,
554 &prog_data.base.vue_map,
555 nir->info->outputs_written,
556 nir->info->separate_shader);
557
558 unsigned code_size;
559 const unsigned *shader_code =
560 brw_compile_gs(compiler, NULL, mem_ctx, &key, &prog_data, nir,
561 NULL, -1, &code_size, NULL);
562 if (shader_code == NULL) {
563 ralloc_free(mem_ctx);
564 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
565 }
566
567 /* TODO: SIMD8 GS */
568 bin = anv_pipeline_upload_kernel(pipeline, cache, sha1, 20,
569 shader_code, code_size,
570 &prog_data.base.base, sizeof(prog_data),
571 &map);
572 if (!bin) {
573 ralloc_free(mem_ctx);
574 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
575 }
576
577 ralloc_free(mem_ctx);
578 }
579
580 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_GEOMETRY, bin);
581
582 return VK_SUCCESS;
583 }
584
585 static VkResult
586 anv_pipeline_compile_fs(struct anv_pipeline *pipeline,
587 struct anv_pipeline_cache *cache,
588 const VkGraphicsPipelineCreateInfo *info,
589 struct anv_shader_module *module,
590 const char *entrypoint,
591 const VkSpecializationInfo *spec_info)
592 {
593 const struct brw_compiler *compiler =
594 pipeline->device->instance->physicalDevice.compiler;
595 struct anv_pipeline_bind_map map;
596 struct brw_wm_prog_key key;
597 struct anv_shader_bin *bin = NULL;
598 unsigned char sha1[20];
599
600 populate_wm_prog_key(pipeline, info, &key);
601
602 if (cache) {
603 anv_hash_shader(sha1, &key, sizeof(key), module, entrypoint,
604 pipeline->layout, spec_info);
605 bin = anv_pipeline_cache_search(cache, sha1, 20);
606 }
607
608 if (bin == NULL) {
609 struct brw_wm_prog_data prog_data = { 0, };
610 struct anv_pipeline_binding surface_to_descriptor[256];
611 struct anv_pipeline_binding sampler_to_descriptor[256];
612
613 map = (struct anv_pipeline_bind_map) {
614 .surface_to_descriptor = surface_to_descriptor + 8,
615 .sampler_to_descriptor = sampler_to_descriptor
616 };
617
618 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
619 MESA_SHADER_FRAGMENT, spec_info,
620 &prog_data.base, &map);
621 if (nir == NULL)
622 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
623
624 unsigned num_rts = 0;
625 struct anv_pipeline_binding rt_bindings[8];
626 nir_function_impl *impl = nir_shader_get_entrypoint(nir);
627 nir_foreach_variable_safe(var, &nir->outputs) {
628 if (var->data.location < FRAG_RESULT_DATA0)
629 continue;
630
631 unsigned rt = var->data.location - FRAG_RESULT_DATA0;
632 if (rt >= key.nr_color_regions) {
633 /* Out-of-bounds, throw it away */
634 var->data.mode = nir_var_local;
635 exec_node_remove(&var->node);
636 exec_list_push_tail(&impl->locals, &var->node);
637 continue;
638 }
639
640 /* Give it a new, compacted, location */
641 var->data.location = FRAG_RESULT_DATA0 + num_rts;
642
643 unsigned array_len =
644 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
645 assert(num_rts + array_len <= 8);
646
647 for (unsigned i = 0; i < array_len; i++) {
648 rt_bindings[num_rts + i] = (struct anv_pipeline_binding) {
649 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
650 .binding = 0,
651 .index = rt + i,
652 };
653 }
654
655 num_rts += array_len;
656 }
657
658 if (num_rts == 0) {
659 /* If we have no render targets, we need a null render target */
660 rt_bindings[0] = (struct anv_pipeline_binding) {
661 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
662 .binding = 0,
663 .index = UINT8_MAX,
664 };
665 num_rts = 1;
666 }
667
668 assert(num_rts <= 8);
669 map.surface_to_descriptor -= num_rts;
670 map.surface_count += num_rts;
671 assert(map.surface_count <= 256);
672 memcpy(map.surface_to_descriptor, rt_bindings,
673 num_rts * sizeof(*rt_bindings));
674
675 anv_fill_binding_table(&prog_data.base, num_rts);
676
677 void *mem_ctx = ralloc_context(NULL);
678
679 ralloc_steal(mem_ctx, nir);
680
681 unsigned code_size;
682 const unsigned *shader_code =
683 brw_compile_fs(compiler, NULL, mem_ctx, &key, &prog_data, nir,
684 NULL, -1, -1, true, false, NULL, &code_size, NULL);
685 if (shader_code == NULL) {
686 ralloc_free(mem_ctx);
687 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
688 }
689
690 bin = anv_pipeline_upload_kernel(pipeline, cache, sha1, 20,
691 shader_code, code_size,
692 &prog_data.base, sizeof(prog_data),
693 &map);
694 if (!bin) {
695 ralloc_free(mem_ctx);
696 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
697 }
698
699 ralloc_free(mem_ctx);
700 }
701
702 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_FRAGMENT, bin);
703
704 return VK_SUCCESS;
705 }
706
707 VkResult
708 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
709 struct anv_pipeline_cache *cache,
710 const VkComputePipelineCreateInfo *info,
711 struct anv_shader_module *module,
712 const char *entrypoint,
713 const VkSpecializationInfo *spec_info)
714 {
715 const struct brw_compiler *compiler =
716 pipeline->device->instance->physicalDevice.compiler;
717 struct anv_pipeline_bind_map map;
718 struct brw_cs_prog_key key;
719 struct anv_shader_bin *bin = NULL;
720 unsigned char sha1[20];
721
722 populate_cs_prog_key(&pipeline->device->info, &key);
723
724 if (cache) {
725 anv_hash_shader(sha1, &key, sizeof(key), module, entrypoint,
726 pipeline->layout, spec_info);
727 bin = anv_pipeline_cache_search(cache, sha1, 20);
728 }
729
730 if (bin == NULL) {
731 struct brw_cs_prog_data prog_data = { 0, };
732 struct anv_pipeline_binding surface_to_descriptor[256];
733 struct anv_pipeline_binding sampler_to_descriptor[256];
734
735 map = (struct anv_pipeline_bind_map) {
736 .surface_to_descriptor = surface_to_descriptor,
737 .sampler_to_descriptor = sampler_to_descriptor
738 };
739
740 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
741 MESA_SHADER_COMPUTE, spec_info,
742 &prog_data.base, &map);
743 if (nir == NULL)
744 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
745
746 anv_fill_binding_table(&prog_data.base, 1);
747
748 void *mem_ctx = ralloc_context(NULL);
749
750 ralloc_steal(mem_ctx, nir);
751
752 unsigned code_size;
753 const unsigned *shader_code =
754 brw_compile_cs(compiler, NULL, mem_ctx, &key, &prog_data, nir,
755 -1, &code_size, NULL);
756 if (shader_code == NULL) {
757 ralloc_free(mem_ctx);
758 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
759 }
760
761 bin = anv_pipeline_upload_kernel(pipeline, cache, sha1, 20,
762 shader_code, code_size,
763 &prog_data.base, sizeof(prog_data),
764 &map);
765 if (!bin) {
766 ralloc_free(mem_ctx);
767 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
768 }
769
770 ralloc_free(mem_ctx);
771 }
772
773 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_COMPUTE, bin);
774
775 return VK_SUCCESS;
776 }
777
778 /**
779 * Copy pipeline state not marked as dynamic.
780 * Dynamic state is pipeline state which hasn't been provided at pipeline
781 * creation time, but is dynamically provided afterwards using various
782 * vkCmdSet* functions.
783 *
784 * The set of state considered "non_dynamic" is determined by the pieces of
785 * state that have their corresponding VkDynamicState enums omitted from
786 * VkPipelineDynamicStateCreateInfo::pDynamicStates.
787 *
788 * @param[out] pipeline Destination non_dynamic state.
789 * @param[in] pCreateInfo Source of non_dynamic state to be copied.
790 */
791 static void
792 copy_non_dynamic_state(struct anv_pipeline *pipeline,
793 const VkGraphicsPipelineCreateInfo *pCreateInfo)
794 {
795 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
796 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
797 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
798
799 pipeline->dynamic_state = default_dynamic_state;
800
801 if (pCreateInfo->pDynamicState) {
802 /* Remove all of the states that are marked as dynamic */
803 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
804 for (uint32_t s = 0; s < count; s++)
805 states &= ~(1 << pCreateInfo->pDynamicState->pDynamicStates[s]);
806 }
807
808 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
809
810 /* Section 9.2 of the Vulkan 1.0.15 spec says:
811 *
812 * pViewportState is [...] NULL if the pipeline
813 * has rasterization disabled.
814 */
815 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
816 assert(pCreateInfo->pViewportState);
817
818 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
819 if (states & (1 << VK_DYNAMIC_STATE_VIEWPORT)) {
820 typed_memcpy(dynamic->viewport.viewports,
821 pCreateInfo->pViewportState->pViewports,
822 pCreateInfo->pViewportState->viewportCount);
823 }
824
825 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
826 if (states & (1 << VK_DYNAMIC_STATE_SCISSOR)) {
827 typed_memcpy(dynamic->scissor.scissors,
828 pCreateInfo->pViewportState->pScissors,
829 pCreateInfo->pViewportState->scissorCount);
830 }
831 }
832
833 if (states & (1 << VK_DYNAMIC_STATE_LINE_WIDTH)) {
834 assert(pCreateInfo->pRasterizationState);
835 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
836 }
837
838 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BIAS)) {
839 assert(pCreateInfo->pRasterizationState);
840 dynamic->depth_bias.bias =
841 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
842 dynamic->depth_bias.clamp =
843 pCreateInfo->pRasterizationState->depthBiasClamp;
844 dynamic->depth_bias.slope =
845 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
846 }
847
848 /* Section 9.2 of the Vulkan 1.0.15 spec says:
849 *
850 * pColorBlendState is [...] NULL if the pipeline has rasterization
851 * disabled or if the subpass of the render pass the pipeline is
852 * created against does not use any color attachments.
853 */
854 bool uses_color_att = false;
855 for (unsigned i = 0; i < subpass->color_count; ++i) {
856 if (subpass->color_attachments[i] != VK_ATTACHMENT_UNUSED) {
857 uses_color_att = true;
858 break;
859 }
860 }
861
862 if (uses_color_att &&
863 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
864 assert(pCreateInfo->pColorBlendState);
865
866 if (states & (1 << VK_DYNAMIC_STATE_BLEND_CONSTANTS))
867 typed_memcpy(dynamic->blend_constants,
868 pCreateInfo->pColorBlendState->blendConstants, 4);
869 }
870
871 /* If there is no depthstencil attachment, then don't read
872 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
873 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
874 * no need to override the depthstencil defaults in
875 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
876 *
877 * Section 9.2 of the Vulkan 1.0.15 spec says:
878 *
879 * pDepthStencilState is [...] NULL if the pipeline has rasterization
880 * disabled or if the subpass of the render pass the pipeline is created
881 * against does not use a depth/stencil attachment.
882 */
883 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
884 subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED) {
885 assert(pCreateInfo->pDepthStencilState);
886
887 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BOUNDS)) {
888 dynamic->depth_bounds.min =
889 pCreateInfo->pDepthStencilState->minDepthBounds;
890 dynamic->depth_bounds.max =
891 pCreateInfo->pDepthStencilState->maxDepthBounds;
892 }
893
894 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
895 dynamic->stencil_compare_mask.front =
896 pCreateInfo->pDepthStencilState->front.compareMask;
897 dynamic->stencil_compare_mask.back =
898 pCreateInfo->pDepthStencilState->back.compareMask;
899 }
900
901 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
902 dynamic->stencil_write_mask.front =
903 pCreateInfo->pDepthStencilState->front.writeMask;
904 dynamic->stencil_write_mask.back =
905 pCreateInfo->pDepthStencilState->back.writeMask;
906 }
907
908 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_REFERENCE)) {
909 dynamic->stencil_reference.front =
910 pCreateInfo->pDepthStencilState->front.reference;
911 dynamic->stencil_reference.back =
912 pCreateInfo->pDepthStencilState->back.reference;
913 }
914 }
915
916 pipeline->dynamic_state_mask = states;
917 }
918
919 static void
920 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
921 {
922 struct anv_render_pass *renderpass = NULL;
923 struct anv_subpass *subpass = NULL;
924
925 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
926 * present. See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
927 */
928 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
929
930 renderpass = anv_render_pass_from_handle(info->renderPass);
931 assert(renderpass);
932
933 assert(info->subpass < renderpass->subpass_count);
934 subpass = &renderpass->subpasses[info->subpass];
935
936 assert(info->stageCount >= 1);
937 assert(info->pVertexInputState);
938 assert(info->pInputAssemblyState);
939 assert(info->pRasterizationState);
940 if (!info->pRasterizationState->rasterizerDiscardEnable) {
941 assert(info->pViewportState);
942 assert(info->pMultisampleState);
943
944 if (subpass && subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED)
945 assert(info->pDepthStencilState);
946
947 if (subpass && subpass->color_count > 0)
948 assert(info->pColorBlendState);
949 }
950
951 for (uint32_t i = 0; i < info->stageCount; ++i) {
952 switch (info->pStages[i].stage) {
953 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
954 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
955 assert(info->pTessellationState);
956 break;
957 default:
958 break;
959 }
960 }
961 }
962
963 /**
964 * Calculate the desired L3 partitioning based on the current state of the
965 * pipeline. For now this simply returns the conservative defaults calculated
966 * by get_default_l3_weights(), but we could probably do better by gathering
967 * more statistics from the pipeline state (e.g. guess of expected URB usage
968 * and bound surfaces), or by using feed-back from performance counters.
969 */
970 void
971 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
972 {
973 const struct gen_device_info *devinfo = &pipeline->device->info;
974
975 const struct gen_l3_weights w =
976 gen_get_default_l3_weights(devinfo, pipeline->needs_data_cache, needs_slm);
977
978 pipeline->urb.l3_config = gen_get_l3_config(devinfo, w);
979 pipeline->urb.total_size =
980 gen_get_l3_config_urb_size(devinfo, pipeline->urb.l3_config);
981 }
982
983 VkResult
984 anv_pipeline_init(struct anv_pipeline *pipeline,
985 struct anv_device *device,
986 struct anv_pipeline_cache *cache,
987 const VkGraphicsPipelineCreateInfo *pCreateInfo,
988 const VkAllocationCallbacks *alloc)
989 {
990 VkResult result;
991
992 anv_validate {
993 anv_pipeline_validate_create_info(pCreateInfo);
994 }
995
996 if (alloc == NULL)
997 alloc = &device->alloc;
998
999 pipeline->device = device;
1000 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
1001
1002 result = anv_reloc_list_init(&pipeline->batch_relocs, alloc);
1003 if (result != VK_SUCCESS)
1004 return result;
1005
1006 pipeline->batch.alloc = alloc;
1007 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1008 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1009 pipeline->batch.relocs = &pipeline->batch_relocs;
1010
1011 copy_non_dynamic_state(pipeline, pCreateInfo);
1012 pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState &&
1013 pCreateInfo->pRasterizationState->depthClampEnable;
1014
1015 pipeline->needs_data_cache = false;
1016
1017 /* When we free the pipeline, we detect stages based on the NULL status
1018 * of various prog_data pointers. Make them NULL by default.
1019 */
1020 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1021
1022 pipeline->active_stages = 0;
1023
1024 const VkPipelineShaderStageCreateInfo *pStages[MESA_SHADER_STAGES] = { 0, };
1025 struct anv_shader_module *modules[MESA_SHADER_STAGES] = { 0, };
1026 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1027 gl_shader_stage stage = ffs(pCreateInfo->pStages[i].stage) - 1;
1028 pStages[stage] = &pCreateInfo->pStages[i];
1029 modules[stage] = anv_shader_module_from_handle(pStages[stage]->module);
1030 }
1031
1032 if (modules[MESA_SHADER_VERTEX]) {
1033 result = anv_pipeline_compile_vs(pipeline, cache, pCreateInfo,
1034 modules[MESA_SHADER_VERTEX],
1035 pStages[MESA_SHADER_VERTEX]->pName,
1036 pStages[MESA_SHADER_VERTEX]->pSpecializationInfo);
1037 if (result != VK_SUCCESS)
1038 goto compile_fail;
1039 }
1040
1041 if (modules[MESA_SHADER_TESS_CTRL] || modules[MESA_SHADER_TESS_EVAL])
1042 anv_finishme("no tessellation support");
1043
1044 if (modules[MESA_SHADER_GEOMETRY]) {
1045 result = anv_pipeline_compile_gs(pipeline, cache, pCreateInfo,
1046 modules[MESA_SHADER_GEOMETRY],
1047 pStages[MESA_SHADER_GEOMETRY]->pName,
1048 pStages[MESA_SHADER_GEOMETRY]->pSpecializationInfo);
1049 if (result != VK_SUCCESS)
1050 goto compile_fail;
1051 }
1052
1053 if (modules[MESA_SHADER_FRAGMENT]) {
1054 result = anv_pipeline_compile_fs(pipeline, cache, pCreateInfo,
1055 modules[MESA_SHADER_FRAGMENT],
1056 pStages[MESA_SHADER_FRAGMENT]->pName,
1057 pStages[MESA_SHADER_FRAGMENT]->pSpecializationInfo);
1058 if (result != VK_SUCCESS)
1059 goto compile_fail;
1060 }
1061
1062 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1063
1064 anv_pipeline_setup_l3_config(pipeline, false);
1065
1066 const VkPipelineVertexInputStateCreateInfo *vi_info =
1067 pCreateInfo->pVertexInputState;
1068
1069 const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
1070
1071 pipeline->vb_used = 0;
1072 for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
1073 const VkVertexInputAttributeDescription *desc =
1074 &vi_info->pVertexAttributeDescriptions[i];
1075
1076 if (inputs_read & (1 << (VERT_ATTRIB_GENERIC0 + desc->location)))
1077 pipeline->vb_used |= 1 << desc->binding;
1078 }
1079
1080 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1081 const VkVertexInputBindingDescription *desc =
1082 &vi_info->pVertexBindingDescriptions[i];
1083
1084 pipeline->binding_stride[desc->binding] = desc->stride;
1085
1086 /* Step rate is programmed per vertex element (attribute), not
1087 * binding. Set up a map of which bindings step per instance, for
1088 * reference by vertex element setup. */
1089 switch (desc->inputRate) {
1090 default:
1091 case VK_VERTEX_INPUT_RATE_VERTEX:
1092 pipeline->instancing_enable[desc->binding] = false;
1093 break;
1094 case VK_VERTEX_INPUT_RATE_INSTANCE:
1095 pipeline->instancing_enable[desc->binding] = true;
1096 break;
1097 }
1098 }
1099
1100 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1101 pCreateInfo->pInputAssemblyState;
1102 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1103 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1104
1105 return VK_SUCCESS;
1106
1107 compile_fail:
1108 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1109 if (pipeline->shaders[s])
1110 anv_shader_bin_unref(device, pipeline->shaders[s]);
1111 }
1112
1113 anv_reloc_list_finish(&pipeline->batch_relocs, alloc);
1114
1115 return result;
1116 }