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