Debian Codegraph @

src/kosmickrisp/vulkan/kk_shader.c

raw symbols SCIP
1 /*
2 * Copyright © 2022 Collabora Ltd. and Red Hat Inc.
3 * Copyright 2025 LunarG, Inc.
4 * Copyright 2025 Google LLC
5 * SPDX-License-Identifier: MIT
6 */
7
8 #include "kk_shader.h"
9
10 #include "kk_cmd_buffer.h"
11 #include "kk_debug.h"
12 #include "kk_descriptor_set_layout.h"
13 #include "kk_device.h"
14 #include "kk_format.h"
15 #include "kk_nir_lower_vbo.h"
16 #include "kk_physical_device.h"
17 #include "kk_sampler.h"
18
19 #include "kosmickrisp/bridge/mtl_bridge.h"
20 #include "kosmickrisp/bridge/vk_to_mtl_map.h"
21 #include "kosmickrisp/compiler/nir_to_msl.h"
22
23 #include "nir_builder.h"
24 #include "nir_lower_blend.h"
25
26 #include "vk_blend.h"
27 #include "vk_format.h"
28 #include "vk_graphics_state.h"
29 #include "vk_nir_convert_ycbcr.h"
30 #include "vk_pipeline.h"
31
32 static const nir_shader_compiler_options *
33 kk_get_nir_options(struct vk_physical_device *vk_pdev, mesa_shader_stage stage,
34 UNUSED const struct vk_pipeline_robustness_state *rs)
35 {
36 return &kk_nir_options;
37 }
38
39 /* TODO_KOSMICKRISP Once we support robustness2, update these values. */
40 static const struct vk_pipeline_robustness_state rs_all_supported = {
41 .uniform_buffers =
42 VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS,
43 .storage_buffers =
44 VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS,
45 .images = VK_PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT,
46 };
47
48 static struct spirv_to_nir_options
49 kk_get_spirv_options(struct vk_physical_device *vk_pdev,
50 UNUSED mesa_shader_stage stage,
51 const struct vk_pipeline_robustness_state *rs)
52 {
53 if (KK_DEBUG(FORCE_ROBUSTNESS))
54 rs = &rs_all_supported;
55 return (struct spirv_to_nir_options){
56 .environment = NIR_SPIRV_VULKAN,
57 .ssbo_addr_format = kk_buffer_addr_format(rs->storage_buffers),
58 .phys_ssbo_addr_format = nir_address_format_64bit_global,
59 .ubo_addr_format = kk_buffer_addr_format(rs->uniform_buffers),
60 .shared_addr_format = nir_address_format_32bit_offset,
61 .min_ssbo_alignment = KK_MIN_SSBO_ALIGNMENT,
62 .min_ubo_alignment = KK_MIN_UBO_ALIGNMENT,
63 };
64 }
65
66 static void
67 kk_preprocess_nir(UNUSED struct vk_physical_device *vk_pdev, nir_shader *nir,
68 UNUSED const struct vk_pipeline_robustness_state *rs)
69 {
70 /* Gather info before preprocess_nir but after some general lowering, so
71 * inputs_read and system_values_read are accurately set.
72 */
73 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
74
75 /* nir_lower_io_to_temporaries is required before nir_lower_blend since the
76 * blending pass sinks writes to the end of the block where we may have a
77 * jump, which is illegal.
78 */
79 NIR_PASS(_, nir, nir_lower_io_vars_to_temporaries,
80 nir_shader_get_entrypoint(nir), nir_var_shader_out);
81
82 msl_preprocess_nir(nir);
83
84 /* Cannot be part of msl_preprocess_nir since clc does not expose
85 * has_base_workgroup_id */
86 nir_lower_compute_system_values_options csv_options = {
87 .has_base_global_invocation_id = 0,
88 .has_base_workgroup_id = true,
89 };
90 NIR_PASS(_, nir, nir_lower_compute_system_values, &csv_options);
91 }
92
93 struct kk_vs_key {
94 bool is_points;
95 struct vk_vertex_input_state vi;
96 };
97
98 static void
99 kk_populate_vs_key(struct kk_vs_key *key,
100 const struct vk_graphics_pipeline_state *state)
101 {
102 memset(key, 0, sizeof(*key));
103 key->is_points =
104 (state->ia->primitive_topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
105 key->vi = *state->vi;
106 }
107
108 struct kk_fs_key {
109 VkFormat color_formats[MESA_VK_MAX_COLOR_ATTACHMENTS];
110 struct vk_color_blend_state color_blend;
111 uint32_t rasterization_samples;
112 uint16_t static_sample_mask;
113 bool has_depth;
114 };
115
116 static void
117 kk_populate_fs_key(struct kk_fs_key *key,
118 const struct vk_graphics_pipeline_state *state)
119 {
120 memset(key, 0, sizeof(*key));
121
122 /* Required since we [de]serialize blend, and render target swizzle for
123 * non-native formats */
124 memcpy(key->color_formats, state->rp->color_attachment_formats,
125 sizeof(key->color_formats));
126
127 /* Blend state gets [de]serialized, so we need to hash it */
128 if (state->cb)
129 key->color_blend = *(state->cb);
130
131 if (state->ms) {
132 key->rasterization_samples = state->ms->rasterization_samples;
133 key->static_sample_mask = state->ms->sample_mask;
134 }
135
136 /* Depth writes are removed unless there's an actual attachment */
137 key->has_depth = state->rp->depth_attachment_format != VK_FORMAT_UNDEFINED;
138 }
139
140 static void
141 kk_hash_graphics_state(struct vk_physical_device *device,
142 const struct vk_graphics_pipeline_state *state,
143 const struct vk_features *enabled_features,
144 VkShaderStageFlags stages, blake3_hash blake3_out)
145 {
146 struct mesa_blake3 blake3_ctx;
147 _mesa_blake3_init(&blake3_ctx);
148
149 if (stages & VK_SHADER_STAGE_VERTEX_BIT) {
150 struct kk_vs_key key;
151 kk_populate_vs_key(&key, state);
152 _mesa_blake3_update(&blake3_ctx, &key, sizeof(key));
153 }
154
155 if (stages & VK_SHADER_STAGE_FRAGMENT_BIT) {
156 struct kk_fs_key key;
157 kk_populate_fs_key(&key, state);
158 _mesa_blake3_update(&blake3_ctx, &key, sizeof(key));
159
160 _mesa_blake3_update(&blake3_ctx, &state->mv->view_mask,
161 sizeof(state->mv->view_mask));
162 }
163
164 _mesa_blake3_final(&blake3_ctx, blake3_out);
165 }
166
167 static void
168 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
169 {
170 assert(glsl_type_is_vector_or_scalar(type));
171
172 uint32_t comp_size =
173 glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
174 unsigned length = glsl_get_vector_elements(type);
175 *size = comp_size * length, *align = comp_size;
176 }
177
178 struct lower_ycbcr_state {
179 uint32_t set_layout_count;
180 struct vk_descriptor_set_layout *const *set_layouts;
181 };
182
183 static const struct vk_ycbcr_conversion_state *
184 lookup_ycbcr_conversion(const void *_state, uint32_t set, uint32_t binding,
185 uint32_t array_index)
186 {
187 const struct lower_ycbcr_state *state = _state;
188 assert(set < state->set_layout_count);
189 assert(state->set_layouts[set] != NULL);
190 const struct kk_descriptor_set_layout *set_layout =
191 vk_to_kk_descriptor_set_layout(state->set_layouts[set]);
192 assert(binding < set_layout->binding_count);
193
194 const struct kk_descriptor_set_binding_layout *bind_layout =
195 &set_layout->binding[binding];
196
197 if (bind_layout->immutable_samplers == NULL)
198 return NULL;
199
200 array_index = MIN2(array_index, bind_layout->array_size - 1);
201
202 const struct kk_sampler *sampler =
203 bind_layout->immutable_samplers[array_index];
204
205 return sampler && sampler->vk.ycbcr_conversion
206 ? &sampler->vk.ycbcr_conversion->state
207 : NULL;
208 }
209
210 static int
211 type_size_vec4(const struct glsl_type *type, bool bindless)
212 {
213 return glsl_count_attribute_slots(type, false);
214 }
215
216 static bool
217 kk_nir_swizzle_fragment_output(nir_builder *b, nir_intrinsic_instr *intrin,
218 void *data)
219 {
220 if (intrin->intrinsic != nir_intrinsic_store_output &&
221 intrin->intrinsic != nir_intrinsic_load_output)
222 return false;
223
224 unsigned slot = nir_intrinsic_io_semantics(intrin).location;
225 if (slot < FRAG_RESULT_DATA0)
226 return false;
227
228 const struct vk_graphics_pipeline_state *state =
229 (const struct vk_graphics_pipeline_state *)data;
230 VkFormat vk_format =
231 state->rp->color_attachment_formats[slot - FRAG_RESULT_DATA0];
232 if (vk_format == VK_FORMAT_UNDEFINED)
233 return false;
234
235 enum pipe_format format = vk_format_to_pipe_format(vk_format);
236 const struct kk_va_format *supported_format = kk_get_va_format(format);
237
238 /* Check if we have to apply any swizzle */
239 if (!supported_format->is_native) {
240 unsigned channel_unswizzle[] = {
241 supported_format->unswizzle.red, supported_format->unswizzle.green,
242 supported_format->unswizzle.blue, supported_format->unswizzle.alpha};
243
244 if (intrin->intrinsic == nir_intrinsic_store_output) {
245 unsigned channel_swizzle[4] = {0u};
246 for (uint32_t i = 0u; i < 4; ++i)
247 channel_swizzle[channel_unswizzle[i]] = i;
248
249 b->cursor = nir_before_instr(&intrin->instr);
250 nir_def *to_replace = intrin->src[0].ssa;
251 nir_def *swizzled = nir_swizzle(b, to_replace, channel_swizzle,
252 to_replace->num_components);
253 nir_src_rewrite(&intrin->src[0], swizzled);
254 } else {
255 b->cursor = nir_after_instr(&intrin->instr);
256 nir_def *to_replace = &intrin->def;
257 nir_def *swizzled = nir_swizzle(b, to_replace, channel_unswizzle,
258 to_replace->num_components);
259 nir_def_rewrite_uses_after(to_replace, swizzled);
260 }
261 return true;
262 }
263
264 return false;
265 }
266
267 static void
268 kk_lower_vs_vbo(nir_shader *nir, const struct vk_graphics_pipeline_state *state)
269 {
270 assert(!(nir->info.inputs_read & BITFIELD64_MASK(VERT_ATTRIB_GENERIC0)) &&
271 "Fixed-function attributes not used in Vulkan");
272 NIR_PASS(_, nir, nir_recompute_io_bases, nir_var_shader_in);
273 /* the shader_out portion of this is load-bearing even for tess eval */
274 /* Fold constant offset srcs for IO. */
275 NIR_PASS(_, nir, nir_opt_constant_folding);
276
277 struct kk_attribute attributes[KK_MAX_ATTRIBS] = {};
278 uint64_t attribs_read = nir->info.inputs_read >> VERT_ATTRIB_GENERIC0;
279 u_foreach_bit(i, state->vi->attributes_valid) {
280 const struct vk_vertex_attribute_state *attr = &state->vi->attributes[i];
281 assert(state->vi->bindings_valid & BITFIELD_BIT(attr->binding));
282 const struct vk_vertex_binding_state *binding =
283 &state->vi->bindings[attr->binding];
284
285 /* nir_assign_io_var_locations compacts vertex inputs, eliminating
286 * unused inputs. We need to do the same here to match the locations.
287 */
288 unsigned slot = util_bitcount64(attribs_read & BITFIELD_MASK(i));
289 attributes[slot].divisor = binding->divisor;
290 attributes[slot].binding = attr->binding;
291 attributes[slot].format = vk_format_to_pipe_format(attr->format);
292 attributes[slot].buf = attr->binding;
293 attributes[slot].instanced =
294 binding->input_rate == VK_VERTEX_INPUT_RATE_INSTANCE;
295 }
296 NIR_PASS(_, nir, kk_nir_lower_vbo, attributes);
297 }
298
299 static void
300 kk_lower_vs(nir_shader *nir, const struct vk_graphics_pipeline_state *state)
301 {
302 if (state->ia->primitive_topology != VK_PRIMITIVE_TOPOLOGY_POINT_LIST)
303 nir_shader_intrinsics_pass(nir, msl_nir_vs_remove_point_size_write,
304 nir_metadata_control_flow, NULL);
305
306 NIR_PASS(_, nir, msl_nir_vs_io_types);
307 }
308
309 static void
310 kk_lower_fs_blend(nir_shader *nir,
311 const struct vk_graphics_pipeline_state *state)
312 {
313 nir_lower_blend_options opts = {
314 .scalar_blend_const = false,
315 .logicop_enable = state->cb->logic_op_enable,
316 .logicop_func = vk_logic_op_to_pipe(state->cb->logic_op),
317 };
318
319 static_assert(ARRAY_SIZE(opts.rt) == 8, "max RTs out of sync");
320
321 for (unsigned i = 0; i < ARRAY_SIZE(opts.rt); ++i) {
322 enum pipe_format format =
323 vk_format_to_pipe_format(state->rp->color_attachment_formats[i]);
324 if (state->cb->attachments[i].blend_enable) {
325 opts.rt[i] = (nir_lower_blend_rt){
326 .format = format,
327
328 .rgb.src_factor = vk_blend_factor_to_pipe(
329 state->cb->attachments[i].src_color_blend_factor),
330 .rgb.dst_factor = vk_blend_factor_to_pipe(
331 state->cb->attachments[i].dst_color_blend_factor),
332 .rgb.func =
333 vk_blend_op_to_pipe(state->cb->attachments[i].color_blend_op),
334
335 .alpha.src_factor = vk_blend_factor_to_pipe(
336 state->cb->attachments[i].src_alpha_blend_factor),
337 .alpha.dst_factor = vk_blend_factor_to_pipe(
338 state->cb->attachments[i].dst_alpha_blend_factor),
339 .alpha.func =
340 vk_blend_op_to_pipe(state->cb->attachments[i].alpha_blend_op),
341
342 .colormask = state->cb->attachments[i].write_mask,
343 };
344 } else {
345 opts.rt[i] = (nir_lower_blend_rt){
346 .format = format,
347
348 .rgb.src_factor = PIPE_BLENDFACTOR_ONE,
349 .rgb.dst_factor = PIPE_BLENDFACTOR_ZERO,
350 .rgb.func = PIPE_BLEND_ADD,
351
352 .alpha.src_factor = PIPE_BLENDFACTOR_ONE,
353 .alpha.dst_factor = PIPE_BLENDFACTOR_ZERO,
354 .alpha.func = PIPE_BLEND_ADD,
355
356 .colormask = state->cb->attachments[i].write_mask,
357 };
358 }
359 }
360 /* Fold constant offset srcs for IO. */
361 NIR_PASS(_, nir, nir_opt_constant_folding);
362 NIR_PASS(_, nir, nir_lower_blend, &opts);
363 }
364
365 static bool
366 lower_subpass_dim(nir_builder *b, nir_tex_instr *tex, UNUSED void *_data)
367 {
368 if (tex->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS)
369 tex->sampler_dim = GLSL_SAMPLER_DIM_2D;
370 else if (tex->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS_MS)
371 tex->sampler_dim = GLSL_SAMPLER_DIM_MS;
372 else
373 return false;
374
375 return true;
376 }
377
378 static void
379 kk_lower_fs(struct kk_device *dev, nir_shader *nir,
380 const struct vk_graphics_pipeline_state *state)
381 {
382 /* msl_nir_lower_sample_shading needs to go before blending since
383 * nir_lower_blend will always set uses_sample_shading to true if there's any
384 * output read. I believe we do not need to lower it always, that is why it
385 * goes here but need to double check. */
386 if (nir->info.fs.uses_sample_shading)
387 NIR_PASS(_, nir, msl_nir_lower_sample_shading);
388
389 if (state->cb)
390 kk_lower_fs_blend(nir, state);
391
392 enum pipe_format rts[MAX_DRAW_BUFFERS] = {PIPE_FORMAT_NONE};
393 const struct vk_render_pass_state *rp = state->rp;
394 for (uint32_t i = 0u; i < MAX_DRAW_BUFFERS; ++i)
395 rts[i] = vk_format_to_pipe_format(rp->color_attachment_formats[i]);
396
397 NIR_PASS(_, nir, msl_nir_fs_force_output_signedness, rts);
398
399 if (state->rp->depth_attachment_format == VK_FORMAT_UNDEFINED ||
400 nir->info.fs.early_fragment_tests)
401 NIR_PASS(_, nir, nir_shader_intrinsics_pass,
402 msl_nir_fs_remove_depth_write, nir_metadata_control_flow, NULL);
403
404 /* Input attachments are treated as 2D textures. Fixes sampler dimension */
405 NIR_PASS(_, nir, nir_shader_tex_pass, lower_subpass_dim, nir_metadata_all,
406 NULL);
407
408 /* Swizzle non-native formats' outputs */
409 NIR_PASS(_, nir, nir_shader_intrinsics_pass, kk_nir_swizzle_fragment_output,
410 nir_metadata_control_flow, (void *)state);
411
412 NIR_PASS(_, nir, msl_nir_fs_io_types);
413
414 if (state->ms && state->ms->rasterization_samples &&
415 state->ms->sample_mask != UINT16_MAX) {
416
417 /* KK_WORKAROUND_7 */
418 if (!(dev->disabled_workarounds & BITFIELD64_BIT(7))) {
419 if (!nir->info.fs.early_fragment_tests) {
420 nir_function_impl *entrypoint = nir_shader_get_entrypoint(nir);
421 nir_builder b = nir_builder_at(nir_after_impl(entrypoint));
422 nir_discard_if(&b,
423 nir_ieq_imm(&b, nir_load_sample_mask_in(&b), 0u));
424 }
425 }
426 NIR_PASS(_, nir, msl_lower_static_sample_mask, state->ms->sample_mask);
427 }
428 /* Check https://github.com/KhronosGroup/Vulkan-Portability/issues/54 for
429 * explanation on why we need this. */
430 else if (nir->info.fs.needs_full_quad_helper_invocations ||
431 nir->info.fs.needs_coarse_quad_helper_invocations)
432 NIR_PASS(_, nir, msl_lower_static_sample_mask, 0xFFFFFFFF);
433
434 /* KK_WORKAROUND_5 */
435 if (!(dev->disabled_workarounds & BITFIELD64_BIT(5)))
436 NIR_PASS(_, nir, msl_nir_fake_guard_for_discards);
437 /* KK_WORKAROUND_4 */
438 if (!(dev->disabled_workarounds & BITFIELD64_BIT(4))) {
439 NIR_PASS(_, nir, nir_lower_helper_writes, true);
440 NIR_PASS(_, nir, nir_lower_is_helper_invocation);
441 }
442 }
443
444 static void
445 kk_lower_nir(struct kk_device *dev, nir_shader *nir,
446 const struct vk_pipeline_robustness_state *rs,
447 uint32_t set_layout_count,
448 struct vk_descriptor_set_layout *const *set_layouts,
449 const struct vk_graphics_pipeline_state *state)
450 {
451 if (KK_DEBUG(FORCE_ROBUSTNESS))
452 rs = &rs_all_supported;
453
454 const nir_opt_access_options access_options = {
455 .is_vulkan = true,
456 };
457 NIR_PASS(_, nir, nir_opt_access, &access_options);
458
459 /* Massage IO related variables to please Metal */
460 if (nir->info.stage == MESA_SHADER_VERTEX) {
461 NIR_PASS(_, nir, kk_nir_lower_vs_multiview, state->mv->view_mask);
462
463 /* kk_nir_lower_vs_multiview may create a temporary array to assign the
464 * correct view index. Since we don't handle derefs, we need to get rid of
465 * them. */
466 NIR_PASS(_, nir, nir_lower_vars_to_scratch, 0,
467 glsl_get_natural_size_align_bytes,
468 glsl_get_natural_size_align_bytes);
469
470 NIR_PASS(_, nir, msl_ensure_vertex_position_output);
471 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
472 NIR_PASS(_, nir, kk_nir_lower_fs_multiview, state->mv->view_mask);
473
474 if (state->rp->depth_attachment_format != VK_FORMAT_UNDEFINED &&
475 state->ial && state->ial->depth_att != MESA_VK_ATTACHMENT_NO_INDEX) {
476 NIR_PASS(_, nir, msl_ensure_depth_write);
477 }
478 }
479
480 const struct lower_ycbcr_state ycbcr_state = {
481 .set_layout_count = set_layout_count,
482 .set_layouts = set_layouts,
483 };
484 NIR_PASS(_, nir, nir_vk_lower_ycbcr_tex, lookup_ycbcr_conversion,
485 &ycbcr_state);
486
487 /* Common msl texture lowering needs to happen after ycbcr lowering and
488 * before descriptor lowering. */
489 NIR_PASS(_, nir, msl_lower_textures);
490
491 /* Lower push constants before lower_descriptors */
492 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_push_const,
493 nir_address_format_32bit_offset);
494
495 NIR_PASS(_, nir, nir_lower_memory_model);
496
497 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_global,
498 nir_address_format_64bit_global);
499 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ssbo,
500 kk_buffer_addr_format(rs->storage_buffers));
501 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ubo,
502 kk_buffer_addr_format(rs->uniform_buffers));
503
504 NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
505 type_size_vec4,
506 nir_lower_io_lower_64bit_to_32 |
507 nir_lower_io_use_interpolated_input_intrinsics);
508
509 NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, nir_var_mem_shared,
510 shared_var_info);
511
512 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_shared,
513 nir_address_format_32bit_offset);
514
515 if (nir->info.zero_initialize_shared_memory && nir->info.shared_size > 0) {
516 /* QMD::SHARED_MEMORY_SIZE requires an alignment of 256B so it's safe to
517 * align everything up to 16B so we can write whole vec4s.
518 */
519 nir->info.shared_size = align(nir->info.shared_size, 16);
520 NIR_PASS(_, nir, nir_zero_initialize_shared_memory, nir->info.shared_size,
521 16);
522
523 /* We need to call lower_compute_system_values again because
524 * nir_zero_initialize_shared_memory generates load_invocation_id which
525 * has to be lowered to load_invocation_index.
526 */
527 NIR_PASS(_, nir, nir_lower_compute_system_values, NULL);
528 }
529
530 NIR_PASS(_, nir, nir_opt_dce);
531 NIR_PASS(_, nir, nir_lower_variable_initializers, ~nir_var_function_temp);
532 NIR_PASS(_, nir, nir_remove_dead_variables,
533 nir_var_shader_in | nir_var_shader_out | nir_var_system_value,
534 NULL);
535 nir->info.io_lowered = true;
536
537 /* Required before kk_nir_lower_vbo so load_input intrinsics' parents are
538 * load_const, otherwise the pass will complain */
539 NIR_PASS(_, nir, nir_opt_constant_folding);
540
541 /* These passes operate on lowered IO. */
542 if (nir->info.stage == MESA_SHADER_VERTEX) {
543 kk_lower_vs(nir, state);
544 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
545 kk_lower_fs(dev, nir, state);
546 }
547
548 /* Descriptor lowering needs to happen after lowering blend since we will
549 * generate a nir_intrinsic_load_blend_const_color_rgba which gets lowered by
550 * the lower descriptor pass
551 */
552 NIR_PASS(_, nir, kk_nir_lower_descriptors, rs, set_layout_count,
553 set_layouts);
554 NIR_PASS(_, nir, kk_nir_lower_textures);
555
556 NIR_PASS(_, nir, nir_lower_global_vars_to_local);
557 }
558
559 static const struct vk_shader_ops kk_shader_ops;
560
561 static void
562 kk_shader_destroy(struct vk_device *vk_dev, struct vk_shader *vk_shader,
563 const VkAllocationCallbacks *pAllocator)
564 {
565 struct kk_device *dev = container_of(vk_dev, struct kk_device, vk);
566 struct kk_shader *shader = container_of(vk_shader, struct kk_shader, vk);
567
568 if (shader->info.stage == MESA_SHADER_COMPUTE) {
569 mtl_release(shader->pipeline.cs);
570 } else if (shader->info.stage == MESA_SHADER_VERTEX) {
571 mtl_release(shader->pipeline.gfx.handle);
572 if (shader->pipeline.gfx.ds_handle)
573 mtl_release(shader->pipeline.gfx.ds_handle);
574 shader->pipeline.gfx.handle = NULL;
575 shader->pipeline.gfx.ds_handle = NULL;
576
577 ralloc_free((void *)shader->info.vs.frag_msl_code);
578 ralloc_free((void *)shader->info.vs.frag_entrypoint_name);
579 }
580
581 ralloc_free((void *)shader->msl_code);
582 ralloc_free((void *)shader->entrypoint_name);
583
584 vk_shader_free(&dev->vk, pAllocator, &shader->vk);
585 }
586
587 static bool
588 gather_vs_inputs(nir_builder *b, nir_intrinsic_instr *intr, void *data)
589 {
590 if (intr->intrinsic != nir_intrinsic_load_input)
591 return false;
592
593 struct nir_io_semantics io = nir_intrinsic_io_semantics(intr);
594 BITSET_WORD *attribs_read = data;
595 BITSET_SET(attribs_read, (io.location - VERT_ATTRIB_GENERIC0));
596 return false;
597 }
598
599 static void
600 gather_shader_info(struct kk_shader *shader, nir_shader *nir,
601 const struct vk_graphics_pipeline_state *state)
602 {
603 shader->info.stage = nir->info.stage;
604 if (nir->info.stage == MESA_SHADER_VERTEX) {
605 nir_shader_intrinsics_pass(nir, gather_vs_inputs, nir_metadata_all,
606 &shader->info.vs.attribs_read);
607 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
608 /* Some meta shaders like vk-meta-resolve will have depth_layout as NONE
609 * which is not a valid Metal layout */
610 if (nir->info.fs.depth_layout == FRAG_DEPTH_LAYOUT_NONE)
611 nir->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
612 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
613 shader->info.cs.local_size.x = nir->info.workgroup_size[0];
614 shader->info.cs.local_size.y = nir->info.workgroup_size[1];
615 shader->info.cs.local_size.z = nir->info.workgroup_size[2];
616 }
617 }
618
619 static void
620 modify_nir_info(nir_shader *nir)
621 {
622 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
623 if (nir->info.stage == MESA_SHADER_VERTEX) {
624 /* Vertex attribute fetch is done in shader through argument buffers. */
625 nir->info.inputs_read = 0u;
626 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
627 /* Some meta shaders like vk-meta-resolve will have depth_layout as NONE
628 * which is not a valid Metal layout */
629 if (nir->info.fs.depth_layout == FRAG_DEPTH_LAYOUT_NONE)
630 nir->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
631
632 /* These values are part of the declaration and go with IO. We only
633 * require the instrunctions to understand interpolation mode. */
634 BITSET_CLEAR(nir->info.system_values_read,
635 SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL);
636 BITSET_CLEAR(nir->info.system_values_read,
637 SYSTEM_VALUE_BARYCENTRIC_PERSP_SAMPLE);
638 BITSET_CLEAR(nir->info.system_values_read,
639 SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID);
640 BITSET_CLEAR(nir->info.system_values_read,
641 SYSTEM_VALUE_BARYCENTRIC_LINEAR_PIXEL);
642 BITSET_CLEAR(nir->info.system_values_read,
643 SYSTEM_VALUE_BARYCENTRIC_LINEAR_CENTROID);
644 BITSET_CLEAR(nir->info.system_values_read,
645 SYSTEM_VALUE_BARYCENTRIC_LINEAR_SAMPLE);
646 }
647 }
648
649 static VkResult
650 kk_compile_shader(struct kk_device *dev, struct vk_shader_compile_info *info,
651 const struct vk_graphics_pipeline_state *state,
652 const VkAllocationCallbacks *pAllocator,
653 struct vk_shader **shader_out)
654 {
655 struct kk_shader *shader;
656 VkResult result = VK_SUCCESS;
657
658 /* We consume the NIR, regardless of success or failure */
659 nir_shader *nir = info->nir;
660
661 shader = vk_shader_zalloc(&dev->vk, &kk_shader_ops, info->stage, pAllocator,
662 sizeof(*shader));
663 if (shader == NULL) {
664 ralloc_free(nir);
665 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
666 }
667
668 if (nir->info.io_lowered == false)
669 kk_lower_nir(dev, nir, info->robustness, info->set_layout_count,
670 info->set_layouts, state);
671
672 gather_shader_info(shader, nir, state);
673
674 /* VBO lowering needs to go here otherwise, the linking step removes all
675 * inputs since we read vertex attributes from UBOs. */
676 if (info->stage == MESA_SHADER_VERTEX) {
677 kk_lower_vs_vbo(nir, state);
678 }
679 msl_lower_nir_late(nir);
680 msl_optimize_nir(nir);
681 modify_nir_info(nir);
682
683 struct nir_to_msl_options translate_options = {
684 .mem_ctx = NULL,
685 .disabled_workarounds = dev->disabled_workarounds,
686 };
687 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
688 for (uint32_t i = 0u; i < MAX_DRAW_BUFFERS; ++i) {
689 enum pipe_format format =
690 vk_format_to_pipe_format(state->rp->color_attachment_formats[i]);
691
692 /* If the attachment is unused, default to 4 to avoid issues with alpha
693 * to coverage with unused attachments. */
694 translate_options.rts_component_count[i] =
695 format == PIPE_FORMAT_NONE ? 4u
696 : util_format_get_nr_components(format);
697 }
698 }
699 shader->msl_code = nir_to_msl(nir, &translate_options);
700 const char *entrypoint_name = nir_shader_get_entrypoint(nir)->function->name;
701
702 /* We need to steal so it doesn't get destroyed with the nir. Needs to happen
703 * after nir_to_msl since that's where we rename the entrypoint.
704 */
705 ralloc_steal(NULL, (void *)entrypoint_name);
706 shader->entrypoint_name = entrypoint_name;
707
708 if (KK_DEBUG(MSL))
709 mesa_logi("%s\n", shader->msl_code);
710
711 ralloc_free(nir);
712
713 *shader_out = &shader->vk;
714
715 return result;
716 }
717
718 static const struct vk_pipeline_robustness_state rs_none = {
719 .uniform_buffers = VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT,
720 .storage_buffers = VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT,
721 .images = VK_PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT,
722 };
723
724 VkResult
725 kk_compile_nir_shader(struct kk_device *dev, nir_shader *nir,
726 const VkAllocationCallbacks *alloc,
727 struct kk_shader **shader_out)
728 {
729 const struct kk_physical_device *pdev = kk_device_physical(dev);
730
731 assert(nir->info.stage == MESA_SHADER_COMPUTE);
732 if (nir->options == NULL)
733 nir->options = kk_get_nir_options((struct vk_physical_device *)&pdev->vk,
734 nir->info.stage, &rs_none);
735
736 struct vk_shader_compile_info info = {
737 .stage = nir->info.stage,
738 .nir = nir,
739 .robustness = &rs_none,
740 };
741
742 struct vk_shader *shader = NULL;
743 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
744 VkResult result = kk_compile_shader(dev, &info, NULL, alloc, &shader);
745 if (result != VK_SUCCESS)
746 return result;
747
748 *shader_out = container_of(shader, struct kk_shader, vk);
749
750 return VK_SUCCESS;
751 }
752
753 static void
754 nir_opts(nir_shader *nir, void *data)
755 {
756 bool progress;
757
758 do {
759 progress = false;
760
761 NIR_PASS(progress, nir, nir_opt_loop);
762 NIR_PASS(progress, nir, nir_opt_copy_prop);
763 NIR_PASS(progress, nir, nir_opt_remove_phis);
764 NIR_PASS(progress, nir, nir_opt_dce);
765
766 NIR_PASS(progress, nir, nir_opt_if, 0);
767 NIR_PASS(progress, nir, nir_opt_dead_cf);
768 NIR_PASS(progress, nir, nir_opt_cse);
769
770 NIR_PASS(progress, nir, nir_opt_peephole_select,
771 &(nir_opt_peephole_select_options){
772 .limit = 8,
773 .expensive_alu_ok = true,
774 .discard_ok = true,
775 });
776
777 NIR_PASS(progress, nir, nir_opt_phi_precision);
778 NIR_PASS(progress, nir, nir_opt_algebraic);
779 NIR_PASS(progress, nir, nir_opt_constant_folding);
780
781 NIR_PASS(progress, nir, nir_opt_undef);
782 NIR_PASS(progress, nir, nir_opt_loop_unroll);
783 } while (progress);
784 }
785
786 static nir_shader *
787 get_empty_nir(struct kk_device *dev, mesa_shader_stage stage,
788 const struct vk_graphics_pipeline_state *state)
789 {
790 nir_shader *nir = nir_shader_create(
791 NULL, stage,
792 kk_get_nir_options(&kk_device_physical(dev)->vk, stage, NULL));
793
794 nir_function *function = nir_function_create(nir, "main_entrypoint");
795 function->is_entrypoint = true;
796 nir_function_impl_create(function);
797
798 const struct vk_pipeline_robustness_state no_robustness = {
799 .storage_buffers = VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED,
800 .uniform_buffers = VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED,
801 .vertex_inputs = VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED,
802 .images = VK_PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED,
803 .null_uniform_buffer_descriptor = false,
804 .null_storage_buffer_descriptor = false,
805 };
806 kk_lower_nir(dev, nir, &no_robustness, 0u, NULL, state);
807 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
808
809 return nir;
810 }
811
812 static VkResult
813 kk_compile_compute_pipeline(struct kk_device *device, struct kk_shader *shader)
814 {
815 uint32_t local_size_threads = shader->info.cs.local_size.x *
816 shader->info.cs.local_size.y *
817 shader->info.cs.local_size.z;
818 mtl_library *library = mtl_new_library(device->mtl_handle, shader->msl_code);
819 if (library == NULL)
820 return VK_ERROR_INVALID_SHADER_NV;
821
822 mtl_function *function =
823 mtl_new_function_with_name(library, shader->entrypoint_name);
824 shader->pipeline.cs = mtl_new_compute_pipeline_state(
825 device->mtl_handle, function, local_size_threads);
826 mtl_release(function);
827 mtl_release(library);
828
829 if (shader->pipeline.cs == NULL)
830 return VK_ERROR_INVALID_SHADER_NV;
831
832 return VK_SUCCESS;
833 }
834
835 static bool
836 has_static_depth_stencil_state(const struct vk_graphics_pipeline_state *state)
837 {
838 if (!state->ds)
839 return false;
840
841 return !(
842 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_DEPTH_TEST_ENABLE) |
843 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_DEPTH_WRITE_ENABLE) |
844 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_DEPTH_COMPARE_OP) |
845 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_STENCIL_TEST_ENABLE) |
846 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_STENCIL_OP) |
847 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_STENCIL_COMPARE_MASK) |
848 BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_DS_STENCIL_WRITE_MASK));
849 }
850
851 static mtl_depth_stencil_state *
852 kk_compile_ds_state(struct kk_device *device, struct kk_shader_info *info)
853 {
854 mtl_stencil_descriptor *front = NULL;
855 mtl_stencil_descriptor *back = NULL;
856 mtl_depth_stencil_descriptor *descriptor =
857 mtl_new_depth_stencil_descriptor();
858 mtl_depth_stencil_descriptor_set_depth_write_enabled(
859 descriptor, info->vs.has_depth_write);
860 mtl_depth_stencil_descriptor_set_depth_compare_function(
861 descriptor, info->vs.depth_compare_op);
862
863 if (info->vs.has_stencil_test) {
864 back = mtl_new_stencil_descriptor();
865 mtl_stencil_descriptor_set_depth_failure_operation(
866 back, info->vs.stencil_back.depth_fail);
867 mtl_stencil_descriptor_set_stencil_failure_operation(
868 back, info->vs.stencil_back.fail);
869 mtl_stencil_descriptor_set_depth_stencil_pass_operation(
870 back, info->vs.stencil_back.pass);
871 mtl_stencil_descriptor_set_stencil_compare_function(
872 back, info->vs.stencil_back.compare);
873 mtl_stencil_descriptor_set_read_mask(back,
874 info->vs.stencil_back.compare_mask);
875 mtl_stencil_descriptor_set_write_mask(back,
876 info->vs.stencil_back.write_mask);
877 mtl_depth_stencil_descriptor_set_back_face_stencil(descriptor, back);
878
879 front = mtl_new_stencil_descriptor();
880 mtl_stencil_descriptor_set_depth_failure_operation(
881 front, info->vs.stencil_front.depth_fail);
882 mtl_stencil_descriptor_set_stencil_failure_operation(
883 front, info->vs.stencil_front.fail);
884 mtl_stencil_descriptor_set_depth_stencil_pass_operation(
885 front, info->vs.stencil_front.pass);
886 mtl_stencil_descriptor_set_stencil_compare_function(
887 front, info->vs.stencil_front.compare);
888 mtl_stencil_descriptor_set_read_mask(front,
889 info->vs.stencil_front.compare_mask);
890 mtl_stencil_descriptor_set_write_mask(front,
891 info->vs.stencil_front.write_mask);
892 mtl_depth_stencil_descriptor_set_front_face_stencil(descriptor, front);
893 }
894
895 mtl_depth_stencil_state *state =
896 mtl_new_depth_stencil_state(device->mtl_handle, descriptor);
897
898 if (front)
899 mtl_release(front);
900 if (back)
901 mtl_release(back);
902 mtl_release(descriptor);
903
904 return state;
905 }
906
907 static void
908 kk_gather_ds_info(const struct vk_depth_stencil_state *ds, bool has_depth,
909 bool has_stencil, struct kk_shader_info *info)
910 {
911 /* Depth */
912 if (has_depth && ds->depth.test_enable) {
913 info->vs.has_depth_write = ds->depth.write_enable;
914 info->vs.depth_compare_op = ds->depth.compare_op;
915 } else {
916 info->vs.has_depth_write = false;
917 info->vs.depth_compare_op = VK_COMPARE_OP_ALWAYS;
918 }
919
920 /* Stencil */
921 info->vs.has_stencil_test = has_stencil && ds->stencil.test_enable;
922 if (info->vs.has_stencil_test) {
923 info->vs.stencil_back.depth_fail = ds->stencil.back.op.depth_fail;
924 info->vs.stencil_back.fail = ds->stencil.back.op.fail;
925 info->vs.stencil_back.pass = ds->stencil.back.op.pass;
926 info->vs.stencil_back.compare = ds->stencil.back.op.compare;
927 info->vs.stencil_back.compare_mask = ds->stencil.back.compare_mask;
928 info->vs.stencil_back.write_mask = ds->stencil.back.write_mask;
929
930 info->vs.stencil_front.depth_fail = ds->stencil.front.op.depth_fail;
931 info->vs.stencil_front.fail = ds->stencil.front.op.fail;
932 info->vs.stencil_front.pass = ds->stencil.front.op.pass;
933 info->vs.stencil_front.compare = ds->stencil.front.op.compare;
934 info->vs.stencil_front.compare_mask = ds->stencil.front.compare_mask;
935 info->vs.stencil_front.write_mask = ds->stencil.front.write_mask;
936 }
937 }
938
939 mtl_depth_stencil_state *
940 kk_compile_depth_stencil_state(struct kk_device *device,
941 const struct vk_depth_stencil_state *ds,
942 bool has_depth, bool has_stencil)
943 {
944 struct kk_shader_info info = {};
945 kk_gather_ds_info(ds, has_depth, has_stencil, &info);
946 return kk_compile_ds_state(device, &info);
947 }
948
949 static struct kk_shader_info
950 gather_graphics_pipeline_create_info(
951 const struct vk_graphics_pipeline_state *state, uint32_t attribs_read,
952 struct kk_shader *fs)
953 {
954 assert(state && fs && "state and fragment shader are a must");
955 struct kk_shader_info info = {.vs.attribs_read = attribs_read};
956
957 info.vs.topology = vk_primitive_topology_to_mtl_primitive_topology_class(
958 state->ia->primitive_topology);
959
960 /* Render pass data */
961 const struct vk_render_pass_state *rp = state->rp;
962 bool has_depth = rp->depth_attachment_format != VK_FORMAT_UNDEFINED;
963 bool has_stencil = rp->stencil_attachment_format != VK_FORMAT_UNDEFINED;
964 {
965 info.vs.color_attachment_count = rp->color_attachment_count;
966 for (uint8_t i = 0u; i < info.vs.color_attachment_count; ++i) {
967 VkFormat format = rp->color_attachment_formats[i];
968 info.vs.rt_formats[i] = format == VK_FORMAT_UNDEFINED
969 ? MTL_PIXEL_FORMAT_INVALID
970 : vk_format_to_mtl_pixel_format(format);
971 }
972 info.vs.d_format =
973 has_depth ? vk_format_to_mtl_pixel_format(rp->depth_attachment_format)
974 : MTL_PIXEL_FORMAT_INVALID;
975 info.vs.s_format =
976 has_stencil
977 ? vk_format_to_mtl_pixel_format(rp->stencil_attachment_format)
978 : MTL_PIXEL_FORMAT_INVALID;
979
980 info.vs.view_mask = state->mv->view_mask;
981 }
982
983 info.vs.has_ds = has_static_depth_stencil_state(state);
984 if (info.vs.has_ds)
985 kk_gather_ds_info(state->ds, has_depth, has_stencil, &info);
986
987 info.vs.has_ms = state->ms != NULL;
988 info.vs.sample_count = 1u;
989 if (info.vs.has_ms) {
990 const struct vk_multisample_state *ms = state->ms;
991 info.vs.sample_count = ms->rasterization_samples;
992 info.vs.has_alpha_to_coverage_enabled = ms->alpha_to_coverage_enable;
993 info.vs.has_alpha_to_one_enabled = ms->alpha_to_one_enable;
994 }
995
996 /* We need to store the fragment source in the vertex too otherwise we won't
997 * be able to create the whole pipeline correctly. */
998 {
999 uint32_t length = strlen(fs->msl_code);
1000 info.vs.frag_msl_code = ralloc_size(NULL, length + 1u);
1001 strcpy(info.vs.frag_msl_code, fs->msl_code);
1002 info.vs.frag_msl_code[length] = '\0';
1003
1004 length = strlen(fs->entrypoint_name);
1005 info.vs.frag_entrypoint_name = ralloc_size(NULL, length + 1u);
1006 strcpy(info.vs.frag_entrypoint_name, fs->entrypoint_name);
1007 info.vs.frag_entrypoint_name[length] = '\0';
1008 }
1009
1010 return info;
1011 }
1012
1013 /* TODO_KOSMICKRISP For now we just support vertex and fragment */
1014 static VkResult
1015 kk_compile_graphics_pipeline(struct kk_device *device, const char *vs,
1016 const char *vs_entrypoint_name, const char *fs,
1017 const char *fs_entrypoint_name,
1018 struct kk_shader_info *info,
1019 struct kk_pipeline_handles *pipeline)
1020 {
1021 VkResult result = VK_SUCCESS;
1022
1023 mtl_library *vertex_library = mtl_new_library(device->mtl_handle, vs);
1024 if (vertex_library == NULL)
1025 return VK_ERROR_INVALID_SHADER_NV;
1026
1027 mtl_function *vertex_function =
1028 mtl_new_function_with_name(vertex_library, vs_entrypoint_name);
1029
1030 mtl_library *fragment_library = mtl_new_library(device->mtl_handle, fs);
1031 if (fragment_library == NULL) {
1032 result = VK_ERROR_INVALID_SHADER_NV;
1033 goto destroy_vertex;
1034 }
1035 mtl_function *fragment_function =
1036 mtl_new_function_with_name(fragment_library, fs_entrypoint_name);
1037
1038 mtl_render_pipeline_descriptor *pipeline_descriptor =
1039 mtl_new_render_pipeline_descriptor();
1040 mtl_render_pipeline_descriptor_set_vertex_shader(pipeline_descriptor,
1041 vertex_function);
1042 mtl_render_pipeline_descriptor_set_fragment_shader(pipeline_descriptor,
1043 fragment_function);
1044
1045 /* Layered rendering in Metal requires setting primitive topology class */
1046 mtl_render_pipeline_descriptor_set_input_primitive_topology(
1047 pipeline_descriptor, info->vs.topology);
1048
1049 for (uint8_t i = 0; i < info->vs.color_attachment_count; ++i) {
1050 if (info->vs.rt_formats[i] != MTL_PIXEL_FORMAT_INVALID)
1051 mtl_render_pipeline_descriptor_set_color_attachment_format(
1052 pipeline_descriptor, i, info->vs.rt_formats[i]);
1053 }
1054
1055 if (info->vs.d_format != MTL_PIXEL_FORMAT_INVALID)
1056 mtl_render_pipeline_descriptor_set_depth_attachment_format(
1057 pipeline_descriptor, info->vs.d_format);
1058
1059 if (info->vs.s_format != MTL_PIXEL_FORMAT_INVALID)
1060 mtl_render_pipeline_descriptor_set_stencil_attachment_format(
1061 pipeline_descriptor, info->vs.s_format);
1062
1063 if (info->vs.has_ds) {
1064 pipeline->gfx.ds_handle = kk_compile_ds_state(device, info);
1065 }
1066
1067 if (info->vs.view_mask) {
1068 uint32_t max_amplification = util_bitcount(info->vs.view_mask);
1069 mtl_render_pipeline_descriptor_set_max_vertex_amplification_count(
1070 pipeline_descriptor, max_amplification);
1071 }
1072
1073 if (info->vs.has_ms) {
1074 mtl_render_pipeline_descriptor_set_raster_sample_count(
1075 pipeline_descriptor, info->vs.sample_count);
1076 mtl_render_pipeline_descriptor_set_alpha_to_coverage(
1077 pipeline_descriptor, info->vs.has_alpha_to_coverage_enabled);
1078 mtl_render_pipeline_descriptor_set_alpha_to_one(
1079 pipeline_descriptor, info->vs.has_alpha_to_one_enabled);
1080 }
1081
1082 pipeline->gfx.handle =
1083 mtl_new_render_pipeline(device->mtl_handle, pipeline_descriptor);
1084 if (pipeline->gfx.handle == NULL)
1085 result = VK_ERROR_INVALID_SHADER_NV;
1086
1087 mtl_release(pipeline_descriptor);
1088 mtl_release(fragment_function);
1089 mtl_release(fragment_library);
1090 destroy_vertex:
1091 mtl_release(vertex_function);
1092 mtl_release(vertex_library);
1093
1094 return result;
1095 }
1096
1097 static VkResult
1098 kk_compile_shaders(struct vk_device *device, uint32_t shader_count,
1099 struct vk_shader_compile_info *infos,
1100 const struct vk_graphics_pipeline_state *state,
1101 const struct vk_features *enabled_features,
1102 const VkAllocationCallbacks *pAllocator,
1103 struct vk_shader **shaders_out)
1104 {
1105 VkResult result = VK_SUCCESS;
1106 struct kk_device *dev = container_of(device, struct kk_device, vk);
1107
1108 /* Vulkan doesn't enforce a fragment shader to build pipelines. We may need
1109 * to create one. */
1110 nir_shader *null_fs = NULL;
1111 nir_shader *shaders[shader_count + 1u];
1112
1113 /* Lower shaders, notably lowering IO. This is a prerequisite for intershader
1114 * optimization. */
1115 for (uint32_t i = 0u; i < shader_count; ++i) {
1116 const struct vk_shader_compile_info *info = &infos[i];
1117 nir_shader *nir = info->nir;
1118
1119 kk_lower_nir(dev, nir, info->robustness, info->set_layout_count,
1120 info->set_layouts, state);
1121
1122 shaders[i] = nir;
1123 }
1124
1125 /* Since we don't support GPL nor shader objects and Metal render pipelines
1126 * require both vertex and fragment, we may need to provide a pass-through
1127 * fragment. */
1128 if (state &&
1129 shaders[shader_count - 1u]->info.stage != MESA_SHADER_FRAGMENT) {
1130 null_fs = get_empty_nir(dev, MESA_SHADER_FRAGMENT, state);
1131 shaders[shader_count] = null_fs;
1132 }
1133
1134 uint32_t total_shaders = null_fs ? shader_count + 1 : shader_count;
1135 nir_opt_varyings_bulk(shaders, total_shaders, true, UINT32_MAX, UINT32_MAX,
1136 nir_opts, NULL);
1137 /* Second pass is required because some dEQP-VK.glsl.matrix.sub.dynamic.*
1138 * would fail otherwise due to vertex outputting vec4 while fragments reading
1139 * vec3 when in reality only vec3 is needed. */
1140 nir_opt_varyings_bulk(shaders, total_shaders, true, UINT32_MAX, UINT32_MAX,
1141 nir_opts, NULL);
1142
1143 for (uint32_t i = 0; i < shader_count; i++) {
1144 result =
1145 kk_compile_shader(dev, &infos[i], state, pAllocator, &shaders_out[i]);
1146 if (result != VK_SUCCESS) {
1147 /* Clean up all the shaders before this point */
1148 for (uint32_t j = 0; j < i; j++)
1149 kk_shader_destroy(&dev->vk, shaders_out[j], pAllocator);
1150
1151 /* Clean up all the NIR after this point */
1152 for (uint32_t j = i + 1; j < shader_count; j++)
1153 ralloc_free(shaders[j]);
1154
1155 if (null_fs)
1156 ralloc_free(null_fs);
1157
1158 /* Memset the output array */
1159 memset(shaders_out, 0, shader_count * sizeof(*shaders_out));
1160
1161 return result;
1162 }
1163 }
1164
1165 /* Compile pipeline:
1166 * 1. Compute pipeline
1167 * 2. Graphics with all stages (since we don't support GPL nor shader
1168 * objects for now). This will be addressed later.
1169 */
1170 if (shaders_out[0]->stage == MESA_SHADER_COMPUTE) {
1171 result = kk_compile_compute_pipeline(
1172 dev, container_of(shaders_out[0], struct kk_shader, vk));
1173 } else {
1174 struct kk_shader *vs = container_of(shaders_out[0], struct kk_shader, vk);
1175 struct kk_shader *fs =
1176 container_of(shaders_out[shader_count - 1u], struct kk_shader, vk);
1177 if (null_fs) {
1178 struct vk_shader_compile_info info = {
1179 .stage = MESA_SHADER_FRAGMENT,
1180 .nir = null_fs,
1181 .robustness = &rs_none,
1182 };
1183 struct vk_shader *frag_shader;
1184 result =
1185 kk_compile_shader(dev, &info, state, &dev->vk.alloc, &frag_shader);
1186
1187 if (result != VK_SUCCESS) {
1188 for (uint32_t i = 0; i < shader_count; i++)
1189 kk_shader_destroy(&dev->vk, shaders_out[i], pAllocator);
1190
1191 /* Memset the output array */
1192 memset(shaders_out, 0, shader_count * sizeof(*shaders_out));
1193
1194 return result;
1195 }
1196 fs = container_of(frag_shader, struct kk_shader, vk);
1197 }
1198
1199 vs->info = gather_graphics_pipeline_create_info(
1200 state, vs->info.vs.attribs_read, fs);
1201 result = kk_compile_graphics_pipeline(
1202 dev, vs->msl_code, vs->entrypoint_name, fs->msl_code,
1203 fs->entrypoint_name, &vs->info, &vs->pipeline);
1204
1205 if (null_fs)
1206 kk_shader_destroy(&dev->vk, &fs->vk, pAllocator);
1207 }
1208
1209 return result;
1210 }
1211
1212 static bool
1213 kk_shader_serialize(struct vk_device *vk_dev, const struct vk_shader *vk_shader,
1214 struct blob *blob)
1215 {
1216 struct kk_shader *shader = container_of(vk_shader, struct kk_shader, vk);
1217
1218 blob_write_bytes(blob, &shader->info, sizeof(shader->info));
1219 uint32_t entrypoint_length = strlen(shader->entrypoint_name) + 1;
1220 uint32_t code_length = strlen(shader->msl_code) + 1;
1221 blob_write_uint32(blob, entrypoint_length);
1222 blob_write_uint32(blob, code_length);
1223 blob_write_bytes(blob, shader->entrypoint_name, entrypoint_length);
1224 blob_write_bytes(blob, shader->msl_code, code_length);
1225
1226 if (shader->info.stage == MESA_SHADER_VERTEX) {
1227 entrypoint_length = strlen(shader->info.vs.frag_entrypoint_name) + 1;
1228 code_length = strlen(shader->info.vs.frag_msl_code) + 1;
1229 blob_write_uint32(blob, entrypoint_length);
1230 blob_write_uint32(blob, code_length);
1231 blob_write_bytes(blob, shader->info.vs.frag_entrypoint_name,
1232 entrypoint_length);
1233 blob_write_bytes(blob, shader->info.vs.frag_msl_code, code_length);
1234 }
1235
1236 return !blob->out_of_memory;
1237 }
1238
1239 static VkResult
1240 kk_deserialize_shader(struct vk_device *vk_dev, struct blob_reader *blob,
1241 uint32_t binary_version,
1242 const VkAllocationCallbacks *pAllocator,
1243 struct vk_shader **shader_out)
1244 {
1245 struct kk_device *dev = container_of(vk_dev, struct kk_device, vk);
1246 struct kk_shader *shader;
1247
1248 struct kk_shader_info info;
1249 blob_copy_bytes(blob, &info, sizeof(info));
1250
1251 const uint32_t entrypoint_length = blob_read_uint32(blob);
1252 const uint32_t code_length = blob_read_uint32(blob);
1253 if (blob->overrun)
1254 return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT);
1255
1256 shader = vk_shader_zalloc(&dev->vk, &kk_shader_ops, info.stage, pAllocator,
1257 sizeof(*shader));
1258 if (shader == NULL)
1259 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1260
1261 shader->info = info;
1262
1263 shader->entrypoint_name = ralloc_array(NULL, char, entrypoint_length);
1264 if (shader->entrypoint_name == NULL) {
1265 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1266 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1267 }
1268
1269 shader->msl_code = ralloc_array(NULL, char, code_length);
1270 if (shader->msl_code == NULL) {
1271 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1272 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1273 }
1274
1275 blob_copy_bytes(blob, (void *)shader->entrypoint_name, entrypoint_length);
1276 blob_copy_bytes(blob, (void *)shader->msl_code, code_length);
1277
1278 if (info.stage == MESA_SHADER_VERTEX) {
1279 const uint32_t frag_entrypoint_length = blob_read_uint32(blob);
1280 const uint32_t frag_code_length = blob_read_uint32(blob);
1281 shader->info.vs.frag_entrypoint_name =
1282 ralloc_array(NULL, char, frag_entrypoint_length);
1283 if (shader->info.vs.frag_entrypoint_name == NULL) {
1284 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1285 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1286 }
1287
1288 shader->info.vs.frag_msl_code =
1289 ralloc_array(NULL, char, frag_code_length);
1290 if (shader->info.vs.frag_msl_code == NULL) {
1291 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1292 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1293 }
1294
1295 blob_copy_bytes(blob, (void *)shader->info.vs.frag_entrypoint_name,
1296 frag_entrypoint_length);
1297 blob_copy_bytes(blob, (void *)shader->info.vs.frag_msl_code,
1298 frag_code_length);
1299 }
1300
1301 if (blob->overrun) {
1302 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1303 return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT);
1304 }
1305
1306 VkResult result = VK_SUCCESS;
1307 if (info.stage == MESA_SHADER_COMPUTE)
1308 result = kk_compile_compute_pipeline(dev, shader);
1309 else if (info.stage == MESA_SHADER_VERTEX) {
1310 result = kk_compile_graphics_pipeline(
1311 dev, shader->msl_code, shader->entrypoint_name,
1312 shader->info.vs.frag_msl_code, shader->info.vs.frag_entrypoint_name,
1313 &shader->info, &shader->pipeline);
1314 }
1315
1316 if (result != VK_SUCCESS) {
1317 kk_shader_destroy(&dev->vk, &shader->vk, pAllocator);
1318 return vk_error(dev, result);
1319 }
1320
1321 *shader_out = &shader->vk;
1322
1323 return VK_SUCCESS;
1324 }
1325
1326 void
1327 kk_cmd_bind_compute_shader(struct kk_cmd_buffer *cmd, struct kk_shader *shader)
1328 {
1329 cmd->state.shaders[MESA_SHADER_COMPUTE] = shader;
1330 }
1331
1332 static void
1333 kk_cmd_bind_graphics_shader(struct kk_cmd_buffer *cmd,
1334 const mesa_shader_stage stage,
1335 struct kk_shader *shader)
1336 {
1337 cmd->state.shaders[stage] = shader;
1338 cmd->state.dirty_shaders |= BITFIELD_BIT(stage);
1339
1340 /* Relevant pipeline data is only stored in vertex shaders */
1341 if (stage != MESA_SHADER_VERTEX)
1342 return;
1343
1344 bool requires_dynamic_depth_stencil = shader->pipeline.gfx.ds_handle == NULL;
1345 if (cmd->state.gfx.is_depth_stencil_dynamic) {
1346 /* If we are switching from dynamic to static, we need to clean up
1347 * temporary state. Otherwise, leave the existing dynamic state
1348 * untouched.
1349 */
1350 if (!requires_dynamic_depth_stencil) {
1351 mtl_release(cmd->state.gfx.depth_stencil_state);
1352 cmd->state.gfx.depth_stencil_state = shader->pipeline.gfx.ds_handle;
1353 }
1354 } else
1355 cmd->state.gfx.depth_stencil_state = shader->pipeline.gfx.ds_handle;
1356 cmd->state.gfx.is_depth_stencil_dynamic = requires_dynamic_depth_stencil;
1357 cmd->state.gfx.dirty |= KK_DIRTY_VB;
1358
1359 cmd->state.gfx.sample_count = shader->info.vs.sample_count;
1360 }
1361
1362 static void
1363 kk_cmd_bind_shaders(struct vk_command_buffer *cmd_buffer, uint32_t stage_count,
1364 const mesa_shader_stage *stages,
1365 struct vk_shader **const shaders)
1366 {
1367 struct kk_cmd_buffer *cmd =
1368 container_of(cmd_buffer, struct kk_cmd_buffer, vk);
1369
1370 for (uint32_t i = 0; i < stage_count; i++) {
1371 struct kk_shader *shader = container_of(shaders[i], struct kk_shader, vk);
1372
1373 if (stages[i] == MESA_SHADER_COMPUTE || stages[i] == MESA_SHADER_KERNEL)
1374 kk_cmd_bind_compute_shader(cmd, shader);
1375 else
1376 kk_cmd_bind_graphics_shader(cmd, stages[i], shader);
1377 }
1378 }
1379
1380 static VkResult
1381 kk_shader_get_executable_properties(
1382 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1383 uint32_t *executable_count, VkPipelineExecutablePropertiesKHR *properties)
1384 {
1385 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutablePropertiesKHR, out, properties,
1386 executable_count);
1387
1388 return vk_outarray_status(&out);
1389 }
1390
1391 static VkResult
1392 kk_shader_get_executable_statistics(
1393 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1394 uint32_t executable_index, uint32_t *statistic_count,
1395 VkPipelineExecutableStatisticKHR *statistics)
1396 {
1397 /* TODO_KOSMICKRISP */
1398 return VK_SUCCESS;
1399 }
1400
1401 static VkResult
1402 kk_shader_get_executable_internal_representations(
1403 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1404 uint32_t executable_index, uint32_t *internal_representation_count,
1405 VkPipelineExecutableInternalRepresentationKHR *internal_representations)
1406 {
1407 /* TODO_KOSMICKRISP */
1408 return VK_SUCCESS;
1409 }
1410
1411 static const struct vk_shader_ops kk_shader_ops = {
1412 .destroy = kk_shader_destroy,
1413 .serialize = kk_shader_serialize,
1414 .get_executable_properties = kk_shader_get_executable_properties,
1415 .get_executable_statistics = kk_shader_get_executable_statistics,
1416 .get_executable_internal_representations =
1417 kk_shader_get_executable_internal_representations,
1418 };
1419
1420 const struct vk_device_shader_ops kk_device_shader_ops = {
1421 .get_nir_options = kk_get_nir_options,
1422 .get_spirv_options = kk_get_spirv_options,
1423 .preprocess_nir = kk_preprocess_nir,
1424 .hash_state = kk_hash_graphics_state,
1425 .compile =
1426 kk_compile_shaders, /* This will only generate the MSL string we need to
1427 use for actual library generation */
1428 .deserialize = kk_deserialize_shader,
1429 .cmd_set_dynamic_graphics_state = vk_cmd_set_dynamic_graphics_state,
1430 .cmd_bind_shaders = kk_cmd_bind_shaders,
1431 };