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