spirv: fix Uniform and Output MemoryAccessMakePointer{Visible,Available}
[mesa.git] / src / compiler / spirv / spirv_to_nir.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 * Authors:
24 * Jason Ekstrand (jason@jlekstrand.net)
25 *
26 */
27
28 #include "vtn_private.h"
29 #include "nir/nir_vla.h"
30 #include "nir/nir_control_flow.h"
31 #include "nir/nir_constant_expressions.h"
32 #include "nir/nir_deref.h"
33 #include "spirv_info.h"
34
35 #include "util/format/u_format.h"
36 #include "util/u_math.h"
37
38 #include <stdio.h>
39
40 void
41 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
42 size_t spirv_offset, const char *message)
43 {
44 if (b->options->debug.func) {
45 b->options->debug.func(b->options->debug.private_data,
46 level, spirv_offset, message);
47 }
48
49 #ifndef NDEBUG
50 if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
51 fprintf(stderr, "%s\n", message);
52 #endif
53 }
54
55 void
56 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
57 size_t spirv_offset, const char *fmt, ...)
58 {
59 va_list args;
60 char *msg;
61
62 va_start(args, fmt);
63 msg = ralloc_vasprintf(NULL, fmt, args);
64 va_end(args);
65
66 vtn_log(b, level, spirv_offset, msg);
67
68 ralloc_free(msg);
69 }
70
71 static void
72 vtn_log_err(struct vtn_builder *b,
73 enum nir_spirv_debug_level level, const char *prefix,
74 const char *file, unsigned line,
75 const char *fmt, va_list args)
76 {
77 char *msg;
78
79 msg = ralloc_strdup(NULL, prefix);
80
81 #ifndef NDEBUG
82 ralloc_asprintf_append(&msg, " In file %s:%u\n", file, line);
83 #endif
84
85 ralloc_asprintf_append(&msg, " ");
86
87 ralloc_vasprintf_append(&msg, fmt, args);
88
89 ralloc_asprintf_append(&msg, "\n %zu bytes into the SPIR-V binary",
90 b->spirv_offset);
91
92 if (b->file) {
93 ralloc_asprintf_append(&msg,
94 "\n in SPIR-V source file %s, line %d, col %d",
95 b->file, b->line, b->col);
96 }
97
98 vtn_log(b, level, b->spirv_offset, msg);
99
100 ralloc_free(msg);
101 }
102
103 static void
104 vtn_dump_shader(struct vtn_builder *b, const char *path, const char *prefix)
105 {
106 static int idx = 0;
107
108 char filename[1024];
109 int len = snprintf(filename, sizeof(filename), "%s/%s-%d.spirv",
110 path, prefix, idx++);
111 if (len < 0 || len >= sizeof(filename))
112 return;
113
114 FILE *f = fopen(filename, "w");
115 if (f == NULL)
116 return;
117
118 fwrite(b->spirv, sizeof(*b->spirv), b->spirv_word_count, f);
119 fclose(f);
120
121 vtn_info("SPIR-V shader dumped to %s", filename);
122 }
123
124 void
125 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
126 const char *fmt, ...)
127 {
128 va_list args;
129
130 va_start(args, fmt);
131 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
132 file, line, fmt, args);
133 va_end(args);
134 }
135
136 void
137 _vtn_err(struct vtn_builder *b, const char *file, unsigned line,
138 const char *fmt, ...)
139 {
140 va_list args;
141
142 va_start(args, fmt);
143 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V ERROR:\n",
144 file, line, fmt, args);
145 va_end(args);
146 }
147
148 void
149 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
150 const char *fmt, ...)
151 {
152 va_list args;
153
154 va_start(args, fmt);
155 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
156 file, line, fmt, args);
157 va_end(args);
158
159 const char *dump_path = getenv("MESA_SPIRV_FAIL_DUMP_PATH");
160 if (dump_path)
161 vtn_dump_shader(b, dump_path, "fail");
162
163 longjmp(b->fail_jump, 1);
164 }
165
166 static struct vtn_ssa_value *
167 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
168 {
169 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
170 val->type = glsl_get_bare_type(type);
171
172 if (glsl_type_is_vector_or_scalar(type)) {
173 unsigned num_components = glsl_get_vector_elements(val->type);
174 unsigned bit_size = glsl_get_bit_size(val->type);
175 val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
176 } else {
177 unsigned elems = glsl_get_length(val->type);
178 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
179 if (glsl_type_is_array_or_matrix(type)) {
180 const struct glsl_type *elem_type = glsl_get_array_element(type);
181 for (unsigned i = 0; i < elems; i++)
182 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
183 } else {
184 vtn_assert(glsl_type_is_struct_or_ifc(type));
185 for (unsigned i = 0; i < elems; i++) {
186 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
187 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
188 }
189 }
190 }
191
192 return val;
193 }
194
195 static struct vtn_ssa_value *
196 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
197 const struct glsl_type *type)
198 {
199 struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
200
201 if (entry)
202 return entry->data;
203
204 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
205 val->type = glsl_get_bare_type(type);
206
207 if (glsl_type_is_vector_or_scalar(type)) {
208 unsigned num_components = glsl_get_vector_elements(val->type);
209 unsigned bit_size = glsl_get_bit_size(type);
210 nir_load_const_instr *load =
211 nir_load_const_instr_create(b->shader, num_components, bit_size);
212
213 memcpy(load->value, constant->values,
214 sizeof(nir_const_value) * num_components);
215
216 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
217 val->def = &load->def;
218 } else {
219 unsigned elems = glsl_get_length(val->type);
220 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
221 if (glsl_type_is_array_or_matrix(type)) {
222 const struct glsl_type *elem_type = glsl_get_array_element(type);
223 for (unsigned i = 0; i < elems; i++) {
224 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
225 elem_type);
226 }
227 } else {
228 vtn_assert(glsl_type_is_struct_or_ifc(type));
229 for (unsigned i = 0; i < elems; i++) {
230 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
231 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
232 elem_type);
233 }
234 }
235 }
236
237 return val;
238 }
239
240 struct vtn_ssa_value *
241 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
242 {
243 struct vtn_value *val = vtn_untyped_value(b, value_id);
244 switch (val->value_type) {
245 case vtn_value_type_undef:
246 return vtn_undef_ssa_value(b, val->type->type);
247
248 case vtn_value_type_constant:
249 return vtn_const_ssa_value(b, val->constant, val->type->type);
250
251 case vtn_value_type_ssa:
252 return val->ssa;
253
254 case vtn_value_type_pointer:
255 vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
256 struct vtn_ssa_value *ssa =
257 vtn_create_ssa_value(b, val->pointer->ptr_type->type);
258 ssa->def = vtn_pointer_to_ssa(b, val->pointer);
259 return ssa;
260
261 default:
262 vtn_fail("Invalid type for an SSA value");
263 }
264 }
265
266 struct vtn_value *
267 vtn_push_ssa_value(struct vtn_builder *b, uint32_t value_id,
268 struct vtn_ssa_value *ssa)
269 {
270 struct vtn_type *type = vtn_get_value_type(b, value_id);
271
272 /* See vtn_create_ssa_value */
273 vtn_fail_if(ssa->type != glsl_get_bare_type(type->type),
274 "Type mismatch for SPIR-V SSA value");
275
276 struct vtn_value *val;
277 if (type->base_type == vtn_base_type_pointer) {
278 val = vtn_push_pointer(b, value_id, vtn_pointer_from_ssa(b, ssa->def, type));
279 } else {
280 /* Don't trip the value_type_ssa check in vtn_push_value */
281 val = vtn_push_value(b, value_id, vtn_value_type_invalid);
282 val->value_type = vtn_value_type_ssa;
283 val->ssa = ssa;
284 }
285
286 return val;
287 }
288
289 nir_ssa_def *
290 vtn_get_nir_ssa(struct vtn_builder *b, uint32_t value_id)
291 {
292 struct vtn_ssa_value *ssa = vtn_ssa_value(b, value_id);
293 vtn_fail_if(!glsl_type_is_vector_or_scalar(ssa->type),
294 "Expected a vector or scalar type");
295 return ssa->def;
296 }
297
298 struct vtn_value *
299 vtn_push_nir_ssa(struct vtn_builder *b, uint32_t value_id, nir_ssa_def *def)
300 {
301 /* Types for all SPIR-V SSA values are set as part of a pre-pass so the
302 * type will be valid by the time we get here.
303 */
304 struct vtn_type *type = vtn_get_value_type(b, value_id);
305 vtn_fail_if(def->num_components != glsl_get_vector_elements(type->type) ||
306 def->bit_size != glsl_get_bit_size(type->type),
307 "Mismatch between NIR and SPIR-V type.");
308 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, type->type);
309 ssa->def = def;
310 return vtn_push_ssa_value(b, value_id, ssa);
311 }
312
313 static nir_deref_instr *
314 vtn_get_image(struct vtn_builder *b, uint32_t value_id)
315 {
316 struct vtn_type *type = vtn_get_value_type(b, value_id);
317 vtn_assert(type->base_type == vtn_base_type_image);
318 return nir_build_deref_cast(&b->nb, vtn_get_nir_ssa(b, value_id),
319 nir_var_uniform, type->glsl_image, 0);
320 }
321
322 static void
323 vtn_push_image(struct vtn_builder *b, uint32_t value_id,
324 nir_deref_instr *deref)
325 {
326 struct vtn_type *type = vtn_get_value_type(b, value_id);
327 vtn_assert(type->base_type == vtn_base_type_image);
328 vtn_push_nir_ssa(b, value_id, &deref->dest.ssa);
329 }
330
331 static nir_deref_instr *
332 vtn_get_sampler(struct vtn_builder *b, uint32_t value_id)
333 {
334 struct vtn_type *type = vtn_get_value_type(b, value_id);
335 vtn_assert(type->base_type == vtn_base_type_sampler);
336 return nir_build_deref_cast(&b->nb, vtn_get_nir_ssa(b, value_id),
337 nir_var_uniform, glsl_bare_sampler_type(), 0);
338 }
339
340 nir_ssa_def *
341 vtn_sampled_image_to_nir_ssa(struct vtn_builder *b,
342 struct vtn_sampled_image si)
343 {
344 return nir_vec2(&b->nb, &si.image->dest.ssa, &si.sampler->dest.ssa);
345 }
346
347 static void
348 vtn_push_sampled_image(struct vtn_builder *b, uint32_t value_id,
349 struct vtn_sampled_image si)
350 {
351 struct vtn_type *type = vtn_get_value_type(b, value_id);
352 vtn_assert(type->base_type == vtn_base_type_sampled_image);
353 vtn_push_nir_ssa(b, value_id, vtn_sampled_image_to_nir_ssa(b, si));
354 }
355
356 static struct vtn_sampled_image
357 vtn_get_sampled_image(struct vtn_builder *b, uint32_t value_id)
358 {
359 struct vtn_type *type = vtn_get_value_type(b, value_id);
360 vtn_assert(type->base_type == vtn_base_type_sampled_image);
361 nir_ssa_def *si_vec2 = vtn_get_nir_ssa(b, value_id);
362
363 struct vtn_sampled_image si = { NULL, };
364 si.image = nir_build_deref_cast(&b->nb, nir_channel(&b->nb, si_vec2, 0),
365 nir_var_uniform,
366 type->image->glsl_image, 0);
367 si.sampler = nir_build_deref_cast(&b->nb, nir_channel(&b->nb, si_vec2, 1),
368 nir_var_uniform,
369 glsl_bare_sampler_type(), 0);
370 return si;
371 }
372
373 static char *
374 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
375 unsigned word_count, unsigned *words_used)
376 {
377 char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
378 if (words_used) {
379 /* Ammount of space taken by the string (including the null) */
380 unsigned len = strlen(dup) + 1;
381 *words_used = DIV_ROUND_UP(len, sizeof(*words));
382 }
383 return dup;
384 }
385
386 const uint32_t *
387 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
388 const uint32_t *end, vtn_instruction_handler handler)
389 {
390 b->file = NULL;
391 b->line = -1;
392 b->col = -1;
393
394 const uint32_t *w = start;
395 while (w < end) {
396 SpvOp opcode = w[0] & SpvOpCodeMask;
397 unsigned count = w[0] >> SpvWordCountShift;
398 vtn_assert(count >= 1 && w + count <= end);
399
400 b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
401
402 switch (opcode) {
403 case SpvOpNop:
404 break; /* Do nothing */
405
406 case SpvOpLine:
407 b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
408 b->line = w[2];
409 b->col = w[3];
410 break;
411
412 case SpvOpNoLine:
413 b->file = NULL;
414 b->line = -1;
415 b->col = -1;
416 break;
417
418 default:
419 if (!handler(b, opcode, w, count))
420 return w;
421 break;
422 }
423
424 w += count;
425 }
426
427 b->spirv_offset = 0;
428 b->file = NULL;
429 b->line = -1;
430 b->col = -1;
431
432 assert(w == end);
433 return w;
434 }
435
436 static bool
437 vtn_handle_non_semantic_instruction(struct vtn_builder *b, SpvOp ext_opcode,
438 const uint32_t *w, unsigned count)
439 {
440 /* Do nothing. */
441 return true;
442 }
443
444 static void
445 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
446 const uint32_t *w, unsigned count)
447 {
448 const char *ext = (const char *)&w[2];
449 switch (opcode) {
450 case SpvOpExtInstImport: {
451 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
452 if (strcmp(ext, "GLSL.std.450") == 0) {
453 val->ext_handler = vtn_handle_glsl450_instruction;
454 } else if ((strcmp(ext, "SPV_AMD_gcn_shader") == 0)
455 && (b->options && b->options->caps.amd_gcn_shader)) {
456 val->ext_handler = vtn_handle_amd_gcn_shader_instruction;
457 } else if ((strcmp(ext, "SPV_AMD_shader_ballot") == 0)
458 && (b->options && b->options->caps.amd_shader_ballot)) {
459 val->ext_handler = vtn_handle_amd_shader_ballot_instruction;
460 } else if ((strcmp(ext, "SPV_AMD_shader_trinary_minmax") == 0)
461 && (b->options && b->options->caps.amd_trinary_minmax)) {
462 val->ext_handler = vtn_handle_amd_shader_trinary_minmax_instruction;
463 } else if ((strcmp(ext, "SPV_AMD_shader_explicit_vertex_parameter") == 0)
464 && (b->options && b->options->caps.amd_shader_explicit_vertex_parameter)) {
465 val->ext_handler = vtn_handle_amd_shader_explicit_vertex_parameter_instruction;
466 } else if (strcmp(ext, "OpenCL.std") == 0) {
467 val->ext_handler = vtn_handle_opencl_instruction;
468 } else if (strstr(ext, "NonSemantic.") == ext) {
469 val->ext_handler = vtn_handle_non_semantic_instruction;
470 } else {
471 vtn_fail("Unsupported extension: %s", ext);
472 }
473 break;
474 }
475
476 case SpvOpExtInst: {
477 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
478 bool handled = val->ext_handler(b, w[4], w, count);
479 vtn_assert(handled);
480 break;
481 }
482
483 default:
484 vtn_fail_with_opcode("Unhandled opcode", opcode);
485 }
486 }
487
488 static void
489 _foreach_decoration_helper(struct vtn_builder *b,
490 struct vtn_value *base_value,
491 int parent_member,
492 struct vtn_value *value,
493 vtn_decoration_foreach_cb cb, void *data)
494 {
495 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
496 int member;
497 if (dec->scope == VTN_DEC_DECORATION) {
498 member = parent_member;
499 } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
500 vtn_fail_if(value->value_type != vtn_value_type_type ||
501 value->type->base_type != vtn_base_type_struct,
502 "OpMemberDecorate and OpGroupMemberDecorate are only "
503 "allowed on OpTypeStruct");
504 /* This means we haven't recursed yet */
505 assert(value == base_value);
506
507 member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
508
509 vtn_fail_if(member >= base_value->type->length,
510 "OpMemberDecorate specifies member %d but the "
511 "OpTypeStruct has only %u members",
512 member, base_value->type->length);
513 } else {
514 /* Not a decoration */
515 assert(dec->scope == VTN_DEC_EXECUTION_MODE);
516 continue;
517 }
518
519 if (dec->group) {
520 assert(dec->group->value_type == vtn_value_type_decoration_group);
521 _foreach_decoration_helper(b, base_value, member, dec->group,
522 cb, data);
523 } else {
524 cb(b, base_value, member, dec, data);
525 }
526 }
527 }
528
529 /** Iterates (recursively if needed) over all of the decorations on a value
530 *
531 * This function iterates over all of the decorations applied to a given
532 * value. If it encounters a decoration group, it recurses into the group
533 * and iterates over all of those decorations as well.
534 */
535 void
536 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
537 vtn_decoration_foreach_cb cb, void *data)
538 {
539 _foreach_decoration_helper(b, value, -1, value, cb, data);
540 }
541
542 void
543 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
544 vtn_execution_mode_foreach_cb cb, void *data)
545 {
546 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
547 if (dec->scope != VTN_DEC_EXECUTION_MODE)
548 continue;
549
550 assert(dec->group == NULL);
551 cb(b, value, dec, data);
552 }
553 }
554
555 void
556 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
557 const uint32_t *w, unsigned count)
558 {
559 const uint32_t *w_end = w + count;
560 const uint32_t target = w[1];
561 w += 2;
562
563 switch (opcode) {
564 case SpvOpDecorationGroup:
565 vtn_push_value(b, target, vtn_value_type_decoration_group);
566 break;
567
568 case SpvOpDecorate:
569 case SpvOpDecorateId:
570 case SpvOpMemberDecorate:
571 case SpvOpDecorateString:
572 case SpvOpMemberDecorateString:
573 case SpvOpExecutionMode:
574 case SpvOpExecutionModeId: {
575 struct vtn_value *val = vtn_untyped_value(b, target);
576
577 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
578 switch (opcode) {
579 case SpvOpDecorate:
580 case SpvOpDecorateId:
581 case SpvOpDecorateString:
582 dec->scope = VTN_DEC_DECORATION;
583 break;
584 case SpvOpMemberDecorate:
585 case SpvOpMemberDecorateString:
586 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(w++);
587 vtn_fail_if(dec->scope < VTN_DEC_STRUCT_MEMBER0, /* overflow */
588 "Member argument of OpMemberDecorate too large");
589 break;
590 case SpvOpExecutionMode:
591 case SpvOpExecutionModeId:
592 dec->scope = VTN_DEC_EXECUTION_MODE;
593 break;
594 default:
595 unreachable("Invalid decoration opcode");
596 }
597 dec->decoration = *(w++);
598 dec->operands = w;
599
600 /* Link into the list */
601 dec->next = val->decoration;
602 val->decoration = dec;
603 break;
604 }
605
606 case SpvOpGroupMemberDecorate:
607 case SpvOpGroupDecorate: {
608 struct vtn_value *group =
609 vtn_value(b, target, vtn_value_type_decoration_group);
610
611 for (; w < w_end; w++) {
612 struct vtn_value *val = vtn_untyped_value(b, *w);
613 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
614
615 dec->group = group;
616 if (opcode == SpvOpGroupDecorate) {
617 dec->scope = VTN_DEC_DECORATION;
618 } else {
619 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
620 vtn_fail_if(dec->scope < 0, /* Check for overflow */
621 "Member argument of OpGroupMemberDecorate too large");
622 }
623
624 /* Link into the list */
625 dec->next = val->decoration;
626 val->decoration = dec;
627 }
628 break;
629 }
630
631 default:
632 unreachable("Unhandled opcode");
633 }
634 }
635
636 struct member_decoration_ctx {
637 unsigned num_fields;
638 struct glsl_struct_field *fields;
639 struct vtn_type *type;
640 };
641
642 /**
643 * Returns true if the given type contains a struct decorated Block or
644 * BufferBlock
645 */
646 bool
647 vtn_type_contains_block(struct vtn_builder *b, struct vtn_type *type)
648 {
649 switch (type->base_type) {
650 case vtn_base_type_array:
651 return vtn_type_contains_block(b, type->array_element);
652 case vtn_base_type_struct:
653 if (type->block || type->buffer_block)
654 return true;
655 for (unsigned i = 0; i < type->length; i++) {
656 if (vtn_type_contains_block(b, type->members[i]))
657 return true;
658 }
659 return false;
660 default:
661 return false;
662 }
663 }
664
665 /** Returns true if two types are "compatible", i.e. you can do an OpLoad,
666 * OpStore, or OpCopyMemory between them without breaking anything.
667 * Technically, the SPIR-V rules require the exact same type ID but this lets
668 * us internally be a bit looser.
669 */
670 bool
671 vtn_types_compatible(struct vtn_builder *b,
672 struct vtn_type *t1, struct vtn_type *t2)
673 {
674 if (t1->id == t2->id)
675 return true;
676
677 if (t1->base_type != t2->base_type)
678 return false;
679
680 switch (t1->base_type) {
681 case vtn_base_type_void:
682 case vtn_base_type_scalar:
683 case vtn_base_type_vector:
684 case vtn_base_type_matrix:
685 case vtn_base_type_image:
686 case vtn_base_type_sampler:
687 case vtn_base_type_sampled_image:
688 return t1->type == t2->type;
689
690 case vtn_base_type_array:
691 return t1->length == t2->length &&
692 vtn_types_compatible(b, t1->array_element, t2->array_element);
693
694 case vtn_base_type_pointer:
695 return vtn_types_compatible(b, t1->deref, t2->deref);
696
697 case vtn_base_type_struct:
698 if (t1->length != t2->length)
699 return false;
700
701 for (unsigned i = 0; i < t1->length; i++) {
702 if (!vtn_types_compatible(b, t1->members[i], t2->members[i]))
703 return false;
704 }
705 return true;
706
707 case vtn_base_type_function:
708 /* This case shouldn't get hit since you can't copy around function
709 * types. Just require them to be identical.
710 */
711 return false;
712 }
713
714 vtn_fail("Invalid base type");
715 }
716
717 struct vtn_type *
718 vtn_type_without_array(struct vtn_type *type)
719 {
720 while (type->base_type == vtn_base_type_array)
721 type = type->array_element;
722 return type;
723 }
724
725 /* does a shallow copy of a vtn_type */
726
727 static struct vtn_type *
728 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
729 {
730 struct vtn_type *dest = ralloc(b, struct vtn_type);
731 *dest = *src;
732
733 switch (src->base_type) {
734 case vtn_base_type_void:
735 case vtn_base_type_scalar:
736 case vtn_base_type_vector:
737 case vtn_base_type_matrix:
738 case vtn_base_type_array:
739 case vtn_base_type_pointer:
740 case vtn_base_type_image:
741 case vtn_base_type_sampler:
742 case vtn_base_type_sampled_image:
743 /* Nothing more to do */
744 break;
745
746 case vtn_base_type_struct:
747 dest->members = ralloc_array(b, struct vtn_type *, src->length);
748 memcpy(dest->members, src->members,
749 src->length * sizeof(src->members[0]));
750
751 dest->offsets = ralloc_array(b, unsigned, src->length);
752 memcpy(dest->offsets, src->offsets,
753 src->length * sizeof(src->offsets[0]));
754 break;
755
756 case vtn_base_type_function:
757 dest->params = ralloc_array(b, struct vtn_type *, src->length);
758 memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
759 break;
760 }
761
762 return dest;
763 }
764
765 static const struct glsl_type *
766 wrap_type_in_array(const struct glsl_type *type,
767 const struct glsl_type *array_type)
768 {
769 if (!glsl_type_is_array(array_type))
770 return type;
771
772 const struct glsl_type *elem_type =
773 wrap_type_in_array(type, glsl_get_array_element(array_type));
774 return glsl_array_type(elem_type, glsl_get_length(array_type),
775 glsl_get_explicit_stride(array_type));
776 }
777
778 static bool
779 vtn_type_needs_explicit_layout(struct vtn_builder *b, enum vtn_variable_mode mode)
780 {
781 /* For OpenCL we never want to strip the info from the types, and it makes
782 * type comparisons easier in later stages.
783 */
784 if (b->options->environment == NIR_SPIRV_OPENCL)
785 return true;
786
787 switch (mode) {
788 case vtn_variable_mode_input:
789 case vtn_variable_mode_output:
790 /* Layout decorations kept because we need offsets for XFB arrays of
791 * blocks.
792 */
793 return b->shader->info.has_transform_feedback_varyings;
794
795 case vtn_variable_mode_ssbo:
796 case vtn_variable_mode_phys_ssbo:
797 case vtn_variable_mode_ubo:
798 return true;
799
800 default:
801 return false;
802 }
803 }
804
805 const struct glsl_type *
806 vtn_type_get_nir_type(struct vtn_builder *b, struct vtn_type *type,
807 enum vtn_variable_mode mode)
808 {
809 if (mode == vtn_variable_mode_atomic_counter) {
810 vtn_fail_if(glsl_without_array(type->type) != glsl_uint_type(),
811 "Variables in the AtomicCounter storage class should be "
812 "(possibly arrays of arrays of) uint.");
813 return wrap_type_in_array(glsl_atomic_uint_type(), type->type);
814 }
815
816 if (mode == vtn_variable_mode_uniform) {
817 switch (type->base_type) {
818 case vtn_base_type_array: {
819 const struct glsl_type *elem_type =
820 vtn_type_get_nir_type(b, type->array_element, mode);
821
822 return glsl_array_type(elem_type, type->length,
823 glsl_get_explicit_stride(type->type));
824 }
825
826 case vtn_base_type_struct: {
827 bool need_new_struct = false;
828 const uint32_t num_fields = type->length;
829 NIR_VLA(struct glsl_struct_field, fields, num_fields);
830 for (unsigned i = 0; i < num_fields; i++) {
831 fields[i] = *glsl_get_struct_field_data(type->type, i);
832 const struct glsl_type *field_nir_type =
833 vtn_type_get_nir_type(b, type->members[i], mode);
834 if (fields[i].type != field_nir_type) {
835 fields[i].type = field_nir_type;
836 need_new_struct = true;
837 }
838 }
839 if (need_new_struct) {
840 if (glsl_type_is_interface(type->type)) {
841 return glsl_interface_type(fields, num_fields,
842 /* packing */ 0, false,
843 glsl_get_type_name(type->type));
844 } else {
845 return glsl_struct_type(fields, num_fields,
846 glsl_get_type_name(type->type),
847 glsl_struct_type_is_packed(type->type));
848 }
849 } else {
850 /* No changes, just pass it on */
851 return type->type;
852 }
853 }
854
855 case vtn_base_type_image:
856 return type->glsl_image;
857
858 case vtn_base_type_sampler:
859 return glsl_bare_sampler_type();
860
861 case vtn_base_type_sampled_image:
862 return type->image->glsl_image;
863
864 default:
865 return type->type;
866 }
867 }
868
869 /* Layout decorations are allowed but ignored in certain conditions,
870 * to allow SPIR-V generators perform type deduplication. Discard
871 * unnecessary ones when passing to NIR.
872 */
873 if (!vtn_type_needs_explicit_layout(b, mode))
874 return glsl_get_bare_type(type->type);
875
876 return type->type;
877 }
878
879 static struct vtn_type *
880 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
881 {
882 type->members[member] = vtn_type_copy(b, type->members[member]);
883 type = type->members[member];
884
885 /* We may have an array of matrices.... Oh, joy! */
886 while (glsl_type_is_array(type->type)) {
887 type->array_element = vtn_type_copy(b, type->array_element);
888 type = type->array_element;
889 }
890
891 vtn_assert(glsl_type_is_matrix(type->type));
892
893 return type;
894 }
895
896 static void
897 vtn_handle_access_qualifier(struct vtn_builder *b, struct vtn_type *type,
898 int member, enum gl_access_qualifier access)
899 {
900 type->members[member] = vtn_type_copy(b, type->members[member]);
901 type = type->members[member];
902
903 type->access |= access;
904 }
905
906 static void
907 array_stride_decoration_cb(struct vtn_builder *b,
908 struct vtn_value *val, int member,
909 const struct vtn_decoration *dec, void *void_ctx)
910 {
911 struct vtn_type *type = val->type;
912
913 if (dec->decoration == SpvDecorationArrayStride) {
914 if (vtn_type_contains_block(b, type)) {
915 vtn_warn("The ArrayStride decoration cannot be applied to an array "
916 "type which contains a structure type decorated Block "
917 "or BufferBlock");
918 /* Ignore the decoration */
919 } else {
920 vtn_fail_if(dec->operands[0] == 0, "ArrayStride must be non-zero");
921 type->stride = dec->operands[0];
922 }
923 }
924 }
925
926 static void
927 struct_member_decoration_cb(struct vtn_builder *b,
928 UNUSED struct vtn_value *val, int member,
929 const struct vtn_decoration *dec, void *void_ctx)
930 {
931 struct member_decoration_ctx *ctx = void_ctx;
932
933 if (member < 0)
934 return;
935
936 assert(member < ctx->num_fields);
937
938 switch (dec->decoration) {
939 case SpvDecorationRelaxedPrecision:
940 case SpvDecorationUniform:
941 case SpvDecorationUniformId:
942 break; /* FIXME: Do nothing with this for now. */
943 case SpvDecorationNonWritable:
944 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_WRITEABLE);
945 break;
946 case SpvDecorationNonReadable:
947 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_READABLE);
948 break;
949 case SpvDecorationVolatile:
950 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_VOLATILE);
951 break;
952 case SpvDecorationCoherent:
953 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_COHERENT);
954 break;
955 case SpvDecorationNoPerspective:
956 ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
957 break;
958 case SpvDecorationFlat:
959 ctx->fields[member].interpolation = INTERP_MODE_FLAT;
960 break;
961 case SpvDecorationExplicitInterpAMD:
962 ctx->fields[member].interpolation = INTERP_MODE_EXPLICIT;
963 break;
964 case SpvDecorationCentroid:
965 ctx->fields[member].centroid = true;
966 break;
967 case SpvDecorationSample:
968 ctx->fields[member].sample = true;
969 break;
970 case SpvDecorationStream:
971 /* This is handled later by var_decoration_cb in vtn_variables.c */
972 break;
973 case SpvDecorationLocation:
974 ctx->fields[member].location = dec->operands[0];
975 break;
976 case SpvDecorationComponent:
977 break; /* FIXME: What should we do with these? */
978 case SpvDecorationBuiltIn:
979 ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
980 ctx->type->members[member]->is_builtin = true;
981 ctx->type->members[member]->builtin = dec->operands[0];
982 ctx->type->builtin_block = true;
983 break;
984 case SpvDecorationOffset:
985 ctx->type->offsets[member] = dec->operands[0];
986 ctx->fields[member].offset = dec->operands[0];
987 break;
988 case SpvDecorationMatrixStride:
989 /* Handled as a second pass */
990 break;
991 case SpvDecorationColMajor:
992 break; /* Nothing to do here. Column-major is the default. */
993 case SpvDecorationRowMajor:
994 mutable_matrix_member(b, ctx->type, member)->row_major = true;
995 break;
996
997 case SpvDecorationPatch:
998 break;
999
1000 case SpvDecorationSpecId:
1001 case SpvDecorationBlock:
1002 case SpvDecorationBufferBlock:
1003 case SpvDecorationArrayStride:
1004 case SpvDecorationGLSLShared:
1005 case SpvDecorationGLSLPacked:
1006 case SpvDecorationInvariant:
1007 case SpvDecorationRestrict:
1008 case SpvDecorationAliased:
1009 case SpvDecorationConstant:
1010 case SpvDecorationIndex:
1011 case SpvDecorationBinding:
1012 case SpvDecorationDescriptorSet:
1013 case SpvDecorationLinkageAttributes:
1014 case SpvDecorationNoContraction:
1015 case SpvDecorationInputAttachmentIndex:
1016 vtn_warn("Decoration not allowed on struct members: %s",
1017 spirv_decoration_to_string(dec->decoration));
1018 break;
1019
1020 case SpvDecorationXfbBuffer:
1021 case SpvDecorationXfbStride:
1022 /* This is handled later by var_decoration_cb in vtn_variables.c */
1023 break;
1024
1025 case SpvDecorationCPacked:
1026 if (b->shader->info.stage != MESA_SHADER_KERNEL)
1027 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1028 spirv_decoration_to_string(dec->decoration));
1029 else
1030 ctx->type->packed = true;
1031 break;
1032
1033 case SpvDecorationSaturatedConversion:
1034 case SpvDecorationFuncParamAttr:
1035 case SpvDecorationFPRoundingMode:
1036 case SpvDecorationFPFastMathMode:
1037 case SpvDecorationAlignment:
1038 if (b->shader->info.stage != MESA_SHADER_KERNEL) {
1039 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1040 spirv_decoration_to_string(dec->decoration));
1041 }
1042 break;
1043
1044 case SpvDecorationUserSemantic:
1045 case SpvDecorationUserTypeGOOGLE:
1046 /* User semantic decorations can safely be ignored by the driver. */
1047 break;
1048
1049 default:
1050 vtn_fail_with_decoration("Unhandled decoration", dec->decoration);
1051 }
1052 }
1053
1054 /** Chases the array type all the way down to the tail and rewrites the
1055 * glsl_types to be based off the tail's glsl_type.
1056 */
1057 static void
1058 vtn_array_type_rewrite_glsl_type(struct vtn_type *type)
1059 {
1060 if (type->base_type != vtn_base_type_array)
1061 return;
1062
1063 vtn_array_type_rewrite_glsl_type(type->array_element);
1064
1065 type->type = glsl_array_type(type->array_element->type,
1066 type->length, type->stride);
1067 }
1068
1069 /* Matrix strides are handled as a separate pass because we need to know
1070 * whether the matrix is row-major or not first.
1071 */
1072 static void
1073 struct_member_matrix_stride_cb(struct vtn_builder *b,
1074 UNUSED struct vtn_value *val, int member,
1075 const struct vtn_decoration *dec,
1076 void *void_ctx)
1077 {
1078 if (dec->decoration != SpvDecorationMatrixStride)
1079 return;
1080
1081 vtn_fail_if(member < 0,
1082 "The MatrixStride decoration is only allowed on members "
1083 "of OpTypeStruct");
1084 vtn_fail_if(dec->operands[0] == 0, "MatrixStride must be non-zero");
1085
1086 struct member_decoration_ctx *ctx = void_ctx;
1087
1088 struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
1089 if (mat_type->row_major) {
1090 mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
1091 mat_type->stride = mat_type->array_element->stride;
1092 mat_type->array_element->stride = dec->operands[0];
1093
1094 mat_type->type = glsl_explicit_matrix_type(mat_type->type,
1095 dec->operands[0], true);
1096 mat_type->array_element->type = glsl_get_column_type(mat_type->type);
1097 } else {
1098 vtn_assert(mat_type->array_element->stride > 0);
1099 mat_type->stride = dec->operands[0];
1100
1101 mat_type->type = glsl_explicit_matrix_type(mat_type->type,
1102 dec->operands[0], false);
1103 }
1104
1105 /* Now that we've replaced the glsl_type with a properly strided matrix
1106 * type, rewrite the member type so that it's an array of the proper kind
1107 * of glsl_type.
1108 */
1109 vtn_array_type_rewrite_glsl_type(ctx->type->members[member]);
1110 ctx->fields[member].type = ctx->type->members[member]->type;
1111 }
1112
1113 static void
1114 struct_block_decoration_cb(struct vtn_builder *b,
1115 struct vtn_value *val, int member,
1116 const struct vtn_decoration *dec, void *ctx)
1117 {
1118 if (member != -1)
1119 return;
1120
1121 struct vtn_type *type = val->type;
1122 if (dec->decoration == SpvDecorationBlock)
1123 type->block = true;
1124 else if (dec->decoration == SpvDecorationBufferBlock)
1125 type->buffer_block = true;
1126 }
1127
1128 static void
1129 type_decoration_cb(struct vtn_builder *b,
1130 struct vtn_value *val, int member,
1131 const struct vtn_decoration *dec, UNUSED void *ctx)
1132 {
1133 struct vtn_type *type = val->type;
1134
1135 if (member != -1) {
1136 /* This should have been handled by OpTypeStruct */
1137 assert(val->type->base_type == vtn_base_type_struct);
1138 assert(member >= 0 && member < val->type->length);
1139 return;
1140 }
1141
1142 switch (dec->decoration) {
1143 case SpvDecorationArrayStride:
1144 vtn_assert(type->base_type == vtn_base_type_array ||
1145 type->base_type == vtn_base_type_pointer);
1146 break;
1147 case SpvDecorationBlock:
1148 vtn_assert(type->base_type == vtn_base_type_struct);
1149 vtn_assert(type->block);
1150 break;
1151 case SpvDecorationBufferBlock:
1152 vtn_assert(type->base_type == vtn_base_type_struct);
1153 vtn_assert(type->buffer_block);
1154 break;
1155 case SpvDecorationGLSLShared:
1156 case SpvDecorationGLSLPacked:
1157 /* Ignore these, since we get explicit offsets anyways */
1158 break;
1159
1160 case SpvDecorationRowMajor:
1161 case SpvDecorationColMajor:
1162 case SpvDecorationMatrixStride:
1163 case SpvDecorationBuiltIn:
1164 case SpvDecorationNoPerspective:
1165 case SpvDecorationFlat:
1166 case SpvDecorationPatch:
1167 case SpvDecorationCentroid:
1168 case SpvDecorationSample:
1169 case SpvDecorationExplicitInterpAMD:
1170 case SpvDecorationVolatile:
1171 case SpvDecorationCoherent:
1172 case SpvDecorationNonWritable:
1173 case SpvDecorationNonReadable:
1174 case SpvDecorationUniform:
1175 case SpvDecorationUniformId:
1176 case SpvDecorationLocation:
1177 case SpvDecorationComponent:
1178 case SpvDecorationOffset:
1179 case SpvDecorationXfbBuffer:
1180 case SpvDecorationXfbStride:
1181 case SpvDecorationUserSemantic:
1182 vtn_warn("Decoration only allowed for struct members: %s",
1183 spirv_decoration_to_string(dec->decoration));
1184 break;
1185
1186 case SpvDecorationStream:
1187 /* We don't need to do anything here, as stream is filled up when
1188 * aplying the decoration to a variable, just check that if it is not a
1189 * struct member, it should be a struct.
1190 */
1191 vtn_assert(type->base_type == vtn_base_type_struct);
1192 break;
1193
1194 case SpvDecorationRelaxedPrecision:
1195 case SpvDecorationSpecId:
1196 case SpvDecorationInvariant:
1197 case SpvDecorationRestrict:
1198 case SpvDecorationAliased:
1199 case SpvDecorationConstant:
1200 case SpvDecorationIndex:
1201 case SpvDecorationBinding:
1202 case SpvDecorationDescriptorSet:
1203 case SpvDecorationLinkageAttributes:
1204 case SpvDecorationNoContraction:
1205 case SpvDecorationInputAttachmentIndex:
1206 vtn_warn("Decoration not allowed on types: %s",
1207 spirv_decoration_to_string(dec->decoration));
1208 break;
1209
1210 case SpvDecorationCPacked:
1211 if (b->shader->info.stage != MESA_SHADER_KERNEL)
1212 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1213 spirv_decoration_to_string(dec->decoration));
1214 else
1215 type->packed = true;
1216 break;
1217
1218 case SpvDecorationSaturatedConversion:
1219 case SpvDecorationFuncParamAttr:
1220 case SpvDecorationFPRoundingMode:
1221 case SpvDecorationFPFastMathMode:
1222 case SpvDecorationAlignment:
1223 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1224 spirv_decoration_to_string(dec->decoration));
1225 break;
1226
1227 case SpvDecorationUserTypeGOOGLE:
1228 /* User semantic decorations can safely be ignored by the driver. */
1229 break;
1230
1231 default:
1232 vtn_fail_with_decoration("Unhandled decoration", dec->decoration);
1233 }
1234 }
1235
1236 static unsigned
1237 translate_image_format(struct vtn_builder *b, SpvImageFormat format)
1238 {
1239 switch (format) {
1240 case SpvImageFormatUnknown: return PIPE_FORMAT_NONE;
1241 case SpvImageFormatRgba32f: return PIPE_FORMAT_R32G32B32A32_FLOAT;
1242 case SpvImageFormatRgba16f: return PIPE_FORMAT_R16G16B16A16_FLOAT;
1243 case SpvImageFormatR32f: return PIPE_FORMAT_R32_FLOAT;
1244 case SpvImageFormatRgba8: return PIPE_FORMAT_R8G8B8A8_UNORM;
1245 case SpvImageFormatRgba8Snorm: return PIPE_FORMAT_R8G8B8A8_SNORM;
1246 case SpvImageFormatRg32f: return PIPE_FORMAT_R32G32_FLOAT;
1247 case SpvImageFormatRg16f: return PIPE_FORMAT_R16G16_FLOAT;
1248 case SpvImageFormatR11fG11fB10f: return PIPE_FORMAT_R11G11B10_FLOAT;
1249 case SpvImageFormatR16f: return PIPE_FORMAT_R16_FLOAT;
1250 case SpvImageFormatRgba16: return PIPE_FORMAT_R16G16B16A16_UNORM;
1251 case SpvImageFormatRgb10A2: return PIPE_FORMAT_R10G10B10A2_UNORM;
1252 case SpvImageFormatRg16: return PIPE_FORMAT_R16G16_UNORM;
1253 case SpvImageFormatRg8: return PIPE_FORMAT_R8G8_UNORM;
1254 case SpvImageFormatR16: return PIPE_FORMAT_R16_UNORM;
1255 case SpvImageFormatR8: return PIPE_FORMAT_R8_UNORM;
1256 case SpvImageFormatRgba16Snorm: return PIPE_FORMAT_R16G16B16A16_SNORM;
1257 case SpvImageFormatRg16Snorm: return PIPE_FORMAT_R16G16_SNORM;
1258 case SpvImageFormatRg8Snorm: return PIPE_FORMAT_R8G8_SNORM;
1259 case SpvImageFormatR16Snorm: return PIPE_FORMAT_R16_SNORM;
1260 case SpvImageFormatR8Snorm: return PIPE_FORMAT_R8_SNORM;
1261 case SpvImageFormatRgba32i: return PIPE_FORMAT_R32G32B32A32_SINT;
1262 case SpvImageFormatRgba16i: return PIPE_FORMAT_R16G16B16A16_SINT;
1263 case SpvImageFormatRgba8i: return PIPE_FORMAT_R8G8B8A8_SINT;
1264 case SpvImageFormatR32i: return PIPE_FORMAT_R32_SINT;
1265 case SpvImageFormatRg32i: return PIPE_FORMAT_R32G32_SINT;
1266 case SpvImageFormatRg16i: return PIPE_FORMAT_R16G16_SINT;
1267 case SpvImageFormatRg8i: return PIPE_FORMAT_R8G8_SINT;
1268 case SpvImageFormatR16i: return PIPE_FORMAT_R16_SINT;
1269 case SpvImageFormatR8i: return PIPE_FORMAT_R8_SINT;
1270 case SpvImageFormatRgba32ui: return PIPE_FORMAT_R32G32B32A32_UINT;
1271 case SpvImageFormatRgba16ui: return PIPE_FORMAT_R16G16B16A16_UINT;
1272 case SpvImageFormatRgba8ui: return PIPE_FORMAT_R8G8B8A8_UINT;
1273 case SpvImageFormatR32ui: return PIPE_FORMAT_R32_UINT;
1274 case SpvImageFormatRgb10a2ui: return PIPE_FORMAT_R10G10B10A2_UINT;
1275 case SpvImageFormatRg32ui: return PIPE_FORMAT_R32G32_UINT;
1276 case SpvImageFormatRg16ui: return PIPE_FORMAT_R16G16_UINT;
1277 case SpvImageFormatRg8ui: return PIPE_FORMAT_R8G8_UINT;
1278 case SpvImageFormatR16ui: return PIPE_FORMAT_R16_UINT;
1279 case SpvImageFormatR8ui: return PIPE_FORMAT_R8_UINT;
1280 default:
1281 vtn_fail("Invalid image format: %s (%u)",
1282 spirv_imageformat_to_string(format), format);
1283 }
1284 }
1285
1286 static void
1287 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
1288 const uint32_t *w, unsigned count)
1289 {
1290 struct vtn_value *val = NULL;
1291
1292 /* In order to properly handle forward declarations, we have to defer
1293 * allocation for pointer types.
1294 */
1295 if (opcode != SpvOpTypePointer && opcode != SpvOpTypeForwardPointer) {
1296 val = vtn_push_value(b, w[1], vtn_value_type_type);
1297 vtn_fail_if(val->type != NULL,
1298 "Only pointers can have forward declarations");
1299 val->type = rzalloc(b, struct vtn_type);
1300 val->type->id = w[1];
1301 }
1302
1303 switch (opcode) {
1304 case SpvOpTypeVoid:
1305 val->type->base_type = vtn_base_type_void;
1306 val->type->type = glsl_void_type();
1307 break;
1308 case SpvOpTypeBool:
1309 val->type->base_type = vtn_base_type_scalar;
1310 val->type->type = glsl_bool_type();
1311 val->type->length = 1;
1312 break;
1313 case SpvOpTypeInt: {
1314 int bit_size = w[2];
1315 const bool signedness = w[3];
1316 val->type->base_type = vtn_base_type_scalar;
1317 switch (bit_size) {
1318 case 64:
1319 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1320 break;
1321 case 32:
1322 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1323 break;
1324 case 16:
1325 val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1326 break;
1327 case 8:
1328 val->type->type = (signedness ? glsl_int8_t_type() : glsl_uint8_t_type());
1329 break;
1330 default:
1331 vtn_fail("Invalid int bit size: %u", bit_size);
1332 }
1333 val->type->length = 1;
1334 break;
1335 }
1336
1337 case SpvOpTypeFloat: {
1338 int bit_size = w[2];
1339 val->type->base_type = vtn_base_type_scalar;
1340 switch (bit_size) {
1341 case 16:
1342 val->type->type = glsl_float16_t_type();
1343 break;
1344 case 32:
1345 val->type->type = glsl_float_type();
1346 break;
1347 case 64:
1348 val->type->type = glsl_double_type();
1349 break;
1350 default:
1351 vtn_fail("Invalid float bit size: %u", bit_size);
1352 }
1353 val->type->length = 1;
1354 break;
1355 }
1356
1357 case SpvOpTypeVector: {
1358 struct vtn_type *base = vtn_get_type(b, w[2]);
1359 unsigned elems = w[3];
1360
1361 vtn_fail_if(base->base_type != vtn_base_type_scalar,
1362 "Base type for OpTypeVector must be a scalar");
1363 vtn_fail_if((elems < 2 || elems > 4) && (elems != 8) && (elems != 16),
1364 "Invalid component count for OpTypeVector");
1365
1366 val->type->base_type = vtn_base_type_vector;
1367 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1368 val->type->length = elems;
1369 val->type->stride = glsl_type_is_boolean(val->type->type)
1370 ? 4 : glsl_get_bit_size(base->type) / 8;
1371 val->type->array_element = base;
1372 break;
1373 }
1374
1375 case SpvOpTypeMatrix: {
1376 struct vtn_type *base = vtn_get_type(b, w[2]);
1377 unsigned columns = w[3];
1378
1379 vtn_fail_if(base->base_type != vtn_base_type_vector,
1380 "Base type for OpTypeMatrix must be a vector");
1381 vtn_fail_if(columns < 2 || columns > 4,
1382 "Invalid column count for OpTypeMatrix");
1383
1384 val->type->base_type = vtn_base_type_matrix;
1385 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1386 glsl_get_vector_elements(base->type),
1387 columns);
1388 vtn_fail_if(glsl_type_is_error(val->type->type),
1389 "Unsupported base type for OpTypeMatrix");
1390 assert(!glsl_type_is_error(val->type->type));
1391 val->type->length = columns;
1392 val->type->array_element = base;
1393 val->type->row_major = false;
1394 val->type->stride = 0;
1395 break;
1396 }
1397
1398 case SpvOpTypeRuntimeArray:
1399 case SpvOpTypeArray: {
1400 struct vtn_type *array_element = vtn_get_type(b, w[2]);
1401
1402 if (opcode == SpvOpTypeRuntimeArray) {
1403 /* A length of 0 is used to denote unsized arrays */
1404 val->type->length = 0;
1405 } else {
1406 val->type->length = vtn_constant_uint(b, w[3]);
1407 }
1408
1409 val->type->base_type = vtn_base_type_array;
1410 val->type->array_element = array_element;
1411 if (b->shader->info.stage == MESA_SHADER_KERNEL)
1412 val->type->stride = glsl_get_cl_size(array_element->type);
1413
1414 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1415 val->type->type = glsl_array_type(array_element->type, val->type->length,
1416 val->type->stride);
1417 break;
1418 }
1419
1420 case SpvOpTypeStruct: {
1421 unsigned num_fields = count - 2;
1422 val->type->base_type = vtn_base_type_struct;
1423 val->type->length = num_fields;
1424 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1425 val->type->offsets = ralloc_array(b, unsigned, num_fields);
1426 val->type->packed = false;
1427
1428 NIR_VLA(struct glsl_struct_field, fields, count);
1429 for (unsigned i = 0; i < num_fields; i++) {
1430 val->type->members[i] = vtn_get_type(b, w[i + 2]);
1431 fields[i] = (struct glsl_struct_field) {
1432 .type = val->type->members[i]->type,
1433 .name = ralloc_asprintf(b, "field%d", i),
1434 .location = -1,
1435 .offset = -1,
1436 };
1437 }
1438
1439 if (b->shader->info.stage == MESA_SHADER_KERNEL) {
1440 unsigned offset = 0;
1441 for (unsigned i = 0; i < num_fields; i++) {
1442 offset = align(offset, glsl_get_cl_alignment(fields[i].type));
1443 fields[i].offset = offset;
1444 offset += glsl_get_cl_size(fields[i].type);
1445 }
1446 }
1447
1448 struct member_decoration_ctx ctx = {
1449 .num_fields = num_fields,
1450 .fields = fields,
1451 .type = val->type
1452 };
1453
1454 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1455 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1456
1457 vtn_foreach_decoration(b, val, struct_block_decoration_cb, NULL);
1458
1459 const char *name = val->name;
1460
1461 if (val->type->block || val->type->buffer_block) {
1462 /* Packing will be ignored since types coming from SPIR-V are
1463 * explicitly laid out.
1464 */
1465 val->type->type = glsl_interface_type(fields, num_fields,
1466 /* packing */ 0, false,
1467 name ? name : "block");
1468 } else {
1469 val->type->type = glsl_struct_type(fields, num_fields,
1470 name ? name : "struct", false);
1471 }
1472 break;
1473 }
1474
1475 case SpvOpTypeFunction: {
1476 val->type->base_type = vtn_base_type_function;
1477 val->type->type = NULL;
1478
1479 val->type->return_type = vtn_get_type(b, w[2]);
1480
1481 const unsigned num_params = count - 3;
1482 val->type->length = num_params;
1483 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1484 for (unsigned i = 0; i < count - 3; i++) {
1485 val->type->params[i] = vtn_get_type(b, w[i + 3]);
1486 }
1487 break;
1488 }
1489
1490 case SpvOpTypePointer:
1491 case SpvOpTypeForwardPointer: {
1492 /* We can't blindly push the value because it might be a forward
1493 * declaration.
1494 */
1495 val = vtn_untyped_value(b, w[1]);
1496
1497 SpvStorageClass storage_class = w[2];
1498
1499 if (val->value_type == vtn_value_type_invalid) {
1500 val->value_type = vtn_value_type_type;
1501 val->type = rzalloc(b, struct vtn_type);
1502 val->type->id = w[1];
1503 val->type->base_type = vtn_base_type_pointer;
1504 val->type->storage_class = storage_class;
1505
1506 /* These can actually be stored to nir_variables and used as SSA
1507 * values so they need a real glsl_type.
1508 */
1509 enum vtn_variable_mode mode = vtn_storage_class_to_mode(
1510 b, storage_class, NULL, NULL);
1511 val->type->type = nir_address_format_to_glsl_type(
1512 vtn_mode_to_address_format(b, mode));
1513 } else {
1514 vtn_fail_if(val->type->storage_class != storage_class,
1515 "The storage classes of an OpTypePointer and any "
1516 "OpTypeForwardPointers that provide forward "
1517 "declarations of it must match.");
1518 }
1519
1520 if (opcode == SpvOpTypePointer) {
1521 vtn_fail_if(val->type->deref != NULL,
1522 "While OpTypeForwardPointer can be used to provide a "
1523 "forward declaration of a pointer, OpTypePointer can "
1524 "only be used once for a given id.");
1525
1526 val->type->deref = vtn_get_type(b, w[3]);
1527
1528 /* Only certain storage classes use ArrayStride. The others (in
1529 * particular Workgroup) are expected to be laid out by the driver.
1530 */
1531 switch (storage_class) {
1532 case SpvStorageClassUniform:
1533 case SpvStorageClassPushConstant:
1534 case SpvStorageClassStorageBuffer:
1535 case SpvStorageClassPhysicalStorageBuffer:
1536 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1537 break;
1538 default:
1539 /* Nothing to do. */
1540 break;
1541 }
1542
1543 if (b->physical_ptrs) {
1544 switch (storage_class) {
1545 case SpvStorageClassFunction:
1546 case SpvStorageClassWorkgroup:
1547 case SpvStorageClassCrossWorkgroup:
1548 case SpvStorageClassUniformConstant:
1549 val->type->stride = align(glsl_get_cl_size(val->type->deref->type),
1550 glsl_get_cl_alignment(val->type->deref->type));
1551 break;
1552 default:
1553 break;
1554 }
1555 }
1556 }
1557 break;
1558 }
1559
1560 case SpvOpTypeImage: {
1561 val->type->base_type = vtn_base_type_image;
1562
1563 /* Images are represented in NIR as a scalar SSA value that is the
1564 * result of a deref instruction. An OpLoad on an OpTypeImage pointer
1565 * from UniformConstant memory just takes the NIR deref from the pointer
1566 * and turns it into an SSA value.
1567 */
1568 val->type->type = nir_address_format_to_glsl_type(
1569 vtn_mode_to_address_format(b, vtn_variable_mode_function));
1570
1571 const struct vtn_type *sampled_type = vtn_get_type(b, w[2]);
1572 if (b->shader->info.stage == MESA_SHADER_KERNEL) {
1573 vtn_fail_if(sampled_type->base_type != vtn_base_type_void,
1574 "Sampled type of OpTypeImage must be void for kernels");
1575 } else {
1576 vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1577 glsl_get_bit_size(sampled_type->type) != 32,
1578 "Sampled type of OpTypeImage must be a 32-bit scalar");
1579 }
1580
1581 enum glsl_sampler_dim dim;
1582 switch ((SpvDim)w[3]) {
1583 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
1584 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
1585 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
1586 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
1587 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
1588 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
1589 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1590 default:
1591 vtn_fail("Invalid SPIR-V image dimensionality: %s (%u)",
1592 spirv_dim_to_string((SpvDim)w[3]), w[3]);
1593 }
1594
1595 /* w[4]: as per Vulkan spec "Validation Rules within a Module",
1596 * The “Depth” operand of OpTypeImage is ignored.
1597 */
1598 bool is_array = w[5];
1599 bool multisampled = w[6];
1600 unsigned sampled = w[7];
1601 SpvImageFormat format = w[8];
1602
1603 if (count > 9)
1604 val->type->access_qualifier = w[9];
1605 else if (b->shader->info.stage == MESA_SHADER_KERNEL)
1606 /* Per the CL C spec: If no qualifier is provided, read_only is assumed. */
1607 val->type->access_qualifier = SpvAccessQualifierReadOnly;
1608 else
1609 val->type->access_qualifier = SpvAccessQualifierReadWrite;
1610
1611 if (multisampled) {
1612 if (dim == GLSL_SAMPLER_DIM_2D)
1613 dim = GLSL_SAMPLER_DIM_MS;
1614 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1615 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1616 else
1617 vtn_fail("Unsupported multisampled image type");
1618 }
1619
1620 val->type->image_format = translate_image_format(b, format);
1621
1622 enum glsl_base_type sampled_base_type =
1623 glsl_get_base_type(sampled_type->type);
1624 if (sampled == 1) {
1625 val->type->glsl_image = glsl_sampler_type(dim, false, is_array,
1626 sampled_base_type);
1627 } else if (sampled == 2) {
1628 val->type->glsl_image = glsl_image_type(dim, is_array,
1629 sampled_base_type);
1630 } else if (b->shader->info.stage == MESA_SHADER_KERNEL) {
1631 val->type->glsl_image = glsl_image_type(dim, is_array,
1632 GLSL_TYPE_VOID);
1633 } else {
1634 vtn_fail("We need to know if the image will be sampled");
1635 }
1636 break;
1637 }
1638
1639 case SpvOpTypeSampledImage: {
1640 val->type->base_type = vtn_base_type_sampled_image;
1641 val->type->image = vtn_get_type(b, w[2]);
1642
1643 /* Sampled images are represented NIR as a vec2 SSA value where each
1644 * component is the result of a deref instruction. The first component
1645 * is the image and the second is the sampler. An OpLoad on an
1646 * OpTypeSampledImage pointer from UniformConstant memory just takes
1647 * the NIR deref from the pointer and duplicates it to both vector
1648 * components.
1649 */
1650 nir_address_format addr_format =
1651 vtn_mode_to_address_format(b, vtn_variable_mode_function);
1652 assert(nir_address_format_num_components(addr_format) == 1);
1653 unsigned bit_size = nir_address_format_bit_size(addr_format);
1654 assert(bit_size == 32 || bit_size == 64);
1655
1656 enum glsl_base_type base_type =
1657 bit_size == 32 ? GLSL_TYPE_UINT : GLSL_TYPE_UINT64;
1658 val->type->type = glsl_vector_type(base_type, 2);
1659 break;
1660 }
1661
1662 case SpvOpTypeSampler:
1663 val->type->base_type = vtn_base_type_sampler;
1664
1665 /* Samplers are represented in NIR as a scalar SSA value that is the
1666 * result of a deref instruction. An OpLoad on an OpTypeSampler pointer
1667 * from UniformConstant memory just takes the NIR deref from the pointer
1668 * and turns it into an SSA value.
1669 */
1670 val->type->type = nir_address_format_to_glsl_type(
1671 vtn_mode_to_address_format(b, vtn_variable_mode_function));
1672 break;
1673
1674 case SpvOpTypeOpaque:
1675 case SpvOpTypeEvent:
1676 case SpvOpTypeDeviceEvent:
1677 case SpvOpTypeReserveId:
1678 case SpvOpTypeQueue:
1679 case SpvOpTypePipe:
1680 default:
1681 vtn_fail_with_opcode("Unhandled opcode", opcode);
1682 }
1683
1684 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1685
1686 if (val->type->base_type == vtn_base_type_struct &&
1687 (val->type->block || val->type->buffer_block)) {
1688 for (unsigned i = 0; i < val->type->length; i++) {
1689 vtn_fail_if(vtn_type_contains_block(b, val->type->members[i]),
1690 "Block and BufferBlock decorations cannot decorate a "
1691 "structure type that is nested at any level inside "
1692 "another structure type decorated with Block or "
1693 "BufferBlock.");
1694 }
1695 }
1696 }
1697
1698 static nir_constant *
1699 vtn_null_constant(struct vtn_builder *b, struct vtn_type *type)
1700 {
1701 nir_constant *c = rzalloc(b, nir_constant);
1702
1703 switch (type->base_type) {
1704 case vtn_base_type_scalar:
1705 case vtn_base_type_vector:
1706 /* Nothing to do here. It's already initialized to zero */
1707 break;
1708
1709 case vtn_base_type_pointer: {
1710 enum vtn_variable_mode mode = vtn_storage_class_to_mode(
1711 b, type->storage_class, type->deref, NULL);
1712 nir_address_format addr_format = vtn_mode_to_address_format(b, mode);
1713
1714 const nir_const_value *null_value = nir_address_format_null_value(addr_format);
1715 memcpy(c->values, null_value,
1716 sizeof(nir_const_value) * nir_address_format_num_components(addr_format));
1717 break;
1718 }
1719
1720 case vtn_base_type_void:
1721 case vtn_base_type_image:
1722 case vtn_base_type_sampler:
1723 case vtn_base_type_sampled_image:
1724 case vtn_base_type_function:
1725 /* For those we have to return something but it doesn't matter what. */
1726 break;
1727
1728 case vtn_base_type_matrix:
1729 case vtn_base_type_array:
1730 vtn_assert(type->length > 0);
1731 c->num_elements = type->length;
1732 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1733
1734 c->elements[0] = vtn_null_constant(b, type->array_element);
1735 for (unsigned i = 1; i < c->num_elements; i++)
1736 c->elements[i] = c->elements[0];
1737 break;
1738
1739 case vtn_base_type_struct:
1740 c->num_elements = type->length;
1741 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1742 for (unsigned i = 0; i < c->num_elements; i++)
1743 c->elements[i] = vtn_null_constant(b, type->members[i]);
1744 break;
1745
1746 default:
1747 vtn_fail("Invalid type for null constant");
1748 }
1749
1750 return c;
1751 }
1752
1753 static void
1754 spec_constant_decoration_cb(struct vtn_builder *b, UNUSED struct vtn_value *val,
1755 ASSERTED int member,
1756 const struct vtn_decoration *dec, void *data)
1757 {
1758 vtn_assert(member == -1);
1759 if (dec->decoration != SpvDecorationSpecId)
1760 return;
1761
1762 nir_const_value *value = data;
1763 for (unsigned i = 0; i < b->num_specializations; i++) {
1764 if (b->specializations[i].id == dec->operands[0]) {
1765 *value = b->specializations[i].value;
1766 return;
1767 }
1768 }
1769 }
1770
1771 static void
1772 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1773 struct vtn_value *val,
1774 ASSERTED int member,
1775 const struct vtn_decoration *dec,
1776 UNUSED void *data)
1777 {
1778 vtn_assert(member == -1);
1779 if (dec->decoration != SpvDecorationBuiltIn ||
1780 dec->operands[0] != SpvBuiltInWorkgroupSize)
1781 return;
1782
1783 vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1784 b->workgroup_size_builtin = val;
1785 }
1786
1787 static void
1788 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1789 const uint32_t *w, unsigned count)
1790 {
1791 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1792 val->constant = rzalloc(b, nir_constant);
1793 switch (opcode) {
1794 case SpvOpConstantTrue:
1795 case SpvOpConstantFalse:
1796 case SpvOpSpecConstantTrue:
1797 case SpvOpSpecConstantFalse: {
1798 vtn_fail_if(val->type->type != glsl_bool_type(),
1799 "Result type of %s must be OpTypeBool",
1800 spirv_op_to_string(opcode));
1801
1802 bool bval = (opcode == SpvOpConstantTrue ||
1803 opcode == SpvOpSpecConstantTrue);
1804
1805 nir_const_value u32val = nir_const_value_for_uint(bval, 32);
1806
1807 if (opcode == SpvOpSpecConstantTrue ||
1808 opcode == SpvOpSpecConstantFalse)
1809 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &u32val);
1810
1811 val->constant->values[0].b = u32val.u32 != 0;
1812 break;
1813 }
1814
1815 case SpvOpConstant:
1816 case SpvOpSpecConstant: {
1817 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1818 "Result type of %s must be a scalar",
1819 spirv_op_to_string(opcode));
1820 int bit_size = glsl_get_bit_size(val->type->type);
1821 switch (bit_size) {
1822 case 64:
1823 val->constant->values[0].u64 = vtn_u64_literal(&w[3]);
1824 break;
1825 case 32:
1826 val->constant->values[0].u32 = w[3];
1827 break;
1828 case 16:
1829 val->constant->values[0].u16 = w[3];
1830 break;
1831 case 8:
1832 val->constant->values[0].u8 = w[3];
1833 break;
1834 default:
1835 vtn_fail("Unsupported SpvOpConstant bit size: %u", bit_size);
1836 }
1837
1838 if (opcode == SpvOpSpecConstant)
1839 vtn_foreach_decoration(b, val, spec_constant_decoration_cb,
1840 &val->constant->values[0]);
1841 break;
1842 }
1843
1844 case SpvOpSpecConstantComposite:
1845 case SpvOpConstantComposite: {
1846 unsigned elem_count = count - 3;
1847 vtn_fail_if(elem_count != val->type->length,
1848 "%s has %u constituents, expected %u",
1849 spirv_op_to_string(opcode), elem_count, val->type->length);
1850
1851 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1852 for (unsigned i = 0; i < elem_count; i++) {
1853 struct vtn_value *val = vtn_untyped_value(b, w[i + 3]);
1854
1855 if (val->value_type == vtn_value_type_constant) {
1856 elems[i] = val->constant;
1857 } else {
1858 vtn_fail_if(val->value_type != vtn_value_type_undef,
1859 "only constants or undefs allowed for "
1860 "SpvOpConstantComposite");
1861 /* to make it easier, just insert a NULL constant for now */
1862 elems[i] = vtn_null_constant(b, val->type);
1863 }
1864 }
1865
1866 switch (val->type->base_type) {
1867 case vtn_base_type_vector: {
1868 assert(glsl_type_is_vector(val->type->type));
1869 for (unsigned i = 0; i < elem_count; i++)
1870 val->constant->values[i] = elems[i]->values[0];
1871 break;
1872 }
1873
1874 case vtn_base_type_matrix:
1875 case vtn_base_type_struct:
1876 case vtn_base_type_array:
1877 ralloc_steal(val->constant, elems);
1878 val->constant->num_elements = elem_count;
1879 val->constant->elements = elems;
1880 break;
1881
1882 default:
1883 vtn_fail("Result type of %s must be a composite type",
1884 spirv_op_to_string(opcode));
1885 }
1886 break;
1887 }
1888
1889 case SpvOpSpecConstantOp: {
1890 nir_const_value u32op = nir_const_value_for_uint(w[3], 32);
1891 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &u32op);
1892 SpvOp opcode = u32op.u32;
1893 switch (opcode) {
1894 case SpvOpVectorShuffle: {
1895 struct vtn_value *v0 = &b->values[w[4]];
1896 struct vtn_value *v1 = &b->values[w[5]];
1897
1898 vtn_assert(v0->value_type == vtn_value_type_constant ||
1899 v0->value_type == vtn_value_type_undef);
1900 vtn_assert(v1->value_type == vtn_value_type_constant ||
1901 v1->value_type == vtn_value_type_undef);
1902
1903 unsigned len0 = glsl_get_vector_elements(v0->type->type);
1904 unsigned len1 = glsl_get_vector_elements(v1->type->type);
1905
1906 vtn_assert(len0 + len1 < 16);
1907
1908 unsigned bit_size = glsl_get_bit_size(val->type->type);
1909 unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1910 unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1911
1912 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1913 (void)bit_size0; (void)bit_size1;
1914
1915 nir_const_value undef = { .u64 = 0xdeadbeefdeadbeef };
1916 nir_const_value combined[NIR_MAX_VEC_COMPONENTS * 2];
1917
1918 if (v0->value_type == vtn_value_type_constant) {
1919 for (unsigned i = 0; i < len0; i++)
1920 combined[i] = v0->constant->values[i];
1921 }
1922 if (v1->value_type == vtn_value_type_constant) {
1923 for (unsigned i = 0; i < len1; i++)
1924 combined[len0 + i] = v1->constant->values[i];
1925 }
1926
1927 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1928 uint32_t comp = w[i + 6];
1929 if (comp == (uint32_t)-1) {
1930 /* If component is not used, set the value to a known constant
1931 * to detect if it is wrongly used.
1932 */
1933 val->constant->values[j] = undef;
1934 } else {
1935 vtn_fail_if(comp >= len0 + len1,
1936 "All Component literals must either be FFFFFFFF "
1937 "or in [0, N - 1] (inclusive).");
1938 val->constant->values[j] = combined[comp];
1939 }
1940 }
1941 break;
1942 }
1943
1944 case SpvOpCompositeExtract:
1945 case SpvOpCompositeInsert: {
1946 struct vtn_value *comp;
1947 unsigned deref_start;
1948 struct nir_constant **c;
1949 if (opcode == SpvOpCompositeExtract) {
1950 comp = vtn_value(b, w[4], vtn_value_type_constant);
1951 deref_start = 5;
1952 c = &comp->constant;
1953 } else {
1954 comp = vtn_value(b, w[5], vtn_value_type_constant);
1955 deref_start = 6;
1956 val->constant = nir_constant_clone(comp->constant,
1957 (nir_variable *)b);
1958 c = &val->constant;
1959 }
1960
1961 int elem = -1;
1962 const struct vtn_type *type = comp->type;
1963 for (unsigned i = deref_start; i < count; i++) {
1964 vtn_fail_if(w[i] > type->length,
1965 "%uth index of %s is %u but the type has only "
1966 "%u elements", i - deref_start,
1967 spirv_op_to_string(opcode), w[i], type->length);
1968
1969 switch (type->base_type) {
1970 case vtn_base_type_vector:
1971 elem = w[i];
1972 type = type->array_element;
1973 break;
1974
1975 case vtn_base_type_matrix:
1976 case vtn_base_type_array:
1977 c = &(*c)->elements[w[i]];
1978 type = type->array_element;
1979 break;
1980
1981 case vtn_base_type_struct:
1982 c = &(*c)->elements[w[i]];
1983 type = type->members[w[i]];
1984 break;
1985
1986 default:
1987 vtn_fail("%s must only index into composite types",
1988 spirv_op_to_string(opcode));
1989 }
1990 }
1991
1992 if (opcode == SpvOpCompositeExtract) {
1993 if (elem == -1) {
1994 val->constant = *c;
1995 } else {
1996 unsigned num_components = type->length;
1997 for (unsigned i = 0; i < num_components; i++)
1998 val->constant->values[i] = (*c)->values[elem + i];
1999 }
2000 } else {
2001 struct vtn_value *insert =
2002 vtn_value(b, w[4], vtn_value_type_constant);
2003 vtn_assert(insert->type == type);
2004 if (elem == -1) {
2005 *c = insert->constant;
2006 } else {
2007 unsigned num_components = type->length;
2008 for (unsigned i = 0; i < num_components; i++)
2009 (*c)->values[elem + i] = insert->constant->values[i];
2010 }
2011 }
2012 break;
2013 }
2014
2015 default: {
2016 bool swap;
2017 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
2018 nir_alu_type src_alu_type = dst_alu_type;
2019 unsigned num_components = glsl_get_vector_elements(val->type->type);
2020 unsigned bit_size;
2021
2022 vtn_assert(count <= 7);
2023
2024 switch (opcode) {
2025 case SpvOpSConvert:
2026 case SpvOpFConvert:
2027 case SpvOpUConvert:
2028 /* We have a source in a conversion */
2029 src_alu_type =
2030 nir_get_nir_type_for_glsl_type(vtn_get_value_type(b, w[4])->type);
2031 /* We use the bitsize of the conversion source to evaluate the opcode later */
2032 bit_size = glsl_get_bit_size(vtn_get_value_type(b, w[4])->type);
2033 break;
2034 default:
2035 bit_size = glsl_get_bit_size(val->type->type);
2036 };
2037
2038 nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
2039 nir_alu_type_get_type_size(src_alu_type),
2040 nir_alu_type_get_type_size(dst_alu_type));
2041 nir_const_value src[3][NIR_MAX_VEC_COMPONENTS];
2042
2043 for (unsigned i = 0; i < count - 4; i++) {
2044 struct vtn_value *src_val =
2045 vtn_value(b, w[4 + i], vtn_value_type_constant);
2046
2047 /* If this is an unsized source, pull the bit size from the
2048 * source; otherwise, we'll use the bit size from the destination.
2049 */
2050 if (!nir_alu_type_get_type_size(nir_op_infos[op].input_types[i]))
2051 bit_size = glsl_get_bit_size(src_val->type->type);
2052
2053 unsigned src_comps = nir_op_infos[op].input_sizes[i] ?
2054 nir_op_infos[op].input_sizes[i] :
2055 num_components;
2056
2057 unsigned j = swap ? 1 - i : i;
2058 for (unsigned c = 0; c < src_comps; c++)
2059 src[j][c] = src_val->constant->values[c];
2060 }
2061
2062 /* fix up fixed size sources */
2063 switch (op) {
2064 case nir_op_ishl:
2065 case nir_op_ishr:
2066 case nir_op_ushr: {
2067 if (bit_size == 32)
2068 break;
2069 for (unsigned i = 0; i < num_components; ++i) {
2070 switch (bit_size) {
2071 case 64: src[1][i].u32 = src[1][i].u64; break;
2072 case 16: src[1][i].u32 = src[1][i].u16; break;
2073 case 8: src[1][i].u32 = src[1][i].u8; break;
2074 }
2075 }
2076 break;
2077 }
2078 default:
2079 break;
2080 }
2081
2082 nir_const_value *srcs[3] = {
2083 src[0], src[1], src[2],
2084 };
2085 nir_eval_const_opcode(op, val->constant->values,
2086 num_components, bit_size, srcs,
2087 b->shader->info.float_controls_execution_mode);
2088 break;
2089 } /* default */
2090 }
2091 break;
2092 }
2093
2094 case SpvOpConstantNull:
2095 val->constant = vtn_null_constant(b, val->type);
2096 break;
2097
2098 default:
2099 vtn_fail_with_opcode("Unhandled opcode", opcode);
2100 }
2101
2102 /* Now that we have the value, update the workgroup size if needed */
2103 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
2104 }
2105
2106 static void
2107 vtn_split_barrier_semantics(struct vtn_builder *b,
2108 SpvMemorySemanticsMask semantics,
2109 SpvMemorySemanticsMask *before,
2110 SpvMemorySemanticsMask *after)
2111 {
2112 /* For memory semantics embedded in operations, we split them into up to
2113 * two barriers, to be added before and after the operation. This is less
2114 * strict than if we propagated until the final backend stage, but still
2115 * result in correct execution.
2116 *
2117 * A further improvement could be pipe this information (and use!) into the
2118 * next compiler layers, at the expense of making the handling of barriers
2119 * more complicated.
2120 */
2121
2122 *before = SpvMemorySemanticsMaskNone;
2123 *after = SpvMemorySemanticsMaskNone;
2124
2125 SpvMemorySemanticsMask order_semantics =
2126 semantics & (SpvMemorySemanticsAcquireMask |
2127 SpvMemorySemanticsReleaseMask |
2128 SpvMemorySemanticsAcquireReleaseMask |
2129 SpvMemorySemanticsSequentiallyConsistentMask);
2130
2131 if (util_bitcount(order_semantics) > 1) {
2132 /* Old GLSLang versions incorrectly set all the ordering bits. This was
2133 * fixed in c51287d744fb6e7e9ccc09f6f8451e6c64b1dad6 of glslang repo,
2134 * and it is in GLSLang since revision "SPIRV99.1321" (from Jul-2016).
2135 */
2136 vtn_warn("Multiple memory ordering semantics specified, "
2137 "assuming AcquireRelease.");
2138 order_semantics = SpvMemorySemanticsAcquireReleaseMask;
2139 }
2140
2141 const SpvMemorySemanticsMask av_vis_semantics =
2142 semantics & (SpvMemorySemanticsMakeAvailableMask |
2143 SpvMemorySemanticsMakeVisibleMask);
2144
2145 const SpvMemorySemanticsMask storage_semantics =
2146 semantics & (SpvMemorySemanticsUniformMemoryMask |
2147 SpvMemorySemanticsSubgroupMemoryMask |
2148 SpvMemorySemanticsWorkgroupMemoryMask |
2149 SpvMemorySemanticsCrossWorkgroupMemoryMask |
2150 SpvMemorySemanticsAtomicCounterMemoryMask |
2151 SpvMemorySemanticsImageMemoryMask |
2152 SpvMemorySemanticsOutputMemoryMask);
2153
2154 const SpvMemorySemanticsMask other_semantics =
2155 semantics & ~(order_semantics | av_vis_semantics | storage_semantics);
2156
2157 if (other_semantics)
2158 vtn_warn("Ignoring unhandled memory semantics: %u\n", other_semantics);
2159
2160 /* SequentiallyConsistent is treated as AcquireRelease. */
2161
2162 /* The RELEASE barrier happens BEFORE the operation, and it is usually
2163 * associated with a Store. All the write operations with a matching
2164 * semantics will not be reordered after the Store.
2165 */
2166 if (order_semantics & (SpvMemorySemanticsReleaseMask |
2167 SpvMemorySemanticsAcquireReleaseMask |
2168 SpvMemorySemanticsSequentiallyConsistentMask)) {
2169 *before |= SpvMemorySemanticsReleaseMask | storage_semantics;
2170 }
2171
2172 /* The ACQUIRE barrier happens AFTER the operation, and it is usually
2173 * associated with a Load. All the operations with a matching semantics
2174 * will not be reordered before the Load.
2175 */
2176 if (order_semantics & (SpvMemorySemanticsAcquireMask |
2177 SpvMemorySemanticsAcquireReleaseMask |
2178 SpvMemorySemanticsSequentiallyConsistentMask)) {
2179 *after |= SpvMemorySemanticsAcquireMask | storage_semantics;
2180 }
2181
2182 if (av_vis_semantics & SpvMemorySemanticsMakeVisibleMask)
2183 *before |= SpvMemorySemanticsMakeVisibleMask | storage_semantics;
2184
2185 if (av_vis_semantics & SpvMemorySemanticsMakeAvailableMask)
2186 *after |= SpvMemorySemanticsMakeAvailableMask | storage_semantics;
2187 }
2188
2189 static nir_memory_semantics
2190 vtn_mem_semantics_to_nir_mem_semantics(struct vtn_builder *b,
2191 SpvMemorySemanticsMask semantics)
2192 {
2193 nir_memory_semantics nir_semantics = 0;
2194
2195 SpvMemorySemanticsMask order_semantics =
2196 semantics & (SpvMemorySemanticsAcquireMask |
2197 SpvMemorySemanticsReleaseMask |
2198 SpvMemorySemanticsAcquireReleaseMask |
2199 SpvMemorySemanticsSequentiallyConsistentMask);
2200
2201 if (util_bitcount(order_semantics) > 1) {
2202 /* Old GLSLang versions incorrectly set all the ordering bits. This was
2203 * fixed in c51287d744fb6e7e9ccc09f6f8451e6c64b1dad6 of glslang repo,
2204 * and it is in GLSLang since revision "SPIRV99.1321" (from Jul-2016).
2205 */
2206 vtn_warn("Multiple memory ordering semantics bits specified, "
2207 "assuming AcquireRelease.");
2208 order_semantics = SpvMemorySemanticsAcquireReleaseMask;
2209 }
2210
2211 switch (order_semantics) {
2212 case 0:
2213 /* Not an ordering barrier. */
2214 break;
2215
2216 case SpvMemorySemanticsAcquireMask:
2217 nir_semantics = NIR_MEMORY_ACQUIRE;
2218 break;
2219
2220 case SpvMemorySemanticsReleaseMask:
2221 nir_semantics = NIR_MEMORY_RELEASE;
2222 break;
2223
2224 case SpvMemorySemanticsSequentiallyConsistentMask:
2225 /* Fall through. Treated as AcquireRelease in Vulkan. */
2226 case SpvMemorySemanticsAcquireReleaseMask:
2227 nir_semantics = NIR_MEMORY_ACQUIRE | NIR_MEMORY_RELEASE;
2228 break;
2229
2230 default:
2231 unreachable("Invalid memory order semantics");
2232 }
2233
2234 if (semantics & SpvMemorySemanticsMakeAvailableMask) {
2235 vtn_fail_if(!b->options->caps.vk_memory_model,
2236 "To use MakeAvailable memory semantics the VulkanMemoryModel "
2237 "capability must be declared.");
2238 nir_semantics |= NIR_MEMORY_MAKE_AVAILABLE;
2239 }
2240
2241 if (semantics & SpvMemorySemanticsMakeVisibleMask) {
2242 vtn_fail_if(!b->options->caps.vk_memory_model,
2243 "To use MakeVisible memory semantics the VulkanMemoryModel "
2244 "capability must be declared.");
2245 nir_semantics |= NIR_MEMORY_MAKE_VISIBLE;
2246 }
2247
2248 return nir_semantics;
2249 }
2250
2251 static nir_variable_mode
2252 vtn_mem_sematics_to_nir_var_modes(struct vtn_builder *b,
2253 SpvMemorySemanticsMask semantics)
2254 {
2255 /* Vulkan Environment for SPIR-V says "SubgroupMemory, CrossWorkgroupMemory,
2256 * and AtomicCounterMemory are ignored".
2257 */
2258 semantics &= ~(SpvMemorySemanticsSubgroupMemoryMask |
2259 SpvMemorySemanticsCrossWorkgroupMemoryMask |
2260 SpvMemorySemanticsAtomicCounterMemoryMask);
2261
2262 /* TODO: Consider adding nir_var_mem_image mode to NIR so it can be used
2263 * for SpvMemorySemanticsImageMemoryMask.
2264 */
2265
2266 nir_variable_mode modes = 0;
2267 if (semantics & (SpvMemorySemanticsUniformMemoryMask |
2268 SpvMemorySemanticsImageMemoryMask)) {
2269 modes |= nir_var_uniform |
2270 nir_var_mem_ubo |
2271 nir_var_mem_ssbo |
2272 nir_var_mem_global;
2273 }
2274 if (semantics & SpvMemorySemanticsWorkgroupMemoryMask)
2275 modes |= nir_var_mem_shared;
2276 if (semantics & SpvMemorySemanticsOutputMemoryMask) {
2277 modes |= nir_var_shader_out;
2278 }
2279
2280 return modes;
2281 }
2282
2283 static nir_scope
2284 vtn_scope_to_nir_scope(struct vtn_builder *b, SpvScope scope)
2285 {
2286 nir_scope nir_scope;
2287 switch (scope) {
2288 case SpvScopeDevice:
2289 vtn_fail_if(b->options->caps.vk_memory_model &&
2290 !b->options->caps.vk_memory_model_device_scope,
2291 "If the Vulkan memory model is declared and any instruction "
2292 "uses Device scope, the VulkanMemoryModelDeviceScope "
2293 "capability must be declared.");
2294 nir_scope = NIR_SCOPE_DEVICE;
2295 break;
2296
2297 case SpvScopeQueueFamily:
2298 vtn_fail_if(!b->options->caps.vk_memory_model,
2299 "To use Queue Family scope, the VulkanMemoryModel capability "
2300 "must be declared.");
2301 nir_scope = NIR_SCOPE_QUEUE_FAMILY;
2302 break;
2303
2304 case SpvScopeWorkgroup:
2305 nir_scope = NIR_SCOPE_WORKGROUP;
2306 break;
2307
2308 case SpvScopeSubgroup:
2309 nir_scope = NIR_SCOPE_SUBGROUP;
2310 break;
2311
2312 case SpvScopeInvocation:
2313 nir_scope = NIR_SCOPE_INVOCATION;
2314 break;
2315
2316 default:
2317 vtn_fail("Invalid memory scope");
2318 }
2319
2320 return nir_scope;
2321 }
2322
2323 static void
2324 vtn_emit_scoped_control_barrier(struct vtn_builder *b, SpvScope exec_scope,
2325 SpvScope mem_scope,
2326 SpvMemorySemanticsMask semantics)
2327 {
2328 nir_memory_semantics nir_semantics =
2329 vtn_mem_semantics_to_nir_mem_semantics(b, semantics);
2330 nir_variable_mode modes = vtn_mem_sematics_to_nir_var_modes(b, semantics);
2331 nir_scope nir_exec_scope = vtn_scope_to_nir_scope(b, exec_scope);
2332
2333 /* Memory semantics is optional for OpControlBarrier. */
2334 nir_scope nir_mem_scope;
2335 if (nir_semantics == 0 || modes == 0)
2336 nir_mem_scope = NIR_SCOPE_NONE;
2337 else
2338 nir_mem_scope = vtn_scope_to_nir_scope(b, mem_scope);
2339
2340 nir_scoped_barrier(&b->nb, nir_exec_scope, nir_mem_scope, nir_semantics, modes);
2341 }
2342
2343 static void
2344 vtn_emit_scoped_memory_barrier(struct vtn_builder *b, SpvScope scope,
2345 SpvMemorySemanticsMask semantics)
2346 {
2347 nir_variable_mode modes = vtn_mem_sematics_to_nir_var_modes(b, semantics);
2348 nir_memory_semantics nir_semantics =
2349 vtn_mem_semantics_to_nir_mem_semantics(b, semantics);
2350
2351 /* No barrier to add. */
2352 if (nir_semantics == 0 || modes == 0)
2353 return;
2354
2355 nir_scope nir_mem_scope = vtn_scope_to_nir_scope(b, scope);
2356 nir_scoped_barrier(&b->nb, NIR_SCOPE_NONE, nir_mem_scope, nir_semantics, modes);
2357 }
2358
2359 struct vtn_ssa_value *
2360 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
2361 {
2362 /* Always use bare types for SSA values for a couple of reasons:
2363 *
2364 * 1. Code which emits deref chains should never listen to the explicit
2365 * layout information on the SSA value if any exists. If we've
2366 * accidentally been relying on this, we want to find those bugs.
2367 *
2368 * 2. We want to be able to quickly check that an SSA value being assigned
2369 * to a SPIR-V value has the right type. Using bare types everywhere
2370 * ensures that we can pointer-compare.
2371 */
2372 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
2373 val->type = glsl_get_bare_type(type);
2374
2375
2376 if (!glsl_type_is_vector_or_scalar(type)) {
2377 unsigned elems = glsl_get_length(val->type);
2378 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2379 if (glsl_type_is_array_or_matrix(type)) {
2380 const struct glsl_type *elem_type = glsl_get_array_element(type);
2381 for (unsigned i = 0; i < elems; i++)
2382 val->elems[i] = vtn_create_ssa_value(b, elem_type);
2383 } else {
2384 vtn_assert(glsl_type_is_struct_or_ifc(type));
2385 for (unsigned i = 0; i < elems; i++) {
2386 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
2387 val->elems[i] = vtn_create_ssa_value(b, elem_type);
2388 }
2389 }
2390 }
2391
2392 return val;
2393 }
2394
2395 static nir_tex_src
2396 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
2397 {
2398 nir_tex_src src;
2399 src.src = nir_src_for_ssa(vtn_get_nir_ssa(b, index));
2400 src.src_type = type;
2401 return src;
2402 }
2403
2404 static uint32_t
2405 image_operand_arg(struct vtn_builder *b, const uint32_t *w, uint32_t count,
2406 uint32_t mask_idx, SpvImageOperandsMask op)
2407 {
2408 static const SpvImageOperandsMask ops_with_arg =
2409 SpvImageOperandsBiasMask |
2410 SpvImageOperandsLodMask |
2411 SpvImageOperandsGradMask |
2412 SpvImageOperandsConstOffsetMask |
2413 SpvImageOperandsOffsetMask |
2414 SpvImageOperandsConstOffsetsMask |
2415 SpvImageOperandsSampleMask |
2416 SpvImageOperandsMinLodMask |
2417 SpvImageOperandsMakeTexelAvailableMask |
2418 SpvImageOperandsMakeTexelVisibleMask;
2419
2420 assert(util_bitcount(op) == 1);
2421 assert(w[mask_idx] & op);
2422 assert(op & ops_with_arg);
2423
2424 uint32_t idx = util_bitcount(w[mask_idx] & (op - 1) & ops_with_arg) + 1;
2425
2426 /* Adjust indices for operands with two arguments. */
2427 static const SpvImageOperandsMask ops_with_two_args =
2428 SpvImageOperandsGradMask;
2429 idx += util_bitcount(w[mask_idx] & (op - 1) & ops_with_two_args);
2430
2431 idx += mask_idx;
2432
2433 vtn_fail_if(idx + (op & ops_with_two_args ? 1 : 0) >= count,
2434 "Image op claims to have %s but does not enough "
2435 "following operands", spirv_imageoperands_to_string(op));
2436
2437 return idx;
2438 }
2439
2440 static void
2441 non_uniform_decoration_cb(struct vtn_builder *b,
2442 struct vtn_value *val, int member,
2443 const struct vtn_decoration *dec, void *void_ctx)
2444 {
2445 enum gl_access_qualifier *access = void_ctx;
2446 switch (dec->decoration) {
2447 case SpvDecorationNonUniformEXT:
2448 *access |= ACCESS_NON_UNIFORM;
2449 break;
2450
2451 default:
2452 break;
2453 }
2454 }
2455
2456 static void
2457 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
2458 const uint32_t *w, unsigned count)
2459 {
2460 struct vtn_type *ret_type = vtn_get_type(b, w[1]);
2461
2462 if (opcode == SpvOpSampledImage) {
2463 struct vtn_sampled_image si = {
2464 .image = vtn_get_image(b, w[3]),
2465 .sampler = vtn_get_sampler(b, w[4]),
2466 };
2467 vtn_push_sampled_image(b, w[2], si);
2468 return;
2469 } else if (opcode == SpvOpImage) {
2470 struct vtn_sampled_image si = vtn_get_sampled_image(b, w[3]);
2471 vtn_push_image(b, w[2], si.image);
2472 return;
2473 }
2474
2475 nir_deref_instr *image = NULL, *sampler = NULL;
2476 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
2477 if (sampled_val->type->base_type == vtn_base_type_sampled_image) {
2478 struct vtn_sampled_image si = vtn_get_sampled_image(b, w[3]);
2479 image = si.image;
2480 sampler = si.sampler;
2481 } else {
2482 image = vtn_get_image(b, w[3]);
2483 }
2484
2485 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image->type);
2486 const bool is_array = glsl_sampler_type_is_array(image->type);
2487 nir_alu_type dest_type = nir_type_invalid;
2488
2489 /* Figure out the base texture operation */
2490 nir_texop texop;
2491 switch (opcode) {
2492 case SpvOpImageSampleImplicitLod:
2493 case SpvOpImageSampleDrefImplicitLod:
2494 case SpvOpImageSampleProjImplicitLod:
2495 case SpvOpImageSampleProjDrefImplicitLod:
2496 texop = nir_texop_tex;
2497 break;
2498
2499 case SpvOpImageSampleExplicitLod:
2500 case SpvOpImageSampleDrefExplicitLod:
2501 case SpvOpImageSampleProjExplicitLod:
2502 case SpvOpImageSampleProjDrefExplicitLod:
2503 texop = nir_texop_txl;
2504 break;
2505
2506 case SpvOpImageFetch:
2507 if (sampler_dim == GLSL_SAMPLER_DIM_MS) {
2508 texop = nir_texop_txf_ms;
2509 } else {
2510 texop = nir_texop_txf;
2511 }
2512 break;
2513
2514 case SpvOpImageGather:
2515 case SpvOpImageDrefGather:
2516 texop = nir_texop_tg4;
2517 break;
2518
2519 case SpvOpImageQuerySizeLod:
2520 case SpvOpImageQuerySize:
2521 texop = nir_texop_txs;
2522 dest_type = nir_type_int;
2523 break;
2524
2525 case SpvOpImageQueryLod:
2526 texop = nir_texop_lod;
2527 dest_type = nir_type_float;
2528 break;
2529
2530 case SpvOpImageQueryLevels:
2531 texop = nir_texop_query_levels;
2532 dest_type = nir_type_int;
2533 break;
2534
2535 case SpvOpImageQuerySamples:
2536 texop = nir_texop_texture_samples;
2537 dest_type = nir_type_int;
2538 break;
2539
2540 case SpvOpFragmentFetchAMD:
2541 texop = nir_texop_fragment_fetch;
2542 break;
2543
2544 case SpvOpFragmentMaskFetchAMD:
2545 texop = nir_texop_fragment_mask_fetch;
2546 break;
2547
2548 default:
2549 vtn_fail_with_opcode("Unhandled opcode", opcode);
2550 }
2551
2552 nir_tex_src srcs[10]; /* 10 should be enough */
2553 nir_tex_src *p = srcs;
2554
2555 p->src = nir_src_for_ssa(&image->dest.ssa);
2556 p->src_type = nir_tex_src_texture_deref;
2557 p++;
2558
2559 switch (texop) {
2560 case nir_texop_tex:
2561 case nir_texop_txb:
2562 case nir_texop_txl:
2563 case nir_texop_txd:
2564 case nir_texop_tg4:
2565 case nir_texop_lod:
2566 vtn_fail_if(sampler == NULL,
2567 "%s requires an image of type OpTypeSampledImage",
2568 spirv_op_to_string(opcode));
2569 p->src = nir_src_for_ssa(&sampler->dest.ssa);
2570 p->src_type = nir_tex_src_sampler_deref;
2571 p++;
2572 break;
2573 case nir_texop_txf:
2574 case nir_texop_txf_ms:
2575 case nir_texop_txs:
2576 case nir_texop_query_levels:
2577 case nir_texop_texture_samples:
2578 case nir_texop_samples_identical:
2579 case nir_texop_fragment_fetch:
2580 case nir_texop_fragment_mask_fetch:
2581 /* These don't */
2582 break;
2583 case nir_texop_txf_ms_fb:
2584 vtn_fail("unexpected nir_texop_txf_ms_fb");
2585 break;
2586 case nir_texop_txf_ms_mcs:
2587 vtn_fail("unexpected nir_texop_txf_ms_mcs");
2588 case nir_texop_tex_prefetch:
2589 vtn_fail("unexpected nir_texop_tex_prefetch");
2590 }
2591
2592 unsigned idx = 4;
2593
2594 struct nir_ssa_def *coord;
2595 unsigned coord_components;
2596 switch (opcode) {
2597 case SpvOpImageSampleImplicitLod:
2598 case SpvOpImageSampleExplicitLod:
2599 case SpvOpImageSampleDrefImplicitLod:
2600 case SpvOpImageSampleDrefExplicitLod:
2601 case SpvOpImageSampleProjImplicitLod:
2602 case SpvOpImageSampleProjExplicitLod:
2603 case SpvOpImageSampleProjDrefImplicitLod:
2604 case SpvOpImageSampleProjDrefExplicitLod:
2605 case SpvOpImageFetch:
2606 case SpvOpImageGather:
2607 case SpvOpImageDrefGather:
2608 case SpvOpImageQueryLod:
2609 case SpvOpFragmentFetchAMD:
2610 case SpvOpFragmentMaskFetchAMD: {
2611 /* All these types have the coordinate as their first real argument */
2612 coord_components = glsl_get_sampler_dim_coordinate_components(sampler_dim);
2613
2614 if (is_array && texop != nir_texop_lod)
2615 coord_components++;
2616
2617 struct vtn_ssa_value *coord_val = vtn_ssa_value(b, w[idx++]);
2618 coord = coord_val->def;
2619 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
2620 (1 << coord_components) - 1));
2621
2622 /* OpenCL allows integer sampling coordinates */
2623 if (glsl_type_is_integer(coord_val->type) &&
2624 opcode == SpvOpImageSampleExplicitLod) {
2625 vtn_fail_if(b->shader->info.stage != MESA_SHADER_KERNEL,
2626 "Unless the Kernel capability is being used, the coordinate parameter "
2627 "OpImageSampleExplicitLod must be floating point.");
2628
2629 p->src = nir_src_for_ssa(nir_i2f32(&b->nb, p->src.ssa));
2630 }
2631
2632 p->src_type = nir_tex_src_coord;
2633 p++;
2634 break;
2635 }
2636
2637 default:
2638 coord = NULL;
2639 coord_components = 0;
2640 break;
2641 }
2642
2643 switch (opcode) {
2644 case SpvOpImageSampleProjImplicitLod:
2645 case SpvOpImageSampleProjExplicitLod:
2646 case SpvOpImageSampleProjDrefImplicitLod:
2647 case SpvOpImageSampleProjDrefExplicitLod:
2648 /* These have the projector as the last coordinate component */
2649 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
2650 p->src_type = nir_tex_src_projector;
2651 p++;
2652 break;
2653
2654 default:
2655 break;
2656 }
2657
2658 bool is_shadow = false;
2659 unsigned gather_component = 0;
2660 switch (opcode) {
2661 case SpvOpImageSampleDrefImplicitLod:
2662 case SpvOpImageSampleDrefExplicitLod:
2663 case SpvOpImageSampleProjDrefImplicitLod:
2664 case SpvOpImageSampleProjDrefExplicitLod:
2665 case SpvOpImageDrefGather:
2666 /* These all have an explicit depth value as their next source */
2667 is_shadow = true;
2668 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2669 break;
2670
2671 case SpvOpImageGather:
2672 /* This has a component as its next source */
2673 gather_component = vtn_constant_uint(b, w[idx++]);
2674 break;
2675
2676 default:
2677 break;
2678 }
2679
2680 /* For OpImageQuerySizeLod, we always have an LOD */
2681 if (opcode == SpvOpImageQuerySizeLod)
2682 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2683
2684 /* For OpFragmentFetchAMD, we always have a multisample index */
2685 if (opcode == SpvOpFragmentFetchAMD)
2686 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2687
2688 /* Now we need to handle some number of optional arguments */
2689 struct vtn_value *gather_offsets = NULL;
2690 if (idx < count) {
2691 uint32_t operands = w[idx];
2692
2693 if (operands & SpvImageOperandsBiasMask) {
2694 vtn_assert(texop == nir_texop_tex ||
2695 texop == nir_texop_tg4);
2696 if (texop == nir_texop_tex)
2697 texop = nir_texop_txb;
2698 uint32_t arg = image_operand_arg(b, w, count, idx,
2699 SpvImageOperandsBiasMask);
2700 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_bias);
2701 }
2702
2703 if (operands & SpvImageOperandsLodMask) {
2704 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2705 texop == nir_texop_txs || texop == nir_texop_tg4);
2706 uint32_t arg = image_operand_arg(b, w, count, idx,
2707 SpvImageOperandsLodMask);
2708 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_lod);
2709 }
2710
2711 if (operands & SpvImageOperandsGradMask) {
2712 vtn_assert(texop == nir_texop_txl);
2713 texop = nir_texop_txd;
2714 uint32_t arg = image_operand_arg(b, w, count, idx,
2715 SpvImageOperandsGradMask);
2716 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_ddx);
2717 (*p++) = vtn_tex_src(b, w[arg + 1], nir_tex_src_ddy);
2718 }
2719
2720 vtn_fail_if(util_bitcount(operands & (SpvImageOperandsConstOffsetsMask |
2721 SpvImageOperandsOffsetMask |
2722 SpvImageOperandsConstOffsetMask)) > 1,
2723 "At most one of the ConstOffset, Offset, and ConstOffsets "
2724 "image operands can be used on a given instruction.");
2725
2726 if (operands & SpvImageOperandsOffsetMask) {
2727 uint32_t arg = image_operand_arg(b, w, count, idx,
2728 SpvImageOperandsOffsetMask);
2729 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_offset);
2730 }
2731
2732 if (operands & SpvImageOperandsConstOffsetMask) {
2733 uint32_t arg = image_operand_arg(b, w, count, idx,
2734 SpvImageOperandsConstOffsetMask);
2735 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_offset);
2736 }
2737
2738 if (operands & SpvImageOperandsConstOffsetsMask) {
2739 vtn_assert(texop == nir_texop_tg4);
2740 uint32_t arg = image_operand_arg(b, w, count, idx,
2741 SpvImageOperandsConstOffsetsMask);
2742 gather_offsets = vtn_value(b, w[arg], vtn_value_type_constant);
2743 }
2744
2745 if (operands & SpvImageOperandsSampleMask) {
2746 vtn_assert(texop == nir_texop_txf_ms);
2747 uint32_t arg = image_operand_arg(b, w, count, idx,
2748 SpvImageOperandsSampleMask);
2749 texop = nir_texop_txf_ms;
2750 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_ms_index);
2751 }
2752
2753 if (operands & SpvImageOperandsMinLodMask) {
2754 vtn_assert(texop == nir_texop_tex ||
2755 texop == nir_texop_txb ||
2756 texop == nir_texop_txd);
2757 uint32_t arg = image_operand_arg(b, w, count, idx,
2758 SpvImageOperandsMinLodMask);
2759 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_min_lod);
2760 }
2761 }
2762
2763 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2764 instr->op = texop;
2765
2766 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2767
2768 instr->coord_components = coord_components;
2769 instr->sampler_dim = sampler_dim;
2770 instr->is_array = is_array;
2771 instr->is_shadow = is_shadow;
2772 instr->is_new_style_shadow =
2773 is_shadow && glsl_get_components(ret_type->type) == 1;
2774 instr->component = gather_component;
2775
2776 /* The Vulkan spec says:
2777 *
2778 * "If an instruction loads from or stores to a resource (including
2779 * atomics and image instructions) and the resource descriptor being
2780 * accessed is not dynamically uniform, then the operand corresponding
2781 * to that resource (e.g. the pointer or sampled image operand) must be
2782 * decorated with NonUniform."
2783 *
2784 * It's very careful to specify that the exact operand must be decorated
2785 * NonUniform. The SPIR-V parser is not expected to chase through long
2786 * chains to find the NonUniform decoration. It's either right there or we
2787 * can assume it doesn't exist.
2788 */
2789 enum gl_access_qualifier access = 0;
2790 vtn_foreach_decoration(b, sampled_val, non_uniform_decoration_cb, &access);
2791
2792 if (image && (access & ACCESS_NON_UNIFORM))
2793 instr->texture_non_uniform = true;
2794
2795 if (sampler && (access & ACCESS_NON_UNIFORM))
2796 instr->sampler_non_uniform = true;
2797
2798 /* for non-query ops, get dest_type from SPIR-V return type */
2799 if (dest_type == nir_type_invalid) {
2800 /* the return type should match the image type, unless the image type is
2801 * VOID (CL image), in which case the return type dictates the sampler
2802 */
2803 enum glsl_base_type sampler_base =
2804 glsl_get_sampler_result_type(image->type);
2805 enum glsl_base_type ret_base = glsl_get_base_type(ret_type->type);
2806 vtn_fail_if(sampler_base != ret_base && sampler_base != GLSL_TYPE_VOID,
2807 "SPIR-V return type mismatches image type. This is only valid "
2808 "for untyped images (OpenCL).");
2809 switch (ret_base) {
2810 case GLSL_TYPE_FLOAT: dest_type = nir_type_float; break;
2811 case GLSL_TYPE_INT: dest_type = nir_type_int; break;
2812 case GLSL_TYPE_UINT: dest_type = nir_type_uint; break;
2813 case GLSL_TYPE_BOOL: dest_type = nir_type_bool; break;
2814 default:
2815 vtn_fail("Invalid base type for sampler result");
2816 }
2817 }
2818
2819 instr->dest_type = dest_type;
2820
2821 nir_ssa_dest_init(&instr->instr, &instr->dest,
2822 nir_tex_instr_dest_size(instr), 32, NULL);
2823
2824 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2825 nir_tex_instr_dest_size(instr));
2826
2827 if (gather_offsets) {
2828 vtn_fail_if(gather_offsets->type->base_type != vtn_base_type_array ||
2829 gather_offsets->type->length != 4,
2830 "ConstOffsets must be an array of size four of vectors "
2831 "of two integer components");
2832
2833 struct vtn_type *vec_type = gather_offsets->type->array_element;
2834 vtn_fail_if(vec_type->base_type != vtn_base_type_vector ||
2835 vec_type->length != 2 ||
2836 !glsl_type_is_integer(vec_type->type),
2837 "ConstOffsets must be an array of size four of vectors "
2838 "of two integer components");
2839
2840 unsigned bit_size = glsl_get_bit_size(vec_type->type);
2841 for (uint32_t i = 0; i < 4; i++) {
2842 const nir_const_value *cvec =
2843 gather_offsets->constant->elements[i]->values;
2844 for (uint32_t j = 0; j < 2; j++) {
2845 switch (bit_size) {
2846 case 8: instr->tg4_offsets[i][j] = cvec[j].i8; break;
2847 case 16: instr->tg4_offsets[i][j] = cvec[j].i16; break;
2848 case 32: instr->tg4_offsets[i][j] = cvec[j].i32; break;
2849 case 64: instr->tg4_offsets[i][j] = cvec[j].i64; break;
2850 default:
2851 vtn_fail("Unsupported bit size: %u", bit_size);
2852 }
2853 }
2854 }
2855 }
2856
2857 nir_builder_instr_insert(&b->nb, &instr->instr);
2858
2859 vtn_push_nir_ssa(b, w[2], &instr->dest.ssa);
2860 }
2861
2862 static void
2863 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2864 const uint32_t *w, nir_src *src)
2865 {
2866 switch (opcode) {
2867 case SpvOpAtomicIIncrement:
2868 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2869 break;
2870
2871 case SpvOpAtomicIDecrement:
2872 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2873 break;
2874
2875 case SpvOpAtomicISub:
2876 src[0] =
2877 nir_src_for_ssa(nir_ineg(&b->nb, vtn_get_nir_ssa(b, w[6])));
2878 break;
2879
2880 case SpvOpAtomicCompareExchange:
2881 case SpvOpAtomicCompareExchangeWeak:
2882 src[0] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[8]));
2883 src[1] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[7]));
2884 break;
2885
2886 case SpvOpAtomicExchange:
2887 case SpvOpAtomicIAdd:
2888 case SpvOpAtomicSMin:
2889 case SpvOpAtomicUMin:
2890 case SpvOpAtomicSMax:
2891 case SpvOpAtomicUMax:
2892 case SpvOpAtomicAnd:
2893 case SpvOpAtomicOr:
2894 case SpvOpAtomicXor:
2895 case SpvOpAtomicFAddEXT:
2896 src[0] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[6]));
2897 break;
2898
2899 default:
2900 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
2901 }
2902 }
2903
2904 static nir_ssa_def *
2905 get_image_coord(struct vtn_builder *b, uint32_t value)
2906 {
2907 nir_ssa_def *coord = vtn_get_nir_ssa(b, value);
2908
2909 /* The image_load_store intrinsics assume a 4-dim coordinate */
2910 unsigned swizzle[4];
2911 for (unsigned i = 0; i < 4; i++)
2912 swizzle[i] = MIN2(i, coord->num_components - 1);
2913
2914 return nir_swizzle(&b->nb, coord, swizzle, 4);
2915 }
2916
2917 static nir_ssa_def *
2918 expand_to_vec4(nir_builder *b, nir_ssa_def *value)
2919 {
2920 if (value->num_components == 4)
2921 return value;
2922
2923 unsigned swiz[4];
2924 for (unsigned i = 0; i < 4; i++)
2925 swiz[i] = i < value->num_components ? i : 0;
2926 return nir_swizzle(b, value, swiz, 4);
2927 }
2928
2929 static void
2930 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2931 const uint32_t *w, unsigned count)
2932 {
2933 /* Just get this one out of the way */
2934 if (opcode == SpvOpImageTexelPointer) {
2935 struct vtn_value *val =
2936 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2937 val->image = ralloc(b, struct vtn_image_pointer);
2938
2939 val->image->image = vtn_nir_deref(b, w[3]);
2940 val->image->coord = get_image_coord(b, w[4]);
2941 val->image->sample = vtn_get_nir_ssa(b, w[5]);
2942 val->image->lod = nir_imm_int(&b->nb, 0);
2943 return;
2944 }
2945
2946 struct vtn_image_pointer image;
2947 SpvScope scope = SpvScopeInvocation;
2948 SpvMemorySemanticsMask semantics = 0;
2949
2950 enum gl_access_qualifier access = 0;
2951
2952 struct vtn_value *res_val;
2953 switch (opcode) {
2954 case SpvOpAtomicExchange:
2955 case SpvOpAtomicCompareExchange:
2956 case SpvOpAtomicCompareExchangeWeak:
2957 case SpvOpAtomicIIncrement:
2958 case SpvOpAtomicIDecrement:
2959 case SpvOpAtomicIAdd:
2960 case SpvOpAtomicISub:
2961 case SpvOpAtomicLoad:
2962 case SpvOpAtomicSMin:
2963 case SpvOpAtomicUMin:
2964 case SpvOpAtomicSMax:
2965 case SpvOpAtomicUMax:
2966 case SpvOpAtomicAnd:
2967 case SpvOpAtomicOr:
2968 case SpvOpAtomicXor:
2969 case SpvOpAtomicFAddEXT:
2970 res_val = vtn_value(b, w[3], vtn_value_type_image_pointer);
2971 image = *res_val->image;
2972 scope = vtn_constant_uint(b, w[4]);
2973 semantics = vtn_constant_uint(b, w[5]);
2974 access |= ACCESS_COHERENT;
2975 break;
2976
2977 case SpvOpAtomicStore:
2978 res_val = vtn_value(b, w[1], vtn_value_type_image_pointer);
2979 image = *res_val->image;
2980 scope = vtn_constant_uint(b, w[2]);
2981 semantics = vtn_constant_uint(b, w[3]);
2982 access |= ACCESS_COHERENT;
2983 break;
2984
2985 case SpvOpImageQuerySizeLod:
2986 res_val = vtn_untyped_value(b, w[3]);
2987 image.image = vtn_get_image(b, w[3]);
2988 image.coord = NULL;
2989 image.sample = NULL;
2990 image.lod = vtn_ssa_value(b, w[4])->def;
2991 break;
2992
2993 case SpvOpImageQuerySize:
2994 res_val = vtn_untyped_value(b, w[3]);
2995 image.image = vtn_get_image(b, w[3]);
2996 image.coord = NULL;
2997 image.sample = NULL;
2998 image.lod = NULL;
2999 break;
3000
3001 case SpvOpImageQueryFormat:
3002 case SpvOpImageQueryOrder:
3003 res_val = vtn_untyped_value(b, w[3]);
3004 image.image = vtn_get_image(b, w[3]);
3005 image.coord = NULL;
3006 image.sample = NULL;
3007 image.lod = NULL;
3008 break;
3009
3010 case SpvOpImageRead: {
3011 res_val = vtn_untyped_value(b, w[3]);
3012 image.image = vtn_get_image(b, w[3]);
3013 image.coord = get_image_coord(b, w[4]);
3014
3015 const SpvImageOperandsMask operands =
3016 count > 5 ? w[5] : SpvImageOperandsMaskNone;
3017
3018 if (operands & SpvImageOperandsSampleMask) {
3019 uint32_t arg = image_operand_arg(b, w, count, 5,
3020 SpvImageOperandsSampleMask);
3021 image.sample = vtn_get_nir_ssa(b, w[arg]);
3022 } else {
3023 image.sample = nir_ssa_undef(&b->nb, 1, 32);
3024 }
3025
3026 if (operands & SpvImageOperandsMakeTexelVisibleMask) {
3027 vtn_fail_if((operands & SpvImageOperandsNonPrivateTexelMask) == 0,
3028 "MakeTexelVisible requires NonPrivateTexel to also be set.");
3029 uint32_t arg = image_operand_arg(b, w, count, 5,
3030 SpvImageOperandsMakeTexelVisibleMask);
3031 semantics = SpvMemorySemanticsMakeVisibleMask;
3032 scope = vtn_constant_uint(b, w[arg]);
3033 }
3034
3035 if (operands & SpvImageOperandsLodMask) {
3036 uint32_t arg = image_operand_arg(b, w, count, 5,
3037 SpvImageOperandsLodMask);
3038 image.lod = vtn_get_nir_ssa(b, w[arg]);
3039 } else {
3040 image.lod = nir_imm_int(&b->nb, 0);
3041 }
3042
3043 /* TODO: Volatile. */
3044
3045 break;
3046 }
3047
3048 case SpvOpImageWrite: {
3049 res_val = vtn_untyped_value(b, w[1]);
3050 image.image = vtn_get_image(b, w[1]);
3051 image.coord = get_image_coord(b, w[2]);
3052
3053 /* texel = w[3] */
3054
3055 const SpvImageOperandsMask operands =
3056 count > 4 ? w[4] : SpvImageOperandsMaskNone;
3057
3058 if (operands & SpvImageOperandsSampleMask) {
3059 uint32_t arg = image_operand_arg(b, w, count, 4,
3060 SpvImageOperandsSampleMask);
3061 image.sample = vtn_get_nir_ssa(b, w[arg]);
3062 } else {
3063 image.sample = nir_ssa_undef(&b->nb, 1, 32);
3064 }
3065
3066 if (operands & SpvImageOperandsMakeTexelAvailableMask) {
3067 vtn_fail_if((operands & SpvImageOperandsNonPrivateTexelMask) == 0,
3068 "MakeTexelAvailable requires NonPrivateTexel to also be set.");
3069 uint32_t arg = image_operand_arg(b, w, count, 4,
3070 SpvImageOperandsMakeTexelAvailableMask);
3071 semantics = SpvMemorySemanticsMakeAvailableMask;
3072 scope = vtn_constant_uint(b, w[arg]);
3073 }
3074
3075 if (operands & SpvImageOperandsLodMask) {
3076 uint32_t arg = image_operand_arg(b, w, count, 4,
3077 SpvImageOperandsLodMask);
3078 image.lod = vtn_get_nir_ssa(b, w[arg]);
3079 } else {
3080 image.lod = nir_imm_int(&b->nb, 0);
3081 }
3082
3083 /* TODO: Volatile. */
3084
3085 break;
3086 }
3087
3088 default:
3089 vtn_fail_with_opcode("Invalid image opcode", opcode);
3090 }
3091
3092 nir_intrinsic_op op;
3093 switch (opcode) {
3094 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_deref_##N; break;
3095 OP(ImageQuerySize, size)
3096 OP(ImageQuerySizeLod, size)
3097 OP(ImageRead, load)
3098 OP(ImageWrite, store)
3099 OP(AtomicLoad, load)
3100 OP(AtomicStore, store)
3101 OP(AtomicExchange, atomic_exchange)
3102 OP(AtomicCompareExchange, atomic_comp_swap)
3103 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
3104 OP(AtomicIIncrement, atomic_add)
3105 OP(AtomicIDecrement, atomic_add)
3106 OP(AtomicIAdd, atomic_add)
3107 OP(AtomicISub, atomic_add)
3108 OP(AtomicSMin, atomic_imin)
3109 OP(AtomicUMin, atomic_umin)
3110 OP(AtomicSMax, atomic_imax)
3111 OP(AtomicUMax, atomic_umax)
3112 OP(AtomicAnd, atomic_and)
3113 OP(AtomicOr, atomic_or)
3114 OP(AtomicXor, atomic_xor)
3115 OP(AtomicFAddEXT, atomic_fadd)
3116 OP(ImageQueryFormat, format)
3117 OP(ImageQueryOrder, order)
3118 #undef OP
3119 default:
3120 vtn_fail_with_opcode("Invalid image opcode", opcode);
3121 }
3122
3123 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
3124
3125 intrin->src[0] = nir_src_for_ssa(&image.image->dest.ssa);
3126
3127 switch (opcode) {
3128 case SpvOpImageQuerySize:
3129 case SpvOpImageQuerySizeLod:
3130 case SpvOpImageQueryFormat:
3131 case SpvOpImageQueryOrder:
3132 break;
3133 default:
3134 /* The image coordinate is always 4 components but we may not have that
3135 * many. Swizzle to compensate.
3136 */
3137 intrin->src[1] = nir_src_for_ssa(expand_to_vec4(&b->nb, image.coord));
3138 intrin->src[2] = nir_src_for_ssa(image.sample);
3139 break;
3140 }
3141
3142 /* The Vulkan spec says:
3143 *
3144 * "If an instruction loads from or stores to a resource (including
3145 * atomics and image instructions) and the resource descriptor being
3146 * accessed is not dynamically uniform, then the operand corresponding
3147 * to that resource (e.g. the pointer or sampled image operand) must be
3148 * decorated with NonUniform."
3149 *
3150 * It's very careful to specify that the exact operand must be decorated
3151 * NonUniform. The SPIR-V parser is not expected to chase through long
3152 * chains to find the NonUniform decoration. It's either right there or we
3153 * can assume it doesn't exist.
3154 */
3155 vtn_foreach_decoration(b, res_val, non_uniform_decoration_cb, &access);
3156 nir_intrinsic_set_access(intrin, access);
3157
3158 switch (opcode) {
3159 case SpvOpImageQueryFormat:
3160 case SpvOpImageQueryOrder:
3161 /* No additional sources */
3162 break;
3163 case SpvOpImageQuerySize:
3164 intrin->src[1] = nir_src_for_ssa(nir_imm_int(&b->nb, 0));
3165 break;
3166 case SpvOpImageQuerySizeLod:
3167 intrin->src[1] = nir_src_for_ssa(image.lod);
3168 break;
3169 case SpvOpAtomicLoad:
3170 case SpvOpImageRead:
3171 /* Only OpImageRead can support a lod parameter if
3172 * SPV_AMD_shader_image_load_store_lod is used but the current NIR
3173 * intrinsics definition for atomics requires us to set it for
3174 * OpAtomicLoad.
3175 */
3176 intrin->src[3] = nir_src_for_ssa(image.lod);
3177 break;
3178 case SpvOpAtomicStore:
3179 case SpvOpImageWrite: {
3180 const uint32_t value_id = opcode == SpvOpAtomicStore ? w[4] : w[3];
3181 struct vtn_ssa_value *value = vtn_ssa_value(b, value_id);
3182 /* nir_intrinsic_image_deref_store always takes a vec4 value */
3183 assert(op == nir_intrinsic_image_deref_store);
3184 intrin->num_components = 4;
3185 intrin->src[3] = nir_src_for_ssa(expand_to_vec4(&b->nb, value->def));
3186 /* Only OpImageWrite can support a lod parameter if
3187 * SPV_AMD_shader_image_load_store_lod is used but the current NIR
3188 * intrinsics definition for atomics requires us to set it for
3189 * OpAtomicStore.
3190 */
3191 intrin->src[4] = nir_src_for_ssa(image.lod);
3192
3193 if (opcode == SpvOpImageWrite)
3194 nir_intrinsic_set_type(intrin, nir_get_nir_type_for_glsl_type(value->type));
3195 break;
3196 }
3197
3198 case SpvOpAtomicCompareExchange:
3199 case SpvOpAtomicCompareExchangeWeak:
3200 case SpvOpAtomicIIncrement:
3201 case SpvOpAtomicIDecrement:
3202 case SpvOpAtomicExchange:
3203 case SpvOpAtomicIAdd:
3204 case SpvOpAtomicISub:
3205 case SpvOpAtomicSMin:
3206 case SpvOpAtomicUMin:
3207 case SpvOpAtomicSMax:
3208 case SpvOpAtomicUMax:
3209 case SpvOpAtomicAnd:
3210 case SpvOpAtomicOr:
3211 case SpvOpAtomicXor:
3212 case SpvOpAtomicFAddEXT:
3213 fill_common_atomic_sources(b, opcode, w, &intrin->src[3]);
3214 break;
3215
3216 default:
3217 vtn_fail_with_opcode("Invalid image opcode", opcode);
3218 }
3219
3220 /* Image operations implicitly have the Image storage memory semantics. */
3221 semantics |= SpvMemorySemanticsImageMemoryMask;
3222
3223 SpvMemorySemanticsMask before_semantics;
3224 SpvMemorySemanticsMask after_semantics;
3225 vtn_split_barrier_semantics(b, semantics, &before_semantics, &after_semantics);
3226
3227 if (before_semantics)
3228 vtn_emit_memory_barrier(b, scope, before_semantics);
3229
3230 if (opcode != SpvOpImageWrite && opcode != SpvOpAtomicStore) {
3231 struct vtn_type *type = vtn_get_type(b, w[1]);
3232
3233 unsigned dest_components = glsl_get_vector_elements(type->type);
3234 if (nir_intrinsic_infos[op].dest_components == 0)
3235 intrin->num_components = dest_components;
3236
3237 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
3238 nir_intrinsic_dest_components(intrin), 32, NULL);
3239
3240 nir_builder_instr_insert(&b->nb, &intrin->instr);
3241
3242 nir_ssa_def *result = &intrin->dest.ssa;
3243 if (nir_intrinsic_dest_components(intrin) != dest_components)
3244 result = nir_channels(&b->nb, result, (1 << dest_components) - 1);
3245
3246 vtn_push_nir_ssa(b, w[2], result);
3247
3248 if (opcode == SpvOpImageRead)
3249 nir_intrinsic_set_type(intrin, nir_get_nir_type_for_glsl_type(type->type));
3250 } else {
3251 nir_builder_instr_insert(&b->nb, &intrin->instr);
3252 }
3253
3254 if (after_semantics)
3255 vtn_emit_memory_barrier(b, scope, after_semantics);
3256 }
3257
3258 static nir_intrinsic_op
3259 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
3260 {
3261 switch (opcode) {
3262 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
3263 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
3264 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
3265 OP(AtomicExchange, atomic_exchange)
3266 OP(AtomicCompareExchange, atomic_comp_swap)
3267 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
3268 OP(AtomicIIncrement, atomic_add)
3269 OP(AtomicIDecrement, atomic_add)
3270 OP(AtomicIAdd, atomic_add)
3271 OP(AtomicISub, atomic_add)
3272 OP(AtomicSMin, atomic_imin)
3273 OP(AtomicUMin, atomic_umin)
3274 OP(AtomicSMax, atomic_imax)
3275 OP(AtomicUMax, atomic_umax)
3276 OP(AtomicAnd, atomic_and)
3277 OP(AtomicOr, atomic_or)
3278 OP(AtomicXor, atomic_xor)
3279 OP(AtomicFAddEXT, atomic_fadd)
3280 #undef OP
3281 default:
3282 vtn_fail_with_opcode("Invalid SSBO atomic", opcode);
3283 }
3284 }
3285
3286 static nir_intrinsic_op
3287 get_uniform_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
3288 {
3289 switch (opcode) {
3290 #define OP(S, N) case SpvOp##S: return nir_intrinsic_atomic_counter_ ##N;
3291 OP(AtomicLoad, read_deref)
3292 OP(AtomicExchange, exchange)
3293 OP(AtomicCompareExchange, comp_swap)
3294 OP(AtomicCompareExchangeWeak, comp_swap)
3295 OP(AtomicIIncrement, inc_deref)
3296 OP(AtomicIDecrement, post_dec_deref)
3297 OP(AtomicIAdd, add_deref)
3298 OP(AtomicISub, add_deref)
3299 OP(AtomicUMin, min_deref)
3300 OP(AtomicUMax, max_deref)
3301 OP(AtomicAnd, and_deref)
3302 OP(AtomicOr, or_deref)
3303 OP(AtomicXor, xor_deref)
3304 #undef OP
3305 default:
3306 /* We left the following out: AtomicStore, AtomicSMin and
3307 * AtomicSmax. Right now there are not nir intrinsics for them. At this
3308 * moment Atomic Counter support is needed for ARB_spirv support, so is
3309 * only need to support GLSL Atomic Counters that are uints and don't
3310 * allow direct storage.
3311 */
3312 vtn_fail("Invalid uniform atomic");
3313 }
3314 }
3315
3316 static nir_intrinsic_op
3317 get_deref_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
3318 {
3319 switch (opcode) {
3320 case SpvOpAtomicLoad: return nir_intrinsic_load_deref;
3321 case SpvOpAtomicStore: return nir_intrinsic_store_deref;
3322 #define OP(S, N) case SpvOp##S: return nir_intrinsic_deref_##N;
3323 OP(AtomicExchange, atomic_exchange)
3324 OP(AtomicCompareExchange, atomic_comp_swap)
3325 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
3326 OP(AtomicIIncrement, atomic_add)
3327 OP(AtomicIDecrement, atomic_add)
3328 OP(AtomicIAdd, atomic_add)
3329 OP(AtomicISub, atomic_add)
3330 OP(AtomicSMin, atomic_imin)
3331 OP(AtomicUMin, atomic_umin)
3332 OP(AtomicSMax, atomic_imax)
3333 OP(AtomicUMax, atomic_umax)
3334 OP(AtomicAnd, atomic_and)
3335 OP(AtomicOr, atomic_or)
3336 OP(AtomicXor, atomic_xor)
3337 OP(AtomicFAddEXT, atomic_fadd)
3338 #undef OP
3339 default:
3340 vtn_fail_with_opcode("Invalid shared atomic", opcode);
3341 }
3342 }
3343
3344 /*
3345 * Handles shared atomics, ssbo atomics and atomic counters.
3346 */
3347 static void
3348 vtn_handle_atomics(struct vtn_builder *b, SpvOp opcode,
3349 const uint32_t *w, UNUSED unsigned count)
3350 {
3351 struct vtn_pointer *ptr;
3352 nir_intrinsic_instr *atomic;
3353
3354 SpvScope scope = SpvScopeInvocation;
3355 SpvMemorySemanticsMask semantics = 0;
3356
3357 switch (opcode) {
3358 case SpvOpAtomicLoad:
3359 case SpvOpAtomicExchange:
3360 case SpvOpAtomicCompareExchange:
3361 case SpvOpAtomicCompareExchangeWeak:
3362 case SpvOpAtomicIIncrement:
3363 case SpvOpAtomicIDecrement:
3364 case SpvOpAtomicIAdd:
3365 case SpvOpAtomicISub:
3366 case SpvOpAtomicSMin:
3367 case SpvOpAtomicUMin:
3368 case SpvOpAtomicSMax:
3369 case SpvOpAtomicUMax:
3370 case SpvOpAtomicAnd:
3371 case SpvOpAtomicOr:
3372 case SpvOpAtomicXor:
3373 case SpvOpAtomicFAddEXT:
3374 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3375 scope = vtn_constant_uint(b, w[4]);
3376 semantics = vtn_constant_uint(b, w[5]);
3377 break;
3378
3379 case SpvOpAtomicStore:
3380 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
3381 scope = vtn_constant_uint(b, w[2]);
3382 semantics = vtn_constant_uint(b, w[3]);
3383 break;
3384
3385 default:
3386 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3387 }
3388
3389 /* uniform as "atomic counter uniform" */
3390 if (ptr->mode == vtn_variable_mode_atomic_counter) {
3391 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
3392 nir_intrinsic_op op = get_uniform_nir_atomic_op(b, opcode);
3393 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3394 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
3395
3396 /* SSBO needs to initialize index/offset. In this case we don't need to,
3397 * as that info is already stored on the ptr->var->var nir_variable (see
3398 * vtn_create_variable)
3399 */
3400
3401 switch (opcode) {
3402 case SpvOpAtomicLoad:
3403 case SpvOpAtomicExchange:
3404 case SpvOpAtomicCompareExchange:
3405 case SpvOpAtomicCompareExchangeWeak:
3406 case SpvOpAtomicIIncrement:
3407 case SpvOpAtomicIDecrement:
3408 case SpvOpAtomicIAdd:
3409 case SpvOpAtomicISub:
3410 case SpvOpAtomicSMin:
3411 case SpvOpAtomicUMin:
3412 case SpvOpAtomicSMax:
3413 case SpvOpAtomicUMax:
3414 case SpvOpAtomicAnd:
3415 case SpvOpAtomicOr:
3416 case SpvOpAtomicXor:
3417 /* Nothing: we don't need to call fill_common_atomic_sources here, as
3418 * atomic counter uniforms doesn't have sources
3419 */
3420 break;
3421
3422 default:
3423 unreachable("Invalid SPIR-V atomic");
3424
3425 }
3426 } else if (vtn_pointer_uses_ssa_offset(b, ptr)) {
3427 nir_ssa_def *offset, *index;
3428 offset = vtn_pointer_to_offset(b, ptr, &index);
3429
3430 assert(ptr->mode == vtn_variable_mode_ssbo);
3431
3432 nir_intrinsic_op op = get_ssbo_nir_atomic_op(b, opcode);
3433 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3434
3435 nir_intrinsic_set_access(atomic, ACCESS_COHERENT);
3436
3437 int src = 0;
3438 switch (opcode) {
3439 case SpvOpAtomicLoad:
3440 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
3441 nir_intrinsic_set_align(atomic, 4, 0);
3442 if (ptr->mode == vtn_variable_mode_ssbo)
3443 atomic->src[src++] = nir_src_for_ssa(index);
3444 atomic->src[src++] = nir_src_for_ssa(offset);
3445 break;
3446
3447 case SpvOpAtomicStore:
3448 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
3449 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
3450 nir_intrinsic_set_align(atomic, 4, 0);
3451 atomic->src[src++] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[4]));
3452 if (ptr->mode == vtn_variable_mode_ssbo)
3453 atomic->src[src++] = nir_src_for_ssa(index);
3454 atomic->src[src++] = nir_src_for_ssa(offset);
3455 break;
3456
3457 case SpvOpAtomicExchange:
3458 case SpvOpAtomicCompareExchange:
3459 case SpvOpAtomicCompareExchangeWeak:
3460 case SpvOpAtomicIIncrement:
3461 case SpvOpAtomicIDecrement:
3462 case SpvOpAtomicIAdd:
3463 case SpvOpAtomicISub:
3464 case SpvOpAtomicSMin:
3465 case SpvOpAtomicUMin:
3466 case SpvOpAtomicSMax:
3467 case SpvOpAtomicUMax:
3468 case SpvOpAtomicAnd:
3469 case SpvOpAtomicOr:
3470 case SpvOpAtomicXor:
3471 case SpvOpAtomicFAddEXT:
3472 if (ptr->mode == vtn_variable_mode_ssbo)
3473 atomic->src[src++] = nir_src_for_ssa(index);
3474 atomic->src[src++] = nir_src_for_ssa(offset);
3475 fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
3476 break;
3477
3478 default:
3479 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3480 }
3481 } else {
3482 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
3483 const struct glsl_type *deref_type = deref->type;
3484 nir_intrinsic_op op = get_deref_nir_atomic_op(b, opcode);
3485 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3486 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
3487
3488 if (ptr->mode != vtn_variable_mode_workgroup)
3489 nir_intrinsic_set_access(atomic, ACCESS_COHERENT);
3490
3491 switch (opcode) {
3492 case SpvOpAtomicLoad:
3493 atomic->num_components = glsl_get_vector_elements(deref_type);
3494 break;
3495
3496 case SpvOpAtomicStore:
3497 atomic->num_components = glsl_get_vector_elements(deref_type);
3498 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
3499 atomic->src[1] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[4]));
3500 break;
3501
3502 case SpvOpAtomicExchange:
3503 case SpvOpAtomicCompareExchange:
3504 case SpvOpAtomicCompareExchangeWeak:
3505 case SpvOpAtomicIIncrement:
3506 case SpvOpAtomicIDecrement:
3507 case SpvOpAtomicIAdd:
3508 case SpvOpAtomicISub:
3509 case SpvOpAtomicSMin:
3510 case SpvOpAtomicUMin:
3511 case SpvOpAtomicSMax:
3512 case SpvOpAtomicUMax:
3513 case SpvOpAtomicAnd:
3514 case SpvOpAtomicOr:
3515 case SpvOpAtomicXor:
3516 case SpvOpAtomicFAddEXT:
3517 fill_common_atomic_sources(b, opcode, w, &atomic->src[1]);
3518 break;
3519
3520 default:
3521 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3522 }
3523 }
3524
3525 /* Atomic ordering operations will implicitly apply to the atomic operation
3526 * storage class, so include that too.
3527 */
3528 semantics |= vtn_mode_to_memory_semantics(ptr->mode);
3529
3530 SpvMemorySemanticsMask before_semantics;
3531 SpvMemorySemanticsMask after_semantics;
3532 vtn_split_barrier_semantics(b, semantics, &before_semantics, &after_semantics);
3533
3534 if (before_semantics)
3535 vtn_emit_memory_barrier(b, scope, before_semantics);
3536
3537 if (opcode != SpvOpAtomicStore) {
3538 struct vtn_type *type = vtn_get_type(b, w[1]);
3539
3540 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
3541 glsl_get_vector_elements(type->type),
3542 glsl_get_bit_size(type->type), NULL);
3543
3544 vtn_push_nir_ssa(b, w[2], &atomic->dest.ssa);
3545 }
3546
3547 nir_builder_instr_insert(&b->nb, &atomic->instr);
3548
3549 if (after_semantics)
3550 vtn_emit_memory_barrier(b, scope, after_semantics);
3551 }
3552
3553 static nir_alu_instr *
3554 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
3555 {
3556 nir_op op = nir_op_vec(num_components);
3557 nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
3558 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
3559 bit_size, NULL);
3560 vec->dest.write_mask = (1 << num_components) - 1;
3561
3562 return vec;
3563 }
3564
3565 struct vtn_ssa_value *
3566 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
3567 {
3568 if (src->transposed)
3569 return src->transposed;
3570
3571 struct vtn_ssa_value *dest =
3572 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
3573
3574 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
3575 nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
3576 glsl_get_bit_size(src->type));
3577 if (glsl_type_is_vector_or_scalar(src->type)) {
3578 vec->src[0].src = nir_src_for_ssa(src->def);
3579 vec->src[0].swizzle[0] = i;
3580 } else {
3581 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
3582 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
3583 vec->src[j].swizzle[0] = i;
3584 }
3585 }
3586 nir_builder_instr_insert(&b->nb, &vec->instr);
3587 dest->elems[i]->def = &vec->dest.dest.ssa;
3588 }
3589
3590 dest->transposed = src;
3591
3592 return dest;
3593 }
3594
3595 static nir_ssa_def *
3596 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
3597 nir_ssa_def *src0, nir_ssa_def *src1,
3598 const uint32_t *indices)
3599 {
3600 nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
3601
3602 for (unsigned i = 0; i < num_components; i++) {
3603 uint32_t index = indices[i];
3604 if (index == 0xffffffff) {
3605 vec->src[i].src =
3606 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
3607 } else if (index < src0->num_components) {
3608 vec->src[i].src = nir_src_for_ssa(src0);
3609 vec->src[i].swizzle[0] = index;
3610 } else {
3611 vec->src[i].src = nir_src_for_ssa(src1);
3612 vec->src[i].swizzle[0] = index - src0->num_components;
3613 }
3614 }
3615
3616 nir_builder_instr_insert(&b->nb, &vec->instr);
3617
3618 return &vec->dest.dest.ssa;
3619 }
3620
3621 /*
3622 * Concatentates a number of vectors/scalars together to produce a vector
3623 */
3624 static nir_ssa_def *
3625 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
3626 unsigned num_srcs, nir_ssa_def **srcs)
3627 {
3628 nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
3629
3630 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3631 *
3632 * "When constructing a vector, there must be at least two Constituent
3633 * operands."
3634 */
3635 vtn_assert(num_srcs >= 2);
3636
3637 unsigned dest_idx = 0;
3638 for (unsigned i = 0; i < num_srcs; i++) {
3639 nir_ssa_def *src = srcs[i];
3640 vtn_assert(dest_idx + src->num_components <= num_components);
3641 for (unsigned j = 0; j < src->num_components; j++) {
3642 vec->src[dest_idx].src = nir_src_for_ssa(src);
3643 vec->src[dest_idx].swizzle[0] = j;
3644 dest_idx++;
3645 }
3646 }
3647
3648 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3649 *
3650 * "When constructing a vector, the total number of components in all
3651 * the operands must equal the number of components in Result Type."
3652 */
3653 vtn_assert(dest_idx == num_components);
3654
3655 nir_builder_instr_insert(&b->nb, &vec->instr);
3656
3657 return &vec->dest.dest.ssa;
3658 }
3659
3660 static struct vtn_ssa_value *
3661 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
3662 {
3663 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
3664 dest->type = src->type;
3665
3666 if (glsl_type_is_vector_or_scalar(src->type)) {
3667 dest->def = src->def;
3668 } else {
3669 unsigned elems = glsl_get_length(src->type);
3670
3671 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
3672 for (unsigned i = 0; i < elems; i++)
3673 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
3674 }
3675
3676 return dest;
3677 }
3678
3679 static struct vtn_ssa_value *
3680 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
3681 struct vtn_ssa_value *insert, const uint32_t *indices,
3682 unsigned num_indices)
3683 {
3684 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
3685
3686 struct vtn_ssa_value *cur = dest;
3687 unsigned i;
3688 for (i = 0; i < num_indices - 1; i++) {
3689 /* If we got a vector here, that means the next index will be trying to
3690 * dereference a scalar.
3691 */
3692 vtn_fail_if(glsl_type_is_vector_or_scalar(cur->type),
3693 "OpCompositeInsert has too many indices.");
3694 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3695 "All indices in an OpCompositeInsert must be in-bounds");
3696 cur = cur->elems[indices[i]];
3697 }
3698
3699 if (glsl_type_is_vector_or_scalar(cur->type)) {
3700 vtn_fail_if(indices[i] >= glsl_get_vector_elements(cur->type),
3701 "All indices in an OpCompositeInsert must be in-bounds");
3702
3703 /* According to the SPIR-V spec, OpCompositeInsert may work down to
3704 * the component granularity. In that case, the last index will be
3705 * the index to insert the scalar into the vector.
3706 */
3707
3708 cur->def = nir_vector_insert_imm(&b->nb, cur->def, insert->def, indices[i]);
3709 } else {
3710 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3711 "All indices in an OpCompositeInsert must be in-bounds");
3712 cur->elems[indices[i]] = insert;
3713 }
3714
3715 return dest;
3716 }
3717
3718 static struct vtn_ssa_value *
3719 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
3720 const uint32_t *indices, unsigned num_indices)
3721 {
3722 struct vtn_ssa_value *cur = src;
3723 for (unsigned i = 0; i < num_indices; i++) {
3724 if (glsl_type_is_vector_or_scalar(cur->type)) {
3725 vtn_assert(i == num_indices - 1);
3726 vtn_fail_if(indices[i] >= glsl_get_vector_elements(cur->type),
3727 "All indices in an OpCompositeExtract must be in-bounds");
3728
3729 /* According to the SPIR-V spec, OpCompositeExtract may work down to
3730 * the component granularity. The last index will be the index of the
3731 * vector to extract.
3732 */
3733
3734 const struct glsl_type *scalar_type =
3735 glsl_scalar_type(glsl_get_base_type(cur->type));
3736 struct vtn_ssa_value *ret = vtn_create_ssa_value(b, scalar_type);
3737 ret->def = nir_channel(&b->nb, cur->def, indices[i]);
3738 return ret;
3739 } else {
3740 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3741 "All indices in an OpCompositeExtract must be in-bounds");
3742 cur = cur->elems[indices[i]];
3743 }
3744 }
3745
3746 return cur;
3747 }
3748
3749 static void
3750 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
3751 const uint32_t *w, unsigned count)
3752 {
3753 struct vtn_type *type = vtn_get_type(b, w[1]);
3754 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, type->type);
3755
3756 switch (opcode) {
3757 case SpvOpVectorExtractDynamic:
3758 ssa->def = nir_vector_extract(&b->nb, vtn_get_nir_ssa(b, w[3]),
3759 vtn_get_nir_ssa(b, w[4]));
3760 break;
3761
3762 case SpvOpVectorInsertDynamic:
3763 ssa->def = nir_vector_insert(&b->nb, vtn_get_nir_ssa(b, w[3]),
3764 vtn_get_nir_ssa(b, w[4]),
3765 vtn_get_nir_ssa(b, w[5]));
3766 break;
3767
3768 case SpvOpVectorShuffle:
3769 ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type->type),
3770 vtn_get_nir_ssa(b, w[3]),
3771 vtn_get_nir_ssa(b, w[4]),
3772 w + 5);
3773 break;
3774
3775 case SpvOpCompositeConstruct: {
3776 unsigned elems = count - 3;
3777 assume(elems >= 1);
3778 if (glsl_type_is_vector_or_scalar(type->type)) {
3779 nir_ssa_def *srcs[NIR_MAX_VEC_COMPONENTS];
3780 for (unsigned i = 0; i < elems; i++)
3781 srcs[i] = vtn_get_nir_ssa(b, w[3 + i]);
3782 ssa->def =
3783 vtn_vector_construct(b, glsl_get_vector_elements(type->type),
3784 elems, srcs);
3785 } else {
3786 ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
3787 for (unsigned i = 0; i < elems; i++)
3788 ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
3789 }
3790 break;
3791 }
3792 case SpvOpCompositeExtract:
3793 ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
3794 w + 4, count - 4);
3795 break;
3796
3797 case SpvOpCompositeInsert:
3798 ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
3799 vtn_ssa_value(b, w[3]),
3800 w + 5, count - 5);
3801 break;
3802
3803 case SpvOpCopyLogical:
3804 ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
3805 break;
3806 case SpvOpCopyObject:
3807 vtn_copy_value(b, w[3], w[2]);
3808 return;
3809
3810 default:
3811 vtn_fail_with_opcode("unknown composite operation", opcode);
3812 }
3813
3814 vtn_push_ssa_value(b, w[2], ssa);
3815 }
3816
3817 static void
3818 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
3819 {
3820 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
3821 nir_builder_instr_insert(&b->nb, &intrin->instr);
3822 }
3823
3824 void
3825 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
3826 SpvMemorySemanticsMask semantics)
3827 {
3828 if (b->shader->options->use_scoped_barrier) {
3829 vtn_emit_scoped_memory_barrier(b, scope, semantics);
3830 return;
3831 }
3832
3833 static const SpvMemorySemanticsMask all_memory_semantics =
3834 SpvMemorySemanticsUniformMemoryMask |
3835 SpvMemorySemanticsWorkgroupMemoryMask |
3836 SpvMemorySemanticsAtomicCounterMemoryMask |
3837 SpvMemorySemanticsImageMemoryMask |
3838 SpvMemorySemanticsOutputMemoryMask;
3839
3840 /* If we're not actually doing a memory barrier, bail */
3841 if (!(semantics & all_memory_semantics))
3842 return;
3843
3844 /* GL and Vulkan don't have these */
3845 vtn_assert(scope != SpvScopeCrossDevice);
3846
3847 if (scope == SpvScopeSubgroup)
3848 return; /* Nothing to do here */
3849
3850 if (scope == SpvScopeWorkgroup) {
3851 vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
3852 return;
3853 }
3854
3855 /* There's only two scopes thing left */
3856 vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
3857
3858 /* Map the GLSL memoryBarrier() construct and any barriers with more than one
3859 * semantic to the corresponding NIR one.
3860 */
3861 if (util_bitcount(semantics & all_memory_semantics) > 1) {
3862 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3863 if (semantics & SpvMemorySemanticsOutputMemoryMask) {
3864 /* GLSL memoryBarrier() (and the corresponding NIR one) doesn't include
3865 * TCS outputs, so we have to emit it's own intrinsic for that. We
3866 * then need to emit another memory_barrier to prevent moving
3867 * non-output operations to before the tcs_patch barrier.
3868 */
3869 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_tcs_patch);
3870 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3871 }
3872 return;
3873 }
3874
3875 /* Issue a more specific barrier */
3876 switch (semantics & all_memory_semantics) {
3877 case SpvMemorySemanticsUniformMemoryMask:
3878 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3879 break;
3880 case SpvMemorySemanticsWorkgroupMemoryMask:
3881 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3882 break;
3883 case SpvMemorySemanticsAtomicCounterMemoryMask:
3884 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3885 break;
3886 case SpvMemorySemanticsImageMemoryMask:
3887 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3888 break;
3889 case SpvMemorySemanticsOutputMemoryMask:
3890 if (b->nb.shader->info.stage == MESA_SHADER_TESS_CTRL)
3891 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_tcs_patch);
3892 break;
3893 default:
3894 break;
3895 }
3896 }
3897
3898 static void
3899 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3900 const uint32_t *w, UNUSED unsigned count)
3901 {
3902 switch (opcode) {
3903 case SpvOpEmitVertex:
3904 case SpvOpEmitStreamVertex:
3905 case SpvOpEndPrimitive:
3906 case SpvOpEndStreamPrimitive: {
3907 nir_intrinsic_op intrinsic_op;
3908 switch (opcode) {
3909 case SpvOpEmitVertex:
3910 case SpvOpEmitStreamVertex:
3911 intrinsic_op = nir_intrinsic_emit_vertex;
3912 break;
3913 case SpvOpEndPrimitive:
3914 case SpvOpEndStreamPrimitive:
3915 intrinsic_op = nir_intrinsic_end_primitive;
3916 break;
3917 default:
3918 unreachable("Invalid opcode");
3919 }
3920
3921 nir_intrinsic_instr *intrin =
3922 nir_intrinsic_instr_create(b->shader, intrinsic_op);
3923
3924 switch (opcode) {
3925 case SpvOpEmitStreamVertex:
3926 case SpvOpEndStreamPrimitive: {
3927 unsigned stream = vtn_constant_uint(b, w[1]);
3928 nir_intrinsic_set_stream_id(intrin, stream);
3929 break;
3930 }
3931
3932 default:
3933 break;
3934 }
3935
3936 nir_builder_instr_insert(&b->nb, &intrin->instr);
3937 break;
3938 }
3939
3940 case SpvOpMemoryBarrier: {
3941 SpvScope scope = vtn_constant_uint(b, w[1]);
3942 SpvMemorySemanticsMask semantics = vtn_constant_uint(b, w[2]);
3943 vtn_emit_memory_barrier(b, scope, semantics);
3944 return;
3945 }
3946
3947 case SpvOpControlBarrier: {
3948 SpvScope execution_scope = vtn_constant_uint(b, w[1]);
3949 SpvScope memory_scope = vtn_constant_uint(b, w[2]);
3950 SpvMemorySemanticsMask memory_semantics = vtn_constant_uint(b, w[3]);
3951
3952 /* GLSLang, prior to commit 8297936dd6eb3, emitted OpControlBarrier with
3953 * memory semantics of None for GLSL barrier().
3954 * And before that, prior to c3f1cdfa, emitted the OpControlBarrier with
3955 * Device instead of Workgroup for execution scope.
3956 */
3957 if (b->wa_glslang_cs_barrier &&
3958 b->nb.shader->info.stage == MESA_SHADER_COMPUTE &&
3959 (execution_scope == SpvScopeWorkgroup ||
3960 execution_scope == SpvScopeDevice) &&
3961 memory_semantics == SpvMemorySemanticsMaskNone) {
3962 execution_scope = SpvScopeWorkgroup;
3963 memory_scope = SpvScopeWorkgroup;
3964 memory_semantics = SpvMemorySemanticsAcquireReleaseMask |
3965 SpvMemorySemanticsWorkgroupMemoryMask;
3966 }
3967
3968 /* From the SPIR-V spec:
3969 *
3970 * "When used with the TessellationControl execution model, it also
3971 * implicitly synchronizes the Output Storage Class: Writes to Output
3972 * variables performed by any invocation executed prior to a
3973 * OpControlBarrier will be visible to any other invocation after
3974 * return from that OpControlBarrier."
3975 */
3976 if (b->nb.shader->info.stage == MESA_SHADER_TESS_CTRL) {
3977 memory_semantics &= ~(SpvMemorySemanticsAcquireMask |
3978 SpvMemorySemanticsReleaseMask |
3979 SpvMemorySemanticsAcquireReleaseMask |
3980 SpvMemorySemanticsSequentiallyConsistentMask);
3981 memory_semantics |= SpvMemorySemanticsAcquireReleaseMask |
3982 SpvMemorySemanticsOutputMemoryMask;
3983 }
3984
3985 if (b->shader->options->use_scoped_barrier) {
3986 vtn_emit_scoped_control_barrier(b, execution_scope, memory_scope,
3987 memory_semantics);
3988 } else {
3989 vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3990
3991 if (execution_scope == SpvScopeWorkgroup)
3992 vtn_emit_barrier(b, nir_intrinsic_control_barrier);
3993 }
3994 break;
3995 }
3996
3997 default:
3998 unreachable("unknown barrier instruction");
3999 }
4000 }
4001
4002 static unsigned
4003 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
4004 SpvExecutionMode mode)
4005 {
4006 switch (mode) {
4007 case SpvExecutionModeInputPoints:
4008 case SpvExecutionModeOutputPoints:
4009 return 0; /* GL_POINTS */
4010 case SpvExecutionModeInputLines:
4011 return 1; /* GL_LINES */
4012 case SpvExecutionModeInputLinesAdjacency:
4013 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
4014 case SpvExecutionModeTriangles:
4015 return 4; /* GL_TRIANGLES */
4016 case SpvExecutionModeInputTrianglesAdjacency:
4017 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
4018 case SpvExecutionModeQuads:
4019 return 7; /* GL_QUADS */
4020 case SpvExecutionModeIsolines:
4021 return 0x8E7A; /* GL_ISOLINES */
4022 case SpvExecutionModeOutputLineStrip:
4023 return 3; /* GL_LINE_STRIP */
4024 case SpvExecutionModeOutputTriangleStrip:
4025 return 5; /* GL_TRIANGLE_STRIP */
4026 default:
4027 vtn_fail("Invalid primitive type: %s (%u)",
4028 spirv_executionmode_to_string(mode), mode);
4029 }
4030 }
4031
4032 static unsigned
4033 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
4034 SpvExecutionMode mode)
4035 {
4036 switch (mode) {
4037 case SpvExecutionModeInputPoints:
4038 return 1;
4039 case SpvExecutionModeInputLines:
4040 return 2;
4041 case SpvExecutionModeInputLinesAdjacency:
4042 return 4;
4043 case SpvExecutionModeTriangles:
4044 return 3;
4045 case SpvExecutionModeInputTrianglesAdjacency:
4046 return 6;
4047 default:
4048 vtn_fail("Invalid GS input mode: %s (%u)",
4049 spirv_executionmode_to_string(mode), mode);
4050 }
4051 }
4052
4053 static gl_shader_stage
4054 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
4055 {
4056 switch (model) {
4057 case SpvExecutionModelVertex:
4058 return MESA_SHADER_VERTEX;
4059 case SpvExecutionModelTessellationControl:
4060 return MESA_SHADER_TESS_CTRL;
4061 case SpvExecutionModelTessellationEvaluation:
4062 return MESA_SHADER_TESS_EVAL;
4063 case SpvExecutionModelGeometry:
4064 return MESA_SHADER_GEOMETRY;
4065 case SpvExecutionModelFragment:
4066 return MESA_SHADER_FRAGMENT;
4067 case SpvExecutionModelGLCompute:
4068 return MESA_SHADER_COMPUTE;
4069 case SpvExecutionModelKernel:
4070 return MESA_SHADER_KERNEL;
4071 default:
4072 vtn_fail("Unsupported execution model: %s (%u)",
4073 spirv_executionmodel_to_string(model), model);
4074 }
4075 }
4076
4077 #define spv_check_supported(name, cap) do { \
4078 if (!(b->options && b->options->caps.name)) \
4079 vtn_warn("Unsupported SPIR-V capability: %s (%u)", \
4080 spirv_capability_to_string(cap), cap); \
4081 } while(0)
4082
4083
4084 void
4085 vtn_handle_entry_point(struct vtn_builder *b, const uint32_t *w,
4086 unsigned count)
4087 {
4088 struct vtn_value *entry_point = &b->values[w[2]];
4089 /* Let this be a name label regardless */
4090 unsigned name_words;
4091 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
4092
4093 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
4094 stage_for_execution_model(b, w[1]) != b->entry_point_stage)
4095 return;
4096
4097 vtn_assert(b->entry_point == NULL);
4098 b->entry_point = entry_point;
4099 }
4100
4101 static bool
4102 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
4103 const uint32_t *w, unsigned count)
4104 {
4105 switch (opcode) {
4106 case SpvOpSource: {
4107 const char *lang;
4108 switch (w[1]) {
4109 default:
4110 case SpvSourceLanguageUnknown: lang = "unknown"; break;
4111 case SpvSourceLanguageESSL: lang = "ESSL"; break;
4112 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
4113 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
4114 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
4115 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
4116 }
4117
4118 uint32_t version = w[2];
4119
4120 const char *file =
4121 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
4122
4123 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
4124 break;
4125 }
4126
4127 case SpvOpSourceExtension:
4128 case SpvOpSourceContinued:
4129 case SpvOpExtension:
4130 case SpvOpModuleProcessed:
4131 /* Unhandled, but these are for debug so that's ok. */
4132 break;
4133
4134 case SpvOpCapability: {
4135 SpvCapability cap = w[1];
4136 switch (cap) {
4137 case SpvCapabilityMatrix:
4138 case SpvCapabilityShader:
4139 case SpvCapabilityGeometry:
4140 case SpvCapabilityGeometryPointSize:
4141 case SpvCapabilityUniformBufferArrayDynamicIndexing:
4142 case SpvCapabilitySampledImageArrayDynamicIndexing:
4143 case SpvCapabilityStorageBufferArrayDynamicIndexing:
4144 case SpvCapabilityStorageImageArrayDynamicIndexing:
4145 case SpvCapabilityImageRect:
4146 case SpvCapabilitySampledRect:
4147 case SpvCapabilitySampled1D:
4148 case SpvCapabilityImage1D:
4149 case SpvCapabilitySampledCubeArray:
4150 case SpvCapabilityImageCubeArray:
4151 case SpvCapabilitySampledBuffer:
4152 case SpvCapabilityImageBuffer:
4153 case SpvCapabilityImageQuery:
4154 case SpvCapabilityDerivativeControl:
4155 case SpvCapabilityInterpolationFunction:
4156 case SpvCapabilityMultiViewport:
4157 case SpvCapabilitySampleRateShading:
4158 case SpvCapabilityClipDistance:
4159 case SpvCapabilityCullDistance:
4160 case SpvCapabilityInputAttachment:
4161 case SpvCapabilityImageGatherExtended:
4162 case SpvCapabilityStorageImageExtendedFormats:
4163 case SpvCapabilityVector16:
4164 break;
4165
4166 case SpvCapabilityLinkage:
4167 case SpvCapabilityFloat16Buffer:
4168 case SpvCapabilitySparseResidency:
4169 vtn_warn("Unsupported SPIR-V capability: %s",
4170 spirv_capability_to_string(cap));
4171 break;
4172
4173 case SpvCapabilityMinLod:
4174 spv_check_supported(min_lod, cap);
4175 break;
4176
4177 case SpvCapabilityAtomicStorage:
4178 spv_check_supported(atomic_storage, cap);
4179 break;
4180
4181 case SpvCapabilityFloat64:
4182 spv_check_supported(float64, cap);
4183 break;
4184 case SpvCapabilityInt64:
4185 spv_check_supported(int64, cap);
4186 break;
4187 case SpvCapabilityInt16:
4188 spv_check_supported(int16, cap);
4189 break;
4190 case SpvCapabilityInt8:
4191 spv_check_supported(int8, cap);
4192 break;
4193
4194 case SpvCapabilityTransformFeedback:
4195 spv_check_supported(transform_feedback, cap);
4196 break;
4197
4198 case SpvCapabilityGeometryStreams:
4199 spv_check_supported(geometry_streams, cap);
4200 break;
4201
4202 case SpvCapabilityInt64Atomics:
4203 spv_check_supported(int64_atomics, cap);
4204 break;
4205
4206 case SpvCapabilityStorageImageMultisample:
4207 spv_check_supported(storage_image_ms, cap);
4208 break;
4209
4210 case SpvCapabilityAddresses:
4211 spv_check_supported(address, cap);
4212 break;
4213
4214 case SpvCapabilityKernel:
4215 spv_check_supported(kernel, cap);
4216 break;
4217
4218 case SpvCapabilityImageBasic:
4219 spv_check_supported(kernel_image, cap);
4220 break;
4221
4222 case SpvCapabilityLiteralSampler:
4223 spv_check_supported(literal_sampler, cap);
4224 break;
4225
4226 case SpvCapabilityImageReadWrite:
4227 case SpvCapabilityImageMipmap:
4228 case SpvCapabilityPipes:
4229 case SpvCapabilityDeviceEnqueue:
4230 case SpvCapabilityGenericPointer:
4231 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
4232 spirv_capability_to_string(cap));
4233 break;
4234
4235 case SpvCapabilityImageMSArray:
4236 spv_check_supported(image_ms_array, cap);
4237 break;
4238
4239 case SpvCapabilityTessellation:
4240 case SpvCapabilityTessellationPointSize:
4241 spv_check_supported(tessellation, cap);
4242 break;
4243
4244 case SpvCapabilityDrawParameters:
4245 spv_check_supported(draw_parameters, cap);
4246 break;
4247
4248 case SpvCapabilityStorageImageReadWithoutFormat:
4249 spv_check_supported(image_read_without_format, cap);
4250 break;
4251
4252 case SpvCapabilityStorageImageWriteWithoutFormat:
4253 spv_check_supported(image_write_without_format, cap);
4254 break;
4255
4256 case SpvCapabilityDeviceGroup:
4257 spv_check_supported(device_group, cap);
4258 break;
4259
4260 case SpvCapabilityMultiView:
4261 spv_check_supported(multiview, cap);
4262 break;
4263
4264 case SpvCapabilityGroupNonUniform:
4265 spv_check_supported(subgroup_basic, cap);
4266 break;
4267
4268 case SpvCapabilitySubgroupVoteKHR:
4269 case SpvCapabilityGroupNonUniformVote:
4270 spv_check_supported(subgroup_vote, cap);
4271 break;
4272
4273 case SpvCapabilitySubgroupBallotKHR:
4274 case SpvCapabilityGroupNonUniformBallot:
4275 spv_check_supported(subgroup_ballot, cap);
4276 break;
4277
4278 case SpvCapabilityGroupNonUniformShuffle:
4279 case SpvCapabilityGroupNonUniformShuffleRelative:
4280 spv_check_supported(subgroup_shuffle, cap);
4281 break;
4282
4283 case SpvCapabilityGroupNonUniformQuad:
4284 spv_check_supported(subgroup_quad, cap);
4285 break;
4286
4287 case SpvCapabilityGroupNonUniformArithmetic:
4288 case SpvCapabilityGroupNonUniformClustered:
4289 spv_check_supported(subgroup_arithmetic, cap);
4290 break;
4291
4292 case SpvCapabilityGroups:
4293 spv_check_supported(amd_shader_ballot, cap);
4294 break;
4295
4296 case SpvCapabilityVariablePointersStorageBuffer:
4297 case SpvCapabilityVariablePointers:
4298 spv_check_supported(variable_pointers, cap);
4299 b->variable_pointers = true;
4300 break;
4301
4302 case SpvCapabilityStorageUniformBufferBlock16:
4303 case SpvCapabilityStorageUniform16:
4304 case SpvCapabilityStoragePushConstant16:
4305 case SpvCapabilityStorageInputOutput16:
4306 spv_check_supported(storage_16bit, cap);
4307 break;
4308
4309 case SpvCapabilityShaderLayer:
4310 case SpvCapabilityShaderViewportIndex:
4311 case SpvCapabilityShaderViewportIndexLayerEXT:
4312 spv_check_supported(shader_viewport_index_layer, cap);
4313 break;
4314
4315 case SpvCapabilityStorageBuffer8BitAccess:
4316 case SpvCapabilityUniformAndStorageBuffer8BitAccess:
4317 case SpvCapabilityStoragePushConstant8:
4318 spv_check_supported(storage_8bit, cap);
4319 break;
4320
4321 case SpvCapabilityShaderNonUniformEXT:
4322 spv_check_supported(descriptor_indexing, cap);
4323 break;
4324
4325 case SpvCapabilityInputAttachmentArrayDynamicIndexingEXT:
4326 case SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT:
4327 case SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT:
4328 spv_check_supported(descriptor_array_dynamic_indexing, cap);
4329 break;
4330
4331 case SpvCapabilityUniformBufferArrayNonUniformIndexingEXT:
4332 case SpvCapabilitySampledImageArrayNonUniformIndexingEXT:
4333 case SpvCapabilityStorageBufferArrayNonUniformIndexingEXT:
4334 case SpvCapabilityStorageImageArrayNonUniformIndexingEXT:
4335 case SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT:
4336 case SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT:
4337 case SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT:
4338 spv_check_supported(descriptor_array_non_uniform_indexing, cap);
4339 break;
4340
4341 case SpvCapabilityRuntimeDescriptorArrayEXT:
4342 spv_check_supported(runtime_descriptor_array, cap);
4343 break;
4344
4345 case SpvCapabilityStencilExportEXT:
4346 spv_check_supported(stencil_export, cap);
4347 break;
4348
4349 case SpvCapabilitySampleMaskPostDepthCoverage:
4350 spv_check_supported(post_depth_coverage, cap);
4351 break;
4352
4353 case SpvCapabilityDenormFlushToZero:
4354 case SpvCapabilityDenormPreserve:
4355 case SpvCapabilitySignedZeroInfNanPreserve:
4356 case SpvCapabilityRoundingModeRTE:
4357 case SpvCapabilityRoundingModeRTZ:
4358 spv_check_supported(float_controls, cap);
4359 break;
4360
4361 case SpvCapabilityPhysicalStorageBufferAddresses:
4362 spv_check_supported(physical_storage_buffer_address, cap);
4363 break;
4364
4365 case SpvCapabilityComputeDerivativeGroupQuadsNV:
4366 case SpvCapabilityComputeDerivativeGroupLinearNV:
4367 spv_check_supported(derivative_group, cap);
4368 break;
4369
4370 case SpvCapabilityFloat16:
4371 spv_check_supported(float16, cap);
4372 break;
4373
4374 case SpvCapabilityFragmentShaderSampleInterlockEXT:
4375 spv_check_supported(fragment_shader_sample_interlock, cap);
4376 break;
4377
4378 case SpvCapabilityFragmentShaderPixelInterlockEXT:
4379 spv_check_supported(fragment_shader_pixel_interlock, cap);
4380 break;
4381
4382 case SpvCapabilityDemoteToHelperInvocationEXT:
4383 spv_check_supported(demote_to_helper_invocation, cap);
4384 break;
4385
4386 case SpvCapabilityShaderClockKHR:
4387 spv_check_supported(shader_clock, cap);
4388 break;
4389
4390 case SpvCapabilityVulkanMemoryModel:
4391 spv_check_supported(vk_memory_model, cap);
4392 break;
4393
4394 case SpvCapabilityVulkanMemoryModelDeviceScope:
4395 spv_check_supported(vk_memory_model_device_scope, cap);
4396 break;
4397
4398 case SpvCapabilityImageReadWriteLodAMD:
4399 spv_check_supported(amd_image_read_write_lod, cap);
4400 break;
4401
4402 case SpvCapabilityIntegerFunctions2INTEL:
4403 spv_check_supported(integer_functions2, cap);
4404 break;
4405
4406 case SpvCapabilityFragmentMaskAMD:
4407 spv_check_supported(amd_fragment_mask, cap);
4408 break;
4409
4410 case SpvCapabilityImageGatherBiasLodAMD:
4411 spv_check_supported(amd_image_gather_bias_lod, cap);
4412 break;
4413
4414 case SpvCapabilityAtomicFloat32AddEXT:
4415 spv_check_supported(float32_atomic_add, cap);
4416 break;
4417
4418 case SpvCapabilityAtomicFloat64AddEXT:
4419 spv_check_supported(float64_atomic_add, cap);
4420 break;
4421
4422 default:
4423 vtn_fail("Unhandled capability: %s (%u)",
4424 spirv_capability_to_string(cap), cap);
4425 }
4426 break;
4427 }
4428
4429 case SpvOpExtInstImport:
4430 vtn_handle_extension(b, opcode, w, count);
4431 break;
4432
4433 case SpvOpMemoryModel:
4434 switch (w[1]) {
4435 case SpvAddressingModelPhysical32:
4436 vtn_fail_if(b->shader->info.stage != MESA_SHADER_KERNEL,
4437 "AddressingModelPhysical32 only supported for kernels");
4438 b->shader->info.cs.ptr_size = 32;
4439 b->physical_ptrs = true;
4440 assert(nir_address_format_bit_size(b->options->global_addr_format) == 32);
4441 assert(nir_address_format_num_components(b->options->global_addr_format) == 1);
4442 assert(nir_address_format_bit_size(b->options->shared_addr_format) == 32);
4443 assert(nir_address_format_num_components(b->options->shared_addr_format) == 1);
4444 if (!b->options->constant_as_global) {
4445 assert(nir_address_format_bit_size(b->options->ubo_addr_format) == 32);
4446 assert(nir_address_format_num_components(b->options->ubo_addr_format) == 1);
4447 }
4448 break;
4449 case SpvAddressingModelPhysical64:
4450 vtn_fail_if(b->shader->info.stage != MESA_SHADER_KERNEL,
4451 "AddressingModelPhysical64 only supported for kernels");
4452 b->shader->info.cs.ptr_size = 64;
4453 b->physical_ptrs = true;
4454 assert(nir_address_format_bit_size(b->options->global_addr_format) == 64);
4455 assert(nir_address_format_num_components(b->options->global_addr_format) == 1);
4456 assert(nir_address_format_bit_size(b->options->shared_addr_format) == 64);
4457 assert(nir_address_format_num_components(b->options->shared_addr_format) == 1);
4458 if (!b->options->constant_as_global) {
4459 assert(nir_address_format_bit_size(b->options->ubo_addr_format) == 64);
4460 assert(nir_address_format_num_components(b->options->ubo_addr_format) == 1);
4461 }
4462 break;
4463 case SpvAddressingModelLogical:
4464 vtn_fail_if(b->shader->info.stage == MESA_SHADER_KERNEL,
4465 "AddressingModelLogical only supported for shaders");
4466 b->physical_ptrs = false;
4467 break;
4468 case SpvAddressingModelPhysicalStorageBuffer64:
4469 vtn_fail_if(!b->options ||
4470 !b->options->caps.physical_storage_buffer_address,
4471 "AddressingModelPhysicalStorageBuffer64 not supported");
4472 break;
4473 default:
4474 vtn_fail("Unknown addressing model: %s (%u)",
4475 spirv_addressingmodel_to_string(w[1]), w[1]);
4476 break;
4477 }
4478
4479 b->mem_model = w[2];
4480 switch (w[2]) {
4481 case SpvMemoryModelSimple:
4482 case SpvMemoryModelGLSL450:
4483 case SpvMemoryModelOpenCL:
4484 break;
4485 case SpvMemoryModelVulkan:
4486 vtn_fail_if(!b->options->caps.vk_memory_model,
4487 "Vulkan memory model is unsupported by this driver");
4488 break;
4489 default:
4490 vtn_fail("Unsupported memory model: %s",
4491 spirv_memorymodel_to_string(w[2]));
4492 break;
4493 }
4494 break;
4495
4496 case SpvOpEntryPoint:
4497 vtn_handle_entry_point(b, w, count);
4498 break;
4499
4500 case SpvOpString:
4501 vtn_push_value(b, w[1], vtn_value_type_string)->str =
4502 vtn_string_literal(b, &w[2], count - 2, NULL);
4503 break;
4504
4505 case SpvOpName:
4506 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
4507 break;
4508
4509 case SpvOpMemberName:
4510 /* TODO */
4511 break;
4512
4513 case SpvOpExecutionMode:
4514 case SpvOpExecutionModeId:
4515 case SpvOpDecorationGroup:
4516 case SpvOpDecorate:
4517 case SpvOpDecorateId:
4518 case SpvOpMemberDecorate:
4519 case SpvOpGroupDecorate:
4520 case SpvOpGroupMemberDecorate:
4521 case SpvOpDecorateString:
4522 case SpvOpMemberDecorateString:
4523 vtn_handle_decoration(b, opcode, w, count);
4524 break;
4525
4526 case SpvOpExtInst: {
4527 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
4528 if (val->ext_handler == vtn_handle_non_semantic_instruction) {
4529 /* NonSemantic extended instructions are acceptable in preamble. */
4530 vtn_handle_non_semantic_instruction(b, w[4], w, count);
4531 return true;
4532 } else {
4533 return false; /* End of preamble. */
4534 }
4535 }
4536
4537 default:
4538 return false; /* End of preamble */
4539 }
4540
4541 return true;
4542 }
4543
4544 static void
4545 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
4546 const struct vtn_decoration *mode, UNUSED void *data)
4547 {
4548 vtn_assert(b->entry_point == entry_point);
4549
4550 switch(mode->exec_mode) {
4551 case SpvExecutionModeOriginUpperLeft:
4552 case SpvExecutionModeOriginLowerLeft:
4553 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4554 b->shader->info.fs.origin_upper_left =
4555 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
4556 break;
4557
4558 case SpvExecutionModeEarlyFragmentTests:
4559 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4560 b->shader->info.fs.early_fragment_tests = true;
4561 break;
4562
4563 case SpvExecutionModePostDepthCoverage:
4564 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4565 b->shader->info.fs.post_depth_coverage = true;
4566 break;
4567
4568 case SpvExecutionModeInvocations:
4569 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4570 b->shader->info.gs.invocations = MAX2(1, mode->operands[0]);
4571 break;
4572
4573 case SpvExecutionModeDepthReplacing:
4574 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4575 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
4576 break;
4577 case SpvExecutionModeDepthGreater:
4578 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4579 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
4580 break;
4581 case SpvExecutionModeDepthLess:
4582 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4583 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
4584 break;
4585 case SpvExecutionModeDepthUnchanged:
4586 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4587 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
4588 break;
4589
4590 case SpvExecutionModeLocalSize:
4591 vtn_assert(gl_shader_stage_is_compute(b->shader->info.stage));
4592 b->shader->info.cs.local_size[0] = mode->operands[0];
4593 b->shader->info.cs.local_size[1] = mode->operands[1];
4594 b->shader->info.cs.local_size[2] = mode->operands[2];
4595 break;
4596
4597 case SpvExecutionModeLocalSizeHint:
4598 break; /* Nothing to do with this */
4599
4600 case SpvExecutionModeOutputVertices:
4601 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4602 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
4603 b->shader->info.tess.tcs_vertices_out = mode->operands[0];
4604 } else {
4605 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4606 b->shader->info.gs.vertices_out = mode->operands[0];
4607 }
4608 break;
4609
4610 case SpvExecutionModeInputPoints:
4611 case SpvExecutionModeInputLines:
4612 case SpvExecutionModeInputLinesAdjacency:
4613 case SpvExecutionModeTriangles:
4614 case SpvExecutionModeInputTrianglesAdjacency:
4615 case SpvExecutionModeQuads:
4616 case SpvExecutionModeIsolines:
4617 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4618 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
4619 b->shader->info.tess.primitive_mode =
4620 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4621 } else {
4622 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4623 b->shader->info.gs.vertices_in =
4624 vertices_in_from_spv_execution_mode(b, mode->exec_mode);
4625 b->shader->info.gs.input_primitive =
4626 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4627 }
4628 break;
4629
4630 case SpvExecutionModeOutputPoints:
4631 case SpvExecutionModeOutputLineStrip:
4632 case SpvExecutionModeOutputTriangleStrip:
4633 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4634 b->shader->info.gs.output_primitive =
4635 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4636 break;
4637
4638 case SpvExecutionModeSpacingEqual:
4639 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4640 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4641 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
4642 break;
4643 case SpvExecutionModeSpacingFractionalEven:
4644 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4645 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4646 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
4647 break;
4648 case SpvExecutionModeSpacingFractionalOdd:
4649 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4650 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4651 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
4652 break;
4653 case SpvExecutionModeVertexOrderCw:
4654 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4655 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4656 b->shader->info.tess.ccw = false;
4657 break;
4658 case SpvExecutionModeVertexOrderCcw:
4659 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4660 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4661 b->shader->info.tess.ccw = true;
4662 break;
4663 case SpvExecutionModePointMode:
4664 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4665 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4666 b->shader->info.tess.point_mode = true;
4667 break;
4668
4669 case SpvExecutionModePixelCenterInteger:
4670 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4671 b->shader->info.fs.pixel_center_integer = true;
4672 break;
4673
4674 case SpvExecutionModeXfb:
4675 b->shader->info.has_transform_feedback_varyings = true;
4676 break;
4677
4678 case SpvExecutionModeVecTypeHint:
4679 break; /* OpenCL */
4680
4681 case SpvExecutionModeContractionOff:
4682 if (b->shader->info.stage != MESA_SHADER_KERNEL)
4683 vtn_warn("ExectionMode only allowed for CL-style kernels: %s",
4684 spirv_executionmode_to_string(mode->exec_mode));
4685 else
4686 b->exact = true;
4687 break;
4688
4689 case SpvExecutionModeStencilRefReplacingEXT:
4690 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4691 break;
4692
4693 case SpvExecutionModeDerivativeGroupQuadsNV:
4694 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
4695 b->shader->info.cs.derivative_group = DERIVATIVE_GROUP_QUADS;
4696 break;
4697
4698 case SpvExecutionModeDerivativeGroupLinearNV:
4699 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
4700 b->shader->info.cs.derivative_group = DERIVATIVE_GROUP_LINEAR;
4701 break;
4702
4703 case SpvExecutionModePixelInterlockOrderedEXT:
4704 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4705 b->shader->info.fs.pixel_interlock_ordered = true;
4706 break;
4707
4708 case SpvExecutionModePixelInterlockUnorderedEXT:
4709 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4710 b->shader->info.fs.pixel_interlock_unordered = true;
4711 break;
4712
4713 case SpvExecutionModeSampleInterlockOrderedEXT:
4714 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4715 b->shader->info.fs.sample_interlock_ordered = true;
4716 break;
4717
4718 case SpvExecutionModeSampleInterlockUnorderedEXT:
4719 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4720 b->shader->info.fs.sample_interlock_unordered = true;
4721 break;
4722
4723 case SpvExecutionModeDenormPreserve:
4724 case SpvExecutionModeDenormFlushToZero:
4725 case SpvExecutionModeSignedZeroInfNanPreserve:
4726 case SpvExecutionModeRoundingModeRTE:
4727 case SpvExecutionModeRoundingModeRTZ: {
4728 unsigned execution_mode = 0;
4729 switch (mode->exec_mode) {
4730 case SpvExecutionModeDenormPreserve:
4731 switch (mode->operands[0]) {
4732 case 16: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP16; break;
4733 case 32: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP32; break;
4734 case 64: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP64; break;
4735 default: vtn_fail("Floating point type not supported");
4736 }
4737 break;
4738 case SpvExecutionModeDenormFlushToZero:
4739 switch (mode->operands[0]) {
4740 case 16: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP16; break;
4741 case 32: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP32; break;
4742 case 64: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP64; break;
4743 default: vtn_fail("Floating point type not supported");
4744 }
4745 break;
4746 case SpvExecutionModeSignedZeroInfNanPreserve:
4747 switch (mode->operands[0]) {
4748 case 16: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP16; break;
4749 case 32: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP32; break;
4750 case 64: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP64; break;
4751 default: vtn_fail("Floating point type not supported");
4752 }
4753 break;
4754 case SpvExecutionModeRoundingModeRTE:
4755 switch (mode->operands[0]) {
4756 case 16: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16; break;
4757 case 32: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32; break;
4758 case 64: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64; break;
4759 default: vtn_fail("Floating point type not supported");
4760 }
4761 break;
4762 case SpvExecutionModeRoundingModeRTZ:
4763 switch (mode->operands[0]) {
4764 case 16: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16; break;
4765 case 32: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32; break;
4766 case 64: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64; break;
4767 default: vtn_fail("Floating point type not supported");
4768 }
4769 break;
4770 default:
4771 break;
4772 }
4773
4774 b->shader->info.float_controls_execution_mode |= execution_mode;
4775 break;
4776 }
4777
4778 case SpvExecutionModeLocalSizeId:
4779 case SpvExecutionModeLocalSizeHintId:
4780 /* Handled later by vtn_handle_execution_mode_id(). */
4781 break;
4782
4783 default:
4784 vtn_fail("Unhandled execution mode: %s (%u)",
4785 spirv_executionmode_to_string(mode->exec_mode),
4786 mode->exec_mode);
4787 }
4788 }
4789
4790 static void
4791 vtn_handle_execution_mode_id(struct vtn_builder *b, struct vtn_value *entry_point,
4792 const struct vtn_decoration *mode, UNUSED void *data)
4793 {
4794
4795 vtn_assert(b->entry_point == entry_point);
4796
4797 switch (mode->exec_mode) {
4798 case SpvExecutionModeLocalSizeId:
4799 b->shader->info.cs.local_size[0] = vtn_constant_uint(b, mode->operands[0]);
4800 b->shader->info.cs.local_size[1] = vtn_constant_uint(b, mode->operands[1]);
4801 b->shader->info.cs.local_size[2] = vtn_constant_uint(b, mode->operands[2]);
4802 break;
4803
4804 case SpvExecutionModeLocalSizeHintId:
4805 /* Nothing to do with this hint. */
4806 break;
4807
4808 default:
4809 /* Nothing to do. Literal execution modes already handled by
4810 * vtn_handle_execution_mode(). */
4811 break;
4812 }
4813 }
4814
4815 static bool
4816 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
4817 const uint32_t *w, unsigned count)
4818 {
4819 vtn_set_instruction_result_type(b, opcode, w, count);
4820
4821 switch (opcode) {
4822 case SpvOpSource:
4823 case SpvOpSourceContinued:
4824 case SpvOpSourceExtension:
4825 case SpvOpExtension:
4826 case SpvOpCapability:
4827 case SpvOpExtInstImport:
4828 case SpvOpMemoryModel:
4829 case SpvOpEntryPoint:
4830 case SpvOpExecutionMode:
4831 case SpvOpString:
4832 case SpvOpName:
4833 case SpvOpMemberName:
4834 case SpvOpDecorationGroup:
4835 case SpvOpDecorate:
4836 case SpvOpDecorateId:
4837 case SpvOpMemberDecorate:
4838 case SpvOpGroupDecorate:
4839 case SpvOpGroupMemberDecorate:
4840 case SpvOpDecorateString:
4841 case SpvOpMemberDecorateString:
4842 vtn_fail("Invalid opcode types and variables section");
4843 break;
4844
4845 case SpvOpTypeVoid:
4846 case SpvOpTypeBool:
4847 case SpvOpTypeInt:
4848 case SpvOpTypeFloat:
4849 case SpvOpTypeVector:
4850 case SpvOpTypeMatrix:
4851 case SpvOpTypeImage:
4852 case SpvOpTypeSampler:
4853 case SpvOpTypeSampledImage:
4854 case SpvOpTypeArray:
4855 case SpvOpTypeRuntimeArray:
4856 case SpvOpTypeStruct:
4857 case SpvOpTypeOpaque:
4858 case SpvOpTypePointer:
4859 case SpvOpTypeForwardPointer:
4860 case SpvOpTypeFunction:
4861 case SpvOpTypeEvent:
4862 case SpvOpTypeDeviceEvent:
4863 case SpvOpTypeReserveId:
4864 case SpvOpTypeQueue:
4865 case SpvOpTypePipe:
4866 vtn_handle_type(b, opcode, w, count);
4867 break;
4868
4869 case SpvOpConstantTrue:
4870 case SpvOpConstantFalse:
4871 case SpvOpConstant:
4872 case SpvOpConstantComposite:
4873 case SpvOpConstantNull:
4874 case SpvOpSpecConstantTrue:
4875 case SpvOpSpecConstantFalse:
4876 case SpvOpSpecConstant:
4877 case SpvOpSpecConstantComposite:
4878 case SpvOpSpecConstantOp:
4879 vtn_handle_constant(b, opcode, w, count);
4880 break;
4881
4882 case SpvOpUndef:
4883 case SpvOpVariable:
4884 case SpvOpConstantSampler:
4885 vtn_handle_variables(b, opcode, w, count);
4886 break;
4887
4888 case SpvOpExtInst: {
4889 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
4890 /* NonSemantic extended instructions are acceptable in preamble, others
4891 * will indicate the end of preamble.
4892 */
4893 return val->ext_handler == vtn_handle_non_semantic_instruction;
4894 }
4895
4896 default:
4897 return false; /* End of preamble */
4898 }
4899
4900 return true;
4901 }
4902
4903 static struct vtn_ssa_value *
4904 vtn_nir_select(struct vtn_builder *b, struct vtn_ssa_value *src0,
4905 struct vtn_ssa_value *src1, struct vtn_ssa_value *src2)
4906 {
4907 struct vtn_ssa_value *dest = rzalloc(b, struct vtn_ssa_value);
4908 dest->type = src1->type;
4909
4910 if (glsl_type_is_vector_or_scalar(src1->type)) {
4911 dest->def = nir_bcsel(&b->nb, src0->def, src1->def, src2->def);
4912 } else {
4913 unsigned elems = glsl_get_length(src1->type);
4914
4915 dest->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
4916 for (unsigned i = 0; i < elems; i++) {
4917 dest->elems[i] = vtn_nir_select(b, src0,
4918 src1->elems[i], src2->elems[i]);
4919 }
4920 }
4921
4922 return dest;
4923 }
4924
4925 static void
4926 vtn_handle_select(struct vtn_builder *b, SpvOp opcode,
4927 const uint32_t *w, unsigned count)
4928 {
4929 /* Handle OpSelect up-front here because it needs to be able to handle
4930 * pointers and not just regular vectors and scalars.
4931 */
4932 struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
4933 struct vtn_value *cond_val = vtn_untyped_value(b, w[3]);
4934 struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
4935 struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
4936
4937 vtn_fail_if(obj1_val->type != res_val->type ||
4938 obj2_val->type != res_val->type,
4939 "Object types must match the result type in OpSelect");
4940
4941 vtn_fail_if((cond_val->type->base_type != vtn_base_type_scalar &&
4942 cond_val->type->base_type != vtn_base_type_vector) ||
4943 !glsl_type_is_boolean(cond_val->type->type),
4944 "OpSelect must have either a vector of booleans or "
4945 "a boolean as Condition type");
4946
4947 vtn_fail_if(cond_val->type->base_type == vtn_base_type_vector &&
4948 (res_val->type->base_type != vtn_base_type_vector ||
4949 res_val->type->length != cond_val->type->length),
4950 "When Condition type in OpSelect is a vector, the Result "
4951 "type must be a vector of the same length");
4952
4953 switch (res_val->type->base_type) {
4954 case vtn_base_type_scalar:
4955 case vtn_base_type_vector:
4956 case vtn_base_type_matrix:
4957 case vtn_base_type_array:
4958 case vtn_base_type_struct:
4959 /* OK. */
4960 break;
4961 case vtn_base_type_pointer:
4962 /* We need to have actual storage for pointer types. */
4963 vtn_fail_if(res_val->type->type == NULL,
4964 "Invalid pointer result type for OpSelect");
4965 break;
4966 default:
4967 vtn_fail("Result type of OpSelect must be a scalar, composite, or pointer");
4968 }
4969
4970 vtn_push_ssa_value(b, w[2],
4971 vtn_nir_select(b, vtn_ssa_value(b, w[3]),
4972 vtn_ssa_value(b, w[4]),
4973 vtn_ssa_value(b, w[5])));
4974 }
4975
4976 static void
4977 vtn_handle_ptr(struct vtn_builder *b, SpvOp opcode,
4978 const uint32_t *w, unsigned count)
4979 {
4980 struct vtn_type *type1 = vtn_get_value_type(b, w[3]);
4981 struct vtn_type *type2 = vtn_get_value_type(b, w[4]);
4982 vtn_fail_if(type1->base_type != vtn_base_type_pointer ||
4983 type2->base_type != vtn_base_type_pointer,
4984 "%s operands must have pointer types",
4985 spirv_op_to_string(opcode));
4986 vtn_fail_if(type1->storage_class != type2->storage_class,
4987 "%s operands must have the same storage class",
4988 spirv_op_to_string(opcode));
4989
4990 struct vtn_type *vtn_type = vtn_get_type(b, w[1]);
4991 const struct glsl_type *type = vtn_type->type;
4992
4993 nir_address_format addr_format = vtn_mode_to_address_format(
4994 b, vtn_storage_class_to_mode(b, type1->storage_class, NULL, NULL));
4995
4996 nir_ssa_def *def;
4997
4998 switch (opcode) {
4999 case SpvOpPtrDiff: {
5000 /* OpPtrDiff returns the difference in number of elements (not byte offset). */
5001 unsigned elem_size, elem_align;
5002 glsl_get_natural_size_align_bytes(type1->deref->type,
5003 &elem_size, &elem_align);
5004
5005 def = nir_build_addr_isub(&b->nb,
5006 vtn_get_nir_ssa(b, w[3]),
5007 vtn_get_nir_ssa(b, w[4]),
5008 addr_format);
5009 def = nir_idiv(&b->nb, def, nir_imm_intN_t(&b->nb, elem_size, def->bit_size));
5010 def = nir_i2i(&b->nb, def, glsl_get_bit_size(type));
5011 break;
5012 }
5013
5014 case SpvOpPtrEqual:
5015 case SpvOpPtrNotEqual: {
5016 def = nir_build_addr_ieq(&b->nb,
5017 vtn_get_nir_ssa(b, w[3]),
5018 vtn_get_nir_ssa(b, w[4]),
5019 addr_format);
5020 if (opcode == SpvOpPtrNotEqual)
5021 def = nir_inot(&b->nb, def);
5022 break;
5023 }
5024
5025 default:
5026 unreachable("Invalid ptr operation");
5027 }
5028
5029 vtn_push_nir_ssa(b, w[2], def);
5030 }
5031
5032 static bool
5033 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
5034 const uint32_t *w, unsigned count)
5035 {
5036 switch (opcode) {
5037 case SpvOpLabel:
5038 break;
5039
5040 case SpvOpLoopMerge:
5041 case SpvOpSelectionMerge:
5042 /* This is handled by cfg pre-pass and walk_blocks */
5043 break;
5044
5045 case SpvOpUndef: {
5046 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
5047 val->type = vtn_get_type(b, w[1]);
5048 break;
5049 }
5050
5051 case SpvOpExtInst:
5052 vtn_handle_extension(b, opcode, w, count);
5053 break;
5054
5055 case SpvOpVariable:
5056 case SpvOpLoad:
5057 case SpvOpStore:
5058 case SpvOpCopyMemory:
5059 case SpvOpCopyMemorySized:
5060 case SpvOpAccessChain:
5061 case SpvOpPtrAccessChain:
5062 case SpvOpInBoundsAccessChain:
5063 case SpvOpInBoundsPtrAccessChain:
5064 case SpvOpArrayLength:
5065 case SpvOpConvertPtrToU:
5066 case SpvOpConvertUToPtr:
5067 vtn_handle_variables(b, opcode, w, count);
5068 break;
5069
5070 case SpvOpFunctionCall:
5071 vtn_handle_function_call(b, opcode, w, count);
5072 break;
5073
5074 case SpvOpSampledImage:
5075 case SpvOpImage:
5076 case SpvOpImageSampleImplicitLod:
5077 case SpvOpImageSampleExplicitLod:
5078 case SpvOpImageSampleDrefImplicitLod:
5079 case SpvOpImageSampleDrefExplicitLod:
5080 case SpvOpImageSampleProjImplicitLod:
5081 case SpvOpImageSampleProjExplicitLod:
5082 case SpvOpImageSampleProjDrefImplicitLod:
5083 case SpvOpImageSampleProjDrefExplicitLod:
5084 case SpvOpImageFetch:
5085 case SpvOpImageGather:
5086 case SpvOpImageDrefGather:
5087 case SpvOpImageQueryLod:
5088 case SpvOpImageQueryLevels:
5089 case SpvOpImageQuerySamples:
5090 vtn_handle_texture(b, opcode, w, count);
5091 break;
5092
5093 case SpvOpImageRead:
5094 case SpvOpImageWrite:
5095 case SpvOpImageTexelPointer:
5096 case SpvOpImageQueryFormat:
5097 case SpvOpImageQueryOrder:
5098 vtn_handle_image(b, opcode, w, count);
5099 break;
5100
5101 case SpvOpImageQuerySizeLod:
5102 case SpvOpImageQuerySize: {
5103 struct vtn_type *image_type = vtn_get_value_type(b, w[3]);
5104 vtn_assert(image_type->base_type == vtn_base_type_image);
5105 if (glsl_type_is_image(image_type->glsl_image)) {
5106 vtn_handle_image(b, opcode, w, count);
5107 } else {
5108 vtn_assert(glsl_type_is_sampler(image_type->glsl_image));
5109 vtn_handle_texture(b, opcode, w, count);
5110 }
5111 break;
5112 }
5113
5114 case SpvOpFragmentMaskFetchAMD:
5115 case SpvOpFragmentFetchAMD:
5116 vtn_handle_texture(b, opcode, w, count);
5117 break;
5118
5119 case SpvOpAtomicLoad:
5120 case SpvOpAtomicExchange:
5121 case SpvOpAtomicCompareExchange:
5122 case SpvOpAtomicCompareExchangeWeak:
5123 case SpvOpAtomicIIncrement:
5124 case SpvOpAtomicIDecrement:
5125 case SpvOpAtomicIAdd:
5126 case SpvOpAtomicISub:
5127 case SpvOpAtomicSMin:
5128 case SpvOpAtomicUMin:
5129 case SpvOpAtomicSMax:
5130 case SpvOpAtomicUMax:
5131 case SpvOpAtomicAnd:
5132 case SpvOpAtomicOr:
5133 case SpvOpAtomicXor:
5134 case SpvOpAtomicFAddEXT: {
5135 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
5136 if (pointer->value_type == vtn_value_type_image_pointer) {
5137 vtn_handle_image(b, opcode, w, count);
5138 } else {
5139 vtn_assert(pointer->value_type == vtn_value_type_pointer);
5140 vtn_handle_atomics(b, opcode, w, count);
5141 }
5142 break;
5143 }
5144
5145 case SpvOpAtomicStore: {
5146 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
5147 if (pointer->value_type == vtn_value_type_image_pointer) {
5148 vtn_handle_image(b, opcode, w, count);
5149 } else {
5150 vtn_assert(pointer->value_type == vtn_value_type_pointer);
5151 vtn_handle_atomics(b, opcode, w, count);
5152 }
5153 break;
5154 }
5155
5156 case SpvOpSelect:
5157 vtn_handle_select(b, opcode, w, count);
5158 break;
5159
5160 case SpvOpSNegate:
5161 case SpvOpFNegate:
5162 case SpvOpNot:
5163 case SpvOpAny:
5164 case SpvOpAll:
5165 case SpvOpConvertFToU:
5166 case SpvOpConvertFToS:
5167 case SpvOpConvertSToF:
5168 case SpvOpConvertUToF:
5169 case SpvOpUConvert:
5170 case SpvOpSConvert:
5171 case SpvOpFConvert:
5172 case SpvOpQuantizeToF16:
5173 case SpvOpPtrCastToGeneric:
5174 case SpvOpGenericCastToPtr:
5175 case SpvOpIsNan:
5176 case SpvOpIsInf:
5177 case SpvOpIsFinite:
5178 case SpvOpIsNormal:
5179 case SpvOpSignBitSet:
5180 case SpvOpLessOrGreater:
5181 case SpvOpOrdered:
5182 case SpvOpUnordered:
5183 case SpvOpIAdd:
5184 case SpvOpFAdd:
5185 case SpvOpISub:
5186 case SpvOpFSub:
5187 case SpvOpIMul:
5188 case SpvOpFMul:
5189 case SpvOpUDiv:
5190 case SpvOpSDiv:
5191 case SpvOpFDiv:
5192 case SpvOpUMod:
5193 case SpvOpSRem:
5194 case SpvOpSMod:
5195 case SpvOpFRem:
5196 case SpvOpFMod:
5197 case SpvOpVectorTimesScalar:
5198 case SpvOpDot:
5199 case SpvOpIAddCarry:
5200 case SpvOpISubBorrow:
5201 case SpvOpUMulExtended:
5202 case SpvOpSMulExtended:
5203 case SpvOpShiftRightLogical:
5204 case SpvOpShiftRightArithmetic:
5205 case SpvOpShiftLeftLogical:
5206 case SpvOpLogicalEqual:
5207 case SpvOpLogicalNotEqual:
5208 case SpvOpLogicalOr:
5209 case SpvOpLogicalAnd:
5210 case SpvOpLogicalNot:
5211 case SpvOpBitwiseOr:
5212 case SpvOpBitwiseXor:
5213 case SpvOpBitwiseAnd:
5214 case SpvOpIEqual:
5215 case SpvOpFOrdEqual:
5216 case SpvOpFUnordEqual:
5217 case SpvOpINotEqual:
5218 case SpvOpFOrdNotEqual:
5219 case SpvOpFUnordNotEqual:
5220 case SpvOpULessThan:
5221 case SpvOpSLessThan:
5222 case SpvOpFOrdLessThan:
5223 case SpvOpFUnordLessThan:
5224 case SpvOpUGreaterThan:
5225 case SpvOpSGreaterThan:
5226 case SpvOpFOrdGreaterThan:
5227 case SpvOpFUnordGreaterThan:
5228 case SpvOpULessThanEqual:
5229 case SpvOpSLessThanEqual:
5230 case SpvOpFOrdLessThanEqual:
5231 case SpvOpFUnordLessThanEqual:
5232 case SpvOpUGreaterThanEqual:
5233 case SpvOpSGreaterThanEqual:
5234 case SpvOpFOrdGreaterThanEqual:
5235 case SpvOpFUnordGreaterThanEqual:
5236 case SpvOpDPdx:
5237 case SpvOpDPdy:
5238 case SpvOpFwidth:
5239 case SpvOpDPdxFine:
5240 case SpvOpDPdyFine:
5241 case SpvOpFwidthFine:
5242 case SpvOpDPdxCoarse:
5243 case SpvOpDPdyCoarse:
5244 case SpvOpFwidthCoarse:
5245 case SpvOpBitFieldInsert:
5246 case SpvOpBitFieldSExtract:
5247 case SpvOpBitFieldUExtract:
5248 case SpvOpBitReverse:
5249 case SpvOpBitCount:
5250 case SpvOpTranspose:
5251 case SpvOpOuterProduct:
5252 case SpvOpMatrixTimesScalar:
5253 case SpvOpVectorTimesMatrix:
5254 case SpvOpMatrixTimesVector:
5255 case SpvOpMatrixTimesMatrix:
5256 case SpvOpUCountLeadingZerosINTEL:
5257 case SpvOpUCountTrailingZerosINTEL:
5258 case SpvOpAbsISubINTEL:
5259 case SpvOpAbsUSubINTEL:
5260 case SpvOpIAddSatINTEL:
5261 case SpvOpUAddSatINTEL:
5262 case SpvOpIAverageINTEL:
5263 case SpvOpUAverageINTEL:
5264 case SpvOpIAverageRoundedINTEL:
5265 case SpvOpUAverageRoundedINTEL:
5266 case SpvOpISubSatINTEL:
5267 case SpvOpUSubSatINTEL:
5268 case SpvOpIMul32x16INTEL:
5269 case SpvOpUMul32x16INTEL:
5270 vtn_handle_alu(b, opcode, w, count);
5271 break;
5272
5273 case SpvOpBitcast:
5274 vtn_handle_bitcast(b, w, count);
5275 break;
5276
5277 case SpvOpVectorExtractDynamic:
5278 case SpvOpVectorInsertDynamic:
5279 case SpvOpVectorShuffle:
5280 case SpvOpCompositeConstruct:
5281 case SpvOpCompositeExtract:
5282 case SpvOpCompositeInsert:
5283 case SpvOpCopyLogical:
5284 case SpvOpCopyObject:
5285 vtn_handle_composite(b, opcode, w, count);
5286 break;
5287
5288 case SpvOpEmitVertex:
5289 case SpvOpEndPrimitive:
5290 case SpvOpEmitStreamVertex:
5291 case SpvOpEndStreamPrimitive:
5292 case SpvOpControlBarrier:
5293 case SpvOpMemoryBarrier:
5294 vtn_handle_barrier(b, opcode, w, count);
5295 break;
5296
5297 case SpvOpGroupNonUniformElect:
5298 case SpvOpGroupNonUniformAll:
5299 case SpvOpGroupNonUniformAny:
5300 case SpvOpGroupNonUniformAllEqual:
5301 case SpvOpGroupNonUniformBroadcast:
5302 case SpvOpGroupNonUniformBroadcastFirst:
5303 case SpvOpGroupNonUniformBallot:
5304 case SpvOpGroupNonUniformInverseBallot:
5305 case SpvOpGroupNonUniformBallotBitExtract:
5306 case SpvOpGroupNonUniformBallotBitCount:
5307 case SpvOpGroupNonUniformBallotFindLSB:
5308 case SpvOpGroupNonUniformBallotFindMSB:
5309 case SpvOpGroupNonUniformShuffle:
5310 case SpvOpGroupNonUniformShuffleXor:
5311 case SpvOpGroupNonUniformShuffleUp:
5312 case SpvOpGroupNonUniformShuffleDown:
5313 case SpvOpGroupNonUniformIAdd:
5314 case SpvOpGroupNonUniformFAdd:
5315 case SpvOpGroupNonUniformIMul:
5316 case SpvOpGroupNonUniformFMul:
5317 case SpvOpGroupNonUniformSMin:
5318 case SpvOpGroupNonUniformUMin:
5319 case SpvOpGroupNonUniformFMin:
5320 case SpvOpGroupNonUniformSMax:
5321 case SpvOpGroupNonUniformUMax:
5322 case SpvOpGroupNonUniformFMax:
5323 case SpvOpGroupNonUniformBitwiseAnd:
5324 case SpvOpGroupNonUniformBitwiseOr:
5325 case SpvOpGroupNonUniformBitwiseXor:
5326 case SpvOpGroupNonUniformLogicalAnd:
5327 case SpvOpGroupNonUniformLogicalOr:
5328 case SpvOpGroupNonUniformLogicalXor:
5329 case SpvOpGroupNonUniformQuadBroadcast:
5330 case SpvOpGroupNonUniformQuadSwap:
5331 case SpvOpGroupAll:
5332 case SpvOpGroupAny:
5333 case SpvOpGroupBroadcast:
5334 case SpvOpGroupIAdd:
5335 case SpvOpGroupFAdd:
5336 case SpvOpGroupFMin:
5337 case SpvOpGroupUMin:
5338 case SpvOpGroupSMin:
5339 case SpvOpGroupFMax:
5340 case SpvOpGroupUMax:
5341 case SpvOpGroupSMax:
5342 case SpvOpSubgroupBallotKHR:
5343 case SpvOpSubgroupFirstInvocationKHR:
5344 case SpvOpSubgroupReadInvocationKHR:
5345 case SpvOpSubgroupAllKHR:
5346 case SpvOpSubgroupAnyKHR:
5347 case SpvOpSubgroupAllEqualKHR:
5348 case SpvOpGroupIAddNonUniformAMD:
5349 case SpvOpGroupFAddNonUniformAMD:
5350 case SpvOpGroupFMinNonUniformAMD:
5351 case SpvOpGroupUMinNonUniformAMD:
5352 case SpvOpGroupSMinNonUniformAMD:
5353 case SpvOpGroupFMaxNonUniformAMD:
5354 case SpvOpGroupUMaxNonUniformAMD:
5355 case SpvOpGroupSMaxNonUniformAMD:
5356 vtn_handle_subgroup(b, opcode, w, count);
5357 break;
5358
5359 case SpvOpPtrDiff:
5360 case SpvOpPtrEqual:
5361 case SpvOpPtrNotEqual:
5362 vtn_handle_ptr(b, opcode, w, count);
5363 break;
5364
5365 case SpvOpBeginInvocationInterlockEXT:
5366 vtn_emit_barrier(b, nir_intrinsic_begin_invocation_interlock);
5367 break;
5368
5369 case SpvOpEndInvocationInterlockEXT:
5370 vtn_emit_barrier(b, nir_intrinsic_end_invocation_interlock);
5371 break;
5372
5373 case SpvOpDemoteToHelperInvocationEXT: {
5374 nir_intrinsic_instr *intrin =
5375 nir_intrinsic_instr_create(b->shader, nir_intrinsic_demote);
5376 nir_builder_instr_insert(&b->nb, &intrin->instr);
5377 break;
5378 }
5379
5380 case SpvOpIsHelperInvocationEXT: {
5381 nir_intrinsic_instr *intrin =
5382 nir_intrinsic_instr_create(b->shader, nir_intrinsic_is_helper_invocation);
5383 nir_ssa_dest_init(&intrin->instr, &intrin->dest, 1, 1, NULL);
5384 nir_builder_instr_insert(&b->nb, &intrin->instr);
5385
5386 vtn_push_nir_ssa(b, w[2], &intrin->dest.ssa);
5387 break;
5388 }
5389
5390 case SpvOpReadClockKHR: {
5391 SpvScope scope = vtn_constant_uint(b, w[3]);
5392 nir_scope nir_scope;
5393
5394 switch (scope) {
5395 case SpvScopeDevice:
5396 nir_scope = NIR_SCOPE_DEVICE;
5397 break;
5398 case SpvScopeSubgroup:
5399 nir_scope = NIR_SCOPE_SUBGROUP;
5400 break;
5401 default:
5402 vtn_fail("invalid read clock scope");
5403 }
5404
5405 /* Operation supports two result types: uvec2 and uint64_t. The NIR
5406 * intrinsic gives uvec2, so pack the result for the other case.
5407 */
5408 nir_intrinsic_instr *intrin =
5409 nir_intrinsic_instr_create(b->nb.shader, nir_intrinsic_shader_clock);
5410 nir_ssa_dest_init(&intrin->instr, &intrin->dest, 2, 32, NULL);
5411 nir_intrinsic_set_memory_scope(intrin, nir_scope);
5412 nir_builder_instr_insert(&b->nb, &intrin->instr);
5413
5414 struct vtn_type *type = vtn_get_type(b, w[1]);
5415 const struct glsl_type *dest_type = type->type;
5416 nir_ssa_def *result;
5417
5418 if (glsl_type_is_vector(dest_type)) {
5419 assert(dest_type == glsl_vector_type(GLSL_TYPE_UINT, 2));
5420 result = &intrin->dest.ssa;
5421 } else {
5422 assert(glsl_type_is_scalar(dest_type));
5423 assert(glsl_get_base_type(dest_type) == GLSL_TYPE_UINT64);
5424 result = nir_pack_64_2x32(&b->nb, &intrin->dest.ssa);
5425 }
5426
5427 vtn_push_nir_ssa(b, w[2], result);
5428 break;
5429 }
5430
5431 case SpvOpLifetimeStart:
5432 case SpvOpLifetimeStop:
5433 break;
5434
5435 default:
5436 vtn_fail_with_opcode("Unhandled opcode", opcode);
5437 }
5438
5439 return true;
5440 }
5441
5442 struct vtn_builder*
5443 vtn_create_builder(const uint32_t *words, size_t word_count,
5444 gl_shader_stage stage, const char *entry_point_name,
5445 const struct spirv_to_nir_options *options)
5446 {
5447 /* Initialize the vtn_builder object */
5448 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
5449 struct spirv_to_nir_options *dup_options =
5450 ralloc(b, struct spirv_to_nir_options);
5451 *dup_options = *options;
5452
5453 b->spirv = words;
5454 b->spirv_word_count = word_count;
5455 b->file = NULL;
5456 b->line = -1;
5457 b->col = -1;
5458 list_inithead(&b->functions);
5459 b->entry_point_stage = stage;
5460 b->entry_point_name = entry_point_name;
5461 b->options = dup_options;
5462
5463 /*
5464 * Handle the SPIR-V header (first 5 dwords).
5465 * Can't use vtx_assert() as the setjmp(3) target isn't initialized yet.
5466 */
5467 if (word_count <= 5)
5468 goto fail;
5469
5470 if (words[0] != SpvMagicNumber) {
5471 vtn_err("words[0] was 0x%x, want 0x%x", words[0], SpvMagicNumber);
5472 goto fail;
5473 }
5474 if (words[1] < 0x10000) {
5475 vtn_err("words[1] was 0x%x, want >= 0x10000", words[1]);
5476 goto fail;
5477 }
5478
5479 uint16_t generator_id = words[2] >> 16;
5480 uint16_t generator_version = words[2];
5481
5482 /* In GLSLang commit 8297936dd6eb3, their handling of barrier() was fixed
5483 * to provide correct memory semantics on compute shader barrier()
5484 * commands. Prior to that, we need to fix them up ourselves. This
5485 * GLSLang fix caused them to bump to generator version 3.
5486 */
5487 b->wa_glslang_cs_barrier = (generator_id == 8 && generator_version < 3);
5488
5489 /* words[2] == generator magic */
5490 unsigned value_id_bound = words[3];
5491 if (words[4] != 0) {
5492 vtn_err("words[4] was %u, want 0", words[4]);
5493 goto fail;
5494 }
5495
5496 b->value_id_bound = value_id_bound;
5497 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
5498
5499 return b;
5500 fail:
5501 ralloc_free(b);
5502 return NULL;
5503 }
5504
5505 static nir_function *
5506 vtn_emit_kernel_entry_point_wrapper(struct vtn_builder *b,
5507 nir_function *entry_point)
5508 {
5509 vtn_assert(entry_point == b->entry_point->func->impl->function);
5510 vtn_fail_if(!entry_point->name, "entry points are required to have a name");
5511 const char *func_name =
5512 ralloc_asprintf(b->shader, "__wrapped_%s", entry_point->name);
5513
5514 /* we shouldn't have any inputs yet */
5515 vtn_assert(!entry_point->shader->num_inputs);
5516 vtn_assert(b->shader->info.stage == MESA_SHADER_KERNEL);
5517
5518 nir_function *main_entry_point = nir_function_create(b->shader, func_name);
5519 main_entry_point->impl = nir_function_impl_create(main_entry_point);
5520 nir_builder_init(&b->nb, main_entry_point->impl);
5521 b->nb.cursor = nir_after_cf_list(&main_entry_point->impl->body);
5522 b->func_param_idx = 0;
5523
5524 nir_call_instr *call = nir_call_instr_create(b->nb.shader, entry_point);
5525
5526 for (unsigned i = 0; i < entry_point->num_params; ++i) {
5527 struct vtn_type *param_type = b->entry_point->func->type->params[i];
5528
5529 /* consider all pointers to function memory to be parameters passed
5530 * by value
5531 */
5532 bool is_by_val = param_type->base_type == vtn_base_type_pointer &&
5533 param_type->storage_class == SpvStorageClassFunction;
5534
5535 /* input variable */
5536 nir_variable *in_var = rzalloc(b->nb.shader, nir_variable);
5537 in_var->data.mode = nir_var_uniform;
5538 in_var->data.read_only = true;
5539 in_var->data.location = i;
5540 if (param_type->base_type == vtn_base_type_image) {
5541 in_var->data.access = 0;
5542 if (param_type->access_qualifier & SpvAccessQualifierReadOnly)
5543 in_var->data.access |= ACCESS_NON_WRITEABLE;
5544 if (param_type->access_qualifier & SpvAccessQualifierWriteOnly)
5545 in_var->data.access |= ACCESS_NON_READABLE;
5546 }
5547
5548 if (is_by_val)
5549 in_var->type = param_type->deref->type;
5550 else if (param_type->base_type == vtn_base_type_image)
5551 in_var->type = param_type->glsl_image;
5552 else if (param_type->base_type == vtn_base_type_sampler)
5553 in_var->type = glsl_bare_sampler_type();
5554 else
5555 in_var->type = param_type->type;
5556
5557 nir_shader_add_variable(b->nb.shader, in_var);
5558 b->nb.shader->num_inputs++;
5559
5560 /* we have to copy the entire variable into function memory */
5561 if (is_by_val) {
5562 nir_variable *copy_var =
5563 nir_local_variable_create(main_entry_point->impl, in_var->type,
5564 "copy_in");
5565 nir_copy_var(&b->nb, copy_var, in_var);
5566 call->params[i] =
5567 nir_src_for_ssa(&nir_build_deref_var(&b->nb, copy_var)->dest.ssa);
5568 } else if (param_type->base_type == vtn_base_type_image ||
5569 param_type->base_type == vtn_base_type_sampler) {
5570 /* Don't load the var, just pass a deref of it */
5571 call->params[i] = nir_src_for_ssa(&nir_build_deref_var(&b->nb, in_var)->dest.ssa);
5572 } else {
5573 call->params[i] = nir_src_for_ssa(nir_load_var(&b->nb, in_var));
5574 }
5575 }
5576
5577 nir_builder_instr_insert(&b->nb, &call->instr);
5578
5579 return main_entry_point;
5580 }
5581
5582 nir_shader *
5583 spirv_to_nir(const uint32_t *words, size_t word_count,
5584 struct nir_spirv_specialization *spec, unsigned num_spec,
5585 gl_shader_stage stage, const char *entry_point_name,
5586 const struct spirv_to_nir_options *options,
5587 const nir_shader_compiler_options *nir_options)
5588
5589 {
5590 const uint32_t *word_end = words + word_count;
5591
5592 struct vtn_builder *b = vtn_create_builder(words, word_count,
5593 stage, entry_point_name,
5594 options);
5595
5596 if (b == NULL)
5597 return NULL;
5598
5599 /* See also _vtn_fail() */
5600 if (setjmp(b->fail_jump)) {
5601 ralloc_free(b);
5602 return NULL;
5603 }
5604
5605 /* Skip the SPIR-V header, handled at vtn_create_builder */
5606 words+= 5;
5607
5608 b->shader = nir_shader_create(b, stage, nir_options, NULL);
5609
5610 /* Handle all the preamble instructions */
5611 words = vtn_foreach_instruction(b, words, word_end,
5612 vtn_handle_preamble_instruction);
5613
5614 if (b->entry_point == NULL) {
5615 vtn_fail("Entry point not found");
5616 ralloc_free(b);
5617 return NULL;
5618 }
5619
5620 /* Ensure a sane address mode is being used for function temps */
5621 assert(nir_address_format_bit_size(b->options->temp_addr_format) == nir_get_ptr_bitsize(b->shader));
5622 assert(nir_address_format_num_components(b->options->temp_addr_format) == 1);
5623
5624 /* Set shader info defaults */
5625 if (stage == MESA_SHADER_GEOMETRY)
5626 b->shader->info.gs.invocations = 1;
5627
5628 /* Parse execution modes. */
5629 vtn_foreach_execution_mode(b, b->entry_point,
5630 vtn_handle_execution_mode, NULL);
5631
5632 b->specializations = spec;
5633 b->num_specializations = num_spec;
5634
5635 /* Handle all variable, type, and constant instructions */
5636 words = vtn_foreach_instruction(b, words, word_end,
5637 vtn_handle_variable_or_type_instruction);
5638
5639 /* Parse execution modes that depend on IDs. Must happen after we have
5640 * constants parsed.
5641 */
5642 vtn_foreach_execution_mode(b, b->entry_point,
5643 vtn_handle_execution_mode_id, NULL);
5644
5645 if (b->workgroup_size_builtin) {
5646 vtn_assert(b->workgroup_size_builtin->type->type ==
5647 glsl_vector_type(GLSL_TYPE_UINT, 3));
5648
5649 nir_const_value *const_size =
5650 b->workgroup_size_builtin->constant->values;
5651
5652 b->shader->info.cs.local_size[0] = const_size[0].u32;
5653 b->shader->info.cs.local_size[1] = const_size[1].u32;
5654 b->shader->info.cs.local_size[2] = const_size[2].u32;
5655 }
5656
5657 /* Set types on all vtn_values */
5658 vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
5659
5660 vtn_build_cfg(b, words, word_end);
5661
5662 assert(b->entry_point->value_type == vtn_value_type_function);
5663 b->entry_point->func->referenced = true;
5664
5665 bool progress;
5666 do {
5667 progress = false;
5668 vtn_foreach_cf_node(node, &b->functions) {
5669 struct vtn_function *func = vtn_cf_node_as_function(node);
5670 if (func->referenced && !func->emitted) {
5671 b->const_table = _mesa_pointer_hash_table_create(b);
5672
5673 vtn_function_emit(b, func, vtn_handle_body_instruction);
5674 progress = true;
5675 }
5676 }
5677 } while (progress);
5678
5679 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
5680 nir_function *entry_point = b->entry_point->func->impl->function;
5681 vtn_assert(entry_point);
5682
5683 /* post process entry_points with input params */
5684 if (entry_point->num_params && b->shader->info.stage == MESA_SHADER_KERNEL)
5685 entry_point = vtn_emit_kernel_entry_point_wrapper(b, entry_point);
5686
5687 /* structurize the CFG */
5688 nir_lower_goto_ifs(b->shader);
5689
5690 entry_point->is_entrypoint = true;
5691
5692 /* When multiple shader stages exist in the same SPIR-V module, we
5693 * generate input and output variables for every stage, in the same
5694 * NIR program. These dead variables can be invalid NIR. For example,
5695 * TCS outputs must be per-vertex arrays (or decorated 'patch'), while
5696 * VS output variables wouldn't be.
5697 *
5698 * To ensure we have valid NIR, we eliminate any dead inputs and outputs
5699 * right away. In order to do so, we must lower any constant initializers
5700 * on outputs so nir_remove_dead_variables sees that they're written to.
5701 */
5702 nir_lower_variable_initializers(b->shader, nir_var_shader_out);
5703 nir_remove_dead_variables(b->shader,
5704 nir_var_shader_in | nir_var_shader_out, NULL);
5705
5706 /* We sometimes generate bogus derefs that, while never used, give the
5707 * validator a bit of heartburn. Run dead code to get rid of them.
5708 */
5709 nir_opt_dce(b->shader);
5710
5711 /* Unparent the shader from the vtn_builder before we delete the builder */
5712 ralloc_steal(NULL, b->shader);
5713
5714 nir_shader *shader = b->shader;
5715 ralloc_free(b);
5716
5717 return shader;
5718 }