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