96ff09c36597765da2d43f20beba096ef9aa6961
[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 <stdio.h>
36
37 void
38 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
39 size_t spirv_offset, const char *message)
40 {
41 if (b->options->debug.func) {
42 b->options->debug.func(b->options->debug.private_data,
43 level, spirv_offset, message);
44 }
45
46 #ifndef NDEBUG
47 if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
48 fprintf(stderr, "%s\n", message);
49 #endif
50 }
51
52 void
53 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
54 size_t spirv_offset, const char *fmt, ...)
55 {
56 va_list args;
57 char *msg;
58
59 va_start(args, fmt);
60 msg = ralloc_vasprintf(NULL, fmt, args);
61 va_end(args);
62
63 vtn_log(b, level, spirv_offset, msg);
64
65 ralloc_free(msg);
66 }
67
68 static void
69 vtn_log_err(struct vtn_builder *b,
70 enum nir_spirv_debug_level level, const char *prefix,
71 const char *file, unsigned line,
72 const char *fmt, va_list args)
73 {
74 char *msg;
75
76 msg = ralloc_strdup(NULL, prefix);
77
78 #ifndef NDEBUG
79 ralloc_asprintf_append(&msg, " In file %s:%u\n", file, line);
80 #endif
81
82 ralloc_asprintf_append(&msg, " ");
83
84 ralloc_vasprintf_append(&msg, fmt, args);
85
86 ralloc_asprintf_append(&msg, "\n %zu bytes into the SPIR-V binary",
87 b->spirv_offset);
88
89 if (b->file) {
90 ralloc_asprintf_append(&msg,
91 "\n in SPIR-V source file %s, line %d, col %d",
92 b->file, b->line, b->col);
93 }
94
95 vtn_log(b, level, b->spirv_offset, msg);
96
97 ralloc_free(msg);
98 }
99
100 static void
101 vtn_dump_shader(struct vtn_builder *b, const char *path, const char *prefix)
102 {
103 static int idx = 0;
104
105 char filename[1024];
106 int len = snprintf(filename, sizeof(filename), "%s/%s-%d.spirv",
107 path, prefix, idx++);
108 if (len < 0 || len >= sizeof(filename))
109 return;
110
111 FILE *f = fopen(filename, "w");
112 if (f == NULL)
113 return;
114
115 fwrite(b->spirv, sizeof(*b->spirv), b->spirv_word_count, f);
116 fclose(f);
117
118 vtn_info("SPIR-V shader dumped to %s", filename);
119 }
120
121 void
122 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
123 const char *fmt, ...)
124 {
125 va_list args;
126
127 va_start(args, fmt);
128 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
129 file, line, fmt, args);
130 va_end(args);
131 }
132
133 void
134 _vtn_err(struct vtn_builder *b, const char *file, unsigned line,
135 const char *fmt, ...)
136 {
137 va_list args;
138
139 va_start(args, fmt);
140 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V ERROR:\n",
141 file, line, fmt, args);
142 va_end(args);
143 }
144
145 void
146 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
147 const char *fmt, ...)
148 {
149 va_list args;
150
151 va_start(args, fmt);
152 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
153 file, line, fmt, args);
154 va_end(args);
155
156 const char *dump_path = getenv("MESA_SPIRV_FAIL_DUMP_PATH");
157 if (dump_path)
158 vtn_dump_shader(b, dump_path, "fail");
159
160 longjmp(b->fail_jump, 1);
161 }
162
163 struct spec_constant_value {
164 bool is_double;
165 union {
166 uint32_t data32;
167 uint64_t data64;
168 };
169 };
170
171 static struct vtn_ssa_value *
172 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
173 {
174 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
175 val->type = type;
176
177 if (glsl_type_is_vector_or_scalar(type)) {
178 unsigned num_components = glsl_get_vector_elements(val->type);
179 unsigned bit_size = glsl_get_bit_size(val->type);
180 val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
181 } else {
182 unsigned elems = glsl_get_length(val->type);
183 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
184 if (glsl_type_is_matrix(type)) {
185 const struct glsl_type *elem_type =
186 glsl_vector_type(glsl_get_base_type(type),
187 glsl_get_vector_elements(type));
188
189 for (unsigned i = 0; i < elems; i++)
190 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
191 } else if (glsl_type_is_array(type)) {
192 const struct glsl_type *elem_type = glsl_get_array_element(type);
193 for (unsigned i = 0; i < elems; i++)
194 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
195 } else {
196 for (unsigned i = 0; i < elems; i++) {
197 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
198 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
199 }
200 }
201 }
202
203 return val;
204 }
205
206 static struct vtn_ssa_value *
207 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
208 const struct glsl_type *type)
209 {
210 struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
211
212 if (entry)
213 return entry->data;
214
215 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
216 val->type = type;
217
218 switch (glsl_get_base_type(type)) {
219 case GLSL_TYPE_INT:
220 case GLSL_TYPE_UINT:
221 case GLSL_TYPE_INT16:
222 case GLSL_TYPE_UINT16:
223 case GLSL_TYPE_UINT8:
224 case GLSL_TYPE_INT8:
225 case GLSL_TYPE_INT64:
226 case GLSL_TYPE_UINT64:
227 case GLSL_TYPE_BOOL:
228 case GLSL_TYPE_FLOAT:
229 case GLSL_TYPE_FLOAT16:
230 case GLSL_TYPE_DOUBLE: {
231 int bit_size = glsl_get_bit_size(type);
232 if (glsl_type_is_vector_or_scalar(type)) {
233 unsigned num_components = glsl_get_vector_elements(val->type);
234 nir_load_const_instr *load =
235 nir_load_const_instr_create(b->shader, num_components, bit_size);
236
237 load->value = constant->values[0];
238
239 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
240 val->def = &load->def;
241 } else {
242 assert(glsl_type_is_matrix(type));
243 unsigned rows = glsl_get_vector_elements(val->type);
244 unsigned columns = glsl_get_matrix_columns(val->type);
245 val->elems = ralloc_array(b, struct vtn_ssa_value *, columns);
246
247 for (unsigned i = 0; i < columns; i++) {
248 struct vtn_ssa_value *col_val = rzalloc(b, struct vtn_ssa_value);
249 col_val->type = glsl_get_column_type(val->type);
250 nir_load_const_instr *load =
251 nir_load_const_instr_create(b->shader, rows, bit_size);
252
253 load->value = constant->values[i];
254
255 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
256 col_val->def = &load->def;
257
258 val->elems[i] = col_val;
259 }
260 }
261 break;
262 }
263
264 case GLSL_TYPE_ARRAY: {
265 unsigned elems = glsl_get_length(val->type);
266 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
267 const struct glsl_type *elem_type = glsl_get_array_element(val->type);
268 for (unsigned i = 0; i < elems; i++)
269 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
270 elem_type);
271 break;
272 }
273
274 case GLSL_TYPE_STRUCT: {
275 unsigned elems = glsl_get_length(val->type);
276 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
277 for (unsigned i = 0; i < elems; i++) {
278 const struct glsl_type *elem_type =
279 glsl_get_struct_field(val->type, i);
280 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
281 elem_type);
282 }
283 break;
284 }
285
286 default:
287 vtn_fail("bad constant type");
288 }
289
290 return val;
291 }
292
293 struct vtn_ssa_value *
294 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
295 {
296 struct vtn_value *val = vtn_untyped_value(b, value_id);
297 switch (val->value_type) {
298 case vtn_value_type_undef:
299 return vtn_undef_ssa_value(b, val->type->type);
300
301 case vtn_value_type_constant:
302 return vtn_const_ssa_value(b, val->constant, val->type->type);
303
304 case vtn_value_type_ssa:
305 return val->ssa;
306
307 case vtn_value_type_pointer:
308 vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
309 struct vtn_ssa_value *ssa =
310 vtn_create_ssa_value(b, val->pointer->ptr_type->type);
311 ssa->def = vtn_pointer_to_ssa(b, val->pointer);
312 return ssa;
313
314 default:
315 vtn_fail("Invalid type for an SSA value");
316 }
317 }
318
319 static char *
320 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
321 unsigned word_count, unsigned *words_used)
322 {
323 char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
324 if (words_used) {
325 /* Ammount of space taken by the string (including the null) */
326 unsigned len = strlen(dup) + 1;
327 *words_used = DIV_ROUND_UP(len, sizeof(*words));
328 }
329 return dup;
330 }
331
332 const uint32_t *
333 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
334 const uint32_t *end, vtn_instruction_handler handler)
335 {
336 b->file = NULL;
337 b->line = -1;
338 b->col = -1;
339
340 const uint32_t *w = start;
341 while (w < end) {
342 SpvOp opcode = w[0] & SpvOpCodeMask;
343 unsigned count = w[0] >> SpvWordCountShift;
344 vtn_assert(count >= 1 && w + count <= end);
345
346 b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
347
348 switch (opcode) {
349 case SpvOpNop:
350 break; /* Do nothing */
351
352 case SpvOpLine:
353 b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
354 b->line = w[2];
355 b->col = w[3];
356 break;
357
358 case SpvOpNoLine:
359 b->file = NULL;
360 b->line = -1;
361 b->col = -1;
362 break;
363
364 default:
365 if (!handler(b, opcode, w, count))
366 return w;
367 break;
368 }
369
370 w += count;
371 }
372
373 b->spirv_offset = 0;
374 b->file = NULL;
375 b->line = -1;
376 b->col = -1;
377
378 assert(w == end);
379 return w;
380 }
381
382 static void
383 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
384 const uint32_t *w, unsigned count)
385 {
386 const char *ext = (const char *)&w[2];
387 switch (opcode) {
388 case SpvOpExtInstImport: {
389 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
390 if (strcmp(ext, "GLSL.std.450") == 0) {
391 val->ext_handler = vtn_handle_glsl450_instruction;
392 } else if ((strcmp(ext, "SPV_AMD_gcn_shader") == 0)
393 && (b->options && b->options->caps.gcn_shader)) {
394 val->ext_handler = vtn_handle_amd_gcn_shader_instruction;
395 } else if ((strcmp(ext, "SPV_AMD_shader_trinary_minmax") == 0)
396 && (b->options && b->options->caps.trinary_minmax)) {
397 val->ext_handler = vtn_handle_amd_shader_trinary_minmax_instruction;
398 } else {
399 vtn_fail("Unsupported extension: %s", ext);
400 }
401 break;
402 }
403
404 case SpvOpExtInst: {
405 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
406 bool handled = val->ext_handler(b, w[4], w, count);
407 vtn_assert(handled);
408 break;
409 }
410
411 default:
412 vtn_fail("Unhandled opcode");
413 }
414 }
415
416 static void
417 _foreach_decoration_helper(struct vtn_builder *b,
418 struct vtn_value *base_value,
419 int parent_member,
420 struct vtn_value *value,
421 vtn_decoration_foreach_cb cb, void *data)
422 {
423 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
424 int member;
425 if (dec->scope == VTN_DEC_DECORATION) {
426 member = parent_member;
427 } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
428 vtn_fail_if(value->value_type != vtn_value_type_type ||
429 value->type->base_type != vtn_base_type_struct,
430 "OpMemberDecorate and OpGroupMemberDecorate are only "
431 "allowed on OpTypeStruct");
432 /* This means we haven't recursed yet */
433 assert(value == base_value);
434
435 member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
436
437 vtn_fail_if(member >= base_value->type->length,
438 "OpMemberDecorate specifies member %d but the "
439 "OpTypeStruct has only %u members",
440 member, base_value->type->length);
441 } else {
442 /* Not a decoration */
443 assert(dec->scope == VTN_DEC_EXECUTION_MODE);
444 continue;
445 }
446
447 if (dec->group) {
448 assert(dec->group->value_type == vtn_value_type_decoration_group);
449 _foreach_decoration_helper(b, base_value, member, dec->group,
450 cb, data);
451 } else {
452 cb(b, base_value, member, dec, data);
453 }
454 }
455 }
456
457 /** Iterates (recursively if needed) over all of the decorations on a value
458 *
459 * This function iterates over all of the decorations applied to a given
460 * value. If it encounters a decoration group, it recurses into the group
461 * and iterates over all of those decorations as well.
462 */
463 void
464 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
465 vtn_decoration_foreach_cb cb, void *data)
466 {
467 _foreach_decoration_helper(b, value, -1, value, cb, data);
468 }
469
470 void
471 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
472 vtn_execution_mode_foreach_cb cb, void *data)
473 {
474 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
475 if (dec->scope != VTN_DEC_EXECUTION_MODE)
476 continue;
477
478 assert(dec->group == NULL);
479 cb(b, value, dec, data);
480 }
481 }
482
483 void
484 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
485 const uint32_t *w, unsigned count)
486 {
487 const uint32_t *w_end = w + count;
488 const uint32_t target = w[1];
489 w += 2;
490
491 switch (opcode) {
492 case SpvOpDecorationGroup:
493 vtn_push_value(b, target, vtn_value_type_decoration_group);
494 break;
495
496 case SpvOpDecorate:
497 case SpvOpMemberDecorate:
498 case SpvOpDecorateStringGOOGLE:
499 case SpvOpMemberDecorateStringGOOGLE:
500 case SpvOpExecutionMode: {
501 struct vtn_value *val = vtn_untyped_value(b, target);
502
503 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
504 switch (opcode) {
505 case SpvOpDecorate:
506 case SpvOpDecorateStringGOOGLE:
507 dec->scope = VTN_DEC_DECORATION;
508 break;
509 case SpvOpMemberDecorate:
510 case SpvOpMemberDecorateStringGOOGLE:
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 dec->scope = VTN_DEC_EXECUTION_MODE;
517 break;
518 default:
519 unreachable("Invalid decoration opcode");
520 }
521 dec->decoration = *(w++);
522 dec->literals = w;
523
524 /* Link into the list */
525 dec->next = val->decoration;
526 val->decoration = dec;
527 break;
528 }
529
530 case SpvOpGroupMemberDecorate:
531 case SpvOpGroupDecorate: {
532 struct vtn_value *group =
533 vtn_value(b, target, vtn_value_type_decoration_group);
534
535 for (; w < w_end; w++) {
536 struct vtn_value *val = vtn_untyped_value(b, *w);
537 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
538
539 dec->group = group;
540 if (opcode == SpvOpGroupDecorate) {
541 dec->scope = VTN_DEC_DECORATION;
542 } else {
543 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
544 vtn_fail_if(dec->scope < 0, /* Check for overflow */
545 "Member argument of OpGroupMemberDecorate too large");
546 }
547
548 /* Link into the list */
549 dec->next = val->decoration;
550 val->decoration = dec;
551 }
552 break;
553 }
554
555 default:
556 unreachable("Unhandled opcode");
557 }
558 }
559
560 struct member_decoration_ctx {
561 unsigned num_fields;
562 struct glsl_struct_field *fields;
563 struct vtn_type *type;
564 };
565
566 /** Returns true if two types are "compatible", i.e. you can do an OpLoad,
567 * OpStore, or OpCopyMemory between them without breaking anything.
568 * Technically, the SPIR-V rules require the exact same type ID but this lets
569 * us internally be a bit looser.
570 */
571 bool
572 vtn_types_compatible(struct vtn_builder *b,
573 struct vtn_type *t1, struct vtn_type *t2)
574 {
575 if (t1->id == t2->id)
576 return true;
577
578 if (t1->base_type != t2->base_type)
579 return false;
580
581 switch (t1->base_type) {
582 case vtn_base_type_void:
583 case vtn_base_type_scalar:
584 case vtn_base_type_vector:
585 case vtn_base_type_matrix:
586 case vtn_base_type_image:
587 case vtn_base_type_sampler:
588 case vtn_base_type_sampled_image:
589 return t1->type == t2->type;
590
591 case vtn_base_type_array:
592 return t1->length == t2->length &&
593 vtn_types_compatible(b, t1->array_element, t2->array_element);
594
595 case vtn_base_type_pointer:
596 return vtn_types_compatible(b, t1->deref, t2->deref);
597
598 case vtn_base_type_struct:
599 if (t1->length != t2->length)
600 return false;
601
602 for (unsigned i = 0; i < t1->length; i++) {
603 if (!vtn_types_compatible(b, t1->members[i], t2->members[i]))
604 return false;
605 }
606 return true;
607
608 case vtn_base_type_function:
609 /* This case shouldn't get hit since you can't copy around function
610 * types. Just require them to be identical.
611 */
612 return false;
613 }
614
615 vtn_fail("Invalid base type");
616 }
617
618 /* does a shallow copy of a vtn_type */
619
620 static struct vtn_type *
621 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
622 {
623 struct vtn_type *dest = ralloc(b, struct vtn_type);
624 *dest = *src;
625
626 switch (src->base_type) {
627 case vtn_base_type_void:
628 case vtn_base_type_scalar:
629 case vtn_base_type_vector:
630 case vtn_base_type_matrix:
631 case vtn_base_type_array:
632 case vtn_base_type_pointer:
633 case vtn_base_type_image:
634 case vtn_base_type_sampler:
635 case vtn_base_type_sampled_image:
636 /* Nothing more to do */
637 break;
638
639 case vtn_base_type_struct:
640 dest->members = ralloc_array(b, struct vtn_type *, src->length);
641 memcpy(dest->members, src->members,
642 src->length * sizeof(src->members[0]));
643
644 dest->offsets = ralloc_array(b, unsigned, src->length);
645 memcpy(dest->offsets, src->offsets,
646 src->length * sizeof(src->offsets[0]));
647 break;
648
649 case vtn_base_type_function:
650 dest->params = ralloc_array(b, struct vtn_type *, src->length);
651 memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
652 break;
653 }
654
655 return dest;
656 }
657
658 static struct vtn_type *
659 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
660 {
661 type->members[member] = vtn_type_copy(b, type->members[member]);
662 type = type->members[member];
663
664 /* We may have an array of matrices.... Oh, joy! */
665 while (glsl_type_is_array(type->type)) {
666 type->array_element = vtn_type_copy(b, type->array_element);
667 type = type->array_element;
668 }
669
670 vtn_assert(glsl_type_is_matrix(type->type));
671
672 return type;
673 }
674
675 static void
676 vtn_handle_access_qualifier(struct vtn_builder *b, struct vtn_type *type,
677 int member, enum gl_access_qualifier access)
678 {
679 type->members[member] = vtn_type_copy(b, type->members[member]);
680 type = type->members[member];
681
682 type->access |= access;
683 }
684
685 static void
686 struct_member_decoration_cb(struct vtn_builder *b,
687 struct vtn_value *val, int member,
688 const struct vtn_decoration *dec, void *void_ctx)
689 {
690 struct member_decoration_ctx *ctx = void_ctx;
691
692 if (member < 0)
693 return;
694
695 assert(member < ctx->num_fields);
696
697 switch (dec->decoration) {
698 case SpvDecorationRelaxedPrecision:
699 case SpvDecorationUniform:
700 break; /* FIXME: Do nothing with this for now. */
701 case SpvDecorationNonWritable:
702 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_WRITEABLE);
703 break;
704 case SpvDecorationNonReadable:
705 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_READABLE);
706 break;
707 case SpvDecorationVolatile:
708 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_VOLATILE);
709 break;
710 case SpvDecorationCoherent:
711 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_COHERENT);
712 break;
713 case SpvDecorationNoPerspective:
714 ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
715 break;
716 case SpvDecorationFlat:
717 ctx->fields[member].interpolation = INTERP_MODE_FLAT;
718 break;
719 case SpvDecorationCentroid:
720 ctx->fields[member].centroid = true;
721 break;
722 case SpvDecorationSample:
723 ctx->fields[member].sample = true;
724 break;
725 case SpvDecorationStream:
726 /* Vulkan only allows one GS stream */
727 vtn_assert(dec->literals[0] == 0);
728 break;
729 case SpvDecorationLocation:
730 ctx->fields[member].location = dec->literals[0];
731 break;
732 case SpvDecorationComponent:
733 break; /* FIXME: What should we do with these? */
734 case SpvDecorationBuiltIn:
735 ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
736 ctx->type->members[member]->is_builtin = true;
737 ctx->type->members[member]->builtin = dec->literals[0];
738 ctx->type->builtin_block = true;
739 break;
740 case SpvDecorationOffset:
741 ctx->type->offsets[member] = dec->literals[0];
742 break;
743 case SpvDecorationMatrixStride:
744 /* Handled as a second pass */
745 break;
746 case SpvDecorationColMajor:
747 break; /* Nothing to do here. Column-major is the default. */
748 case SpvDecorationRowMajor:
749 mutable_matrix_member(b, ctx->type, member)->row_major = true;
750 break;
751
752 case SpvDecorationPatch:
753 break;
754
755 case SpvDecorationSpecId:
756 case SpvDecorationBlock:
757 case SpvDecorationBufferBlock:
758 case SpvDecorationArrayStride:
759 case SpvDecorationGLSLShared:
760 case SpvDecorationGLSLPacked:
761 case SpvDecorationInvariant:
762 case SpvDecorationRestrict:
763 case SpvDecorationAliased:
764 case SpvDecorationConstant:
765 case SpvDecorationIndex:
766 case SpvDecorationBinding:
767 case SpvDecorationDescriptorSet:
768 case SpvDecorationLinkageAttributes:
769 case SpvDecorationNoContraction:
770 case SpvDecorationInputAttachmentIndex:
771 vtn_warn("Decoration not allowed on struct members: %s",
772 spirv_decoration_to_string(dec->decoration));
773 break;
774
775 case SpvDecorationXfbBuffer:
776 case SpvDecorationXfbStride:
777 vtn_warn("Vulkan does not have transform feedback");
778 break;
779
780 case SpvDecorationCPacked:
781 case SpvDecorationSaturatedConversion:
782 case SpvDecorationFuncParamAttr:
783 case SpvDecorationFPRoundingMode:
784 case SpvDecorationFPFastMathMode:
785 case SpvDecorationAlignment:
786 vtn_warn("Decoration only allowed for CL-style kernels: %s",
787 spirv_decoration_to_string(dec->decoration));
788 break;
789
790 case SpvDecorationHlslSemanticGOOGLE:
791 /* HLSL semantic decorations can safely be ignored by the driver. */
792 break;
793
794 default:
795 vtn_fail("Unhandled decoration");
796 }
797 }
798
799 /* Matrix strides are handled as a separate pass because we need to know
800 * whether the matrix is row-major or not first.
801 */
802 static void
803 struct_member_matrix_stride_cb(struct vtn_builder *b,
804 struct vtn_value *val, int member,
805 const struct vtn_decoration *dec,
806 void *void_ctx)
807 {
808 if (dec->decoration != SpvDecorationMatrixStride)
809 return;
810
811 vtn_fail_if(member < 0,
812 "The MatrixStride decoration is only allowed on members "
813 "of OpTypeStruct");
814
815 struct member_decoration_ctx *ctx = void_ctx;
816
817 struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
818 if (mat_type->row_major) {
819 mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
820 mat_type->stride = mat_type->array_element->stride;
821 mat_type->array_element->stride = dec->literals[0];
822 } else {
823 vtn_assert(mat_type->array_element->stride > 0);
824 mat_type->stride = dec->literals[0];
825 }
826 }
827
828 static void
829 type_decoration_cb(struct vtn_builder *b,
830 struct vtn_value *val, int member,
831 const struct vtn_decoration *dec, void *ctx)
832 {
833 struct vtn_type *type = val->type;
834
835 if (member != -1) {
836 /* This should have been handled by OpTypeStruct */
837 assert(val->type->base_type == vtn_base_type_struct);
838 assert(member >= 0 && member < val->type->length);
839 return;
840 }
841
842 switch (dec->decoration) {
843 case SpvDecorationArrayStride:
844 vtn_assert(type->base_type == vtn_base_type_matrix ||
845 type->base_type == vtn_base_type_array ||
846 type->base_type == vtn_base_type_pointer);
847 type->stride = dec->literals[0];
848 break;
849 case SpvDecorationBlock:
850 vtn_assert(type->base_type == vtn_base_type_struct);
851 type->block = true;
852 break;
853 case SpvDecorationBufferBlock:
854 vtn_assert(type->base_type == vtn_base_type_struct);
855 type->buffer_block = true;
856 break;
857 case SpvDecorationGLSLShared:
858 case SpvDecorationGLSLPacked:
859 /* Ignore these, since we get explicit offsets anyways */
860 break;
861
862 case SpvDecorationRowMajor:
863 case SpvDecorationColMajor:
864 case SpvDecorationMatrixStride:
865 case SpvDecorationBuiltIn:
866 case SpvDecorationNoPerspective:
867 case SpvDecorationFlat:
868 case SpvDecorationPatch:
869 case SpvDecorationCentroid:
870 case SpvDecorationSample:
871 case SpvDecorationVolatile:
872 case SpvDecorationCoherent:
873 case SpvDecorationNonWritable:
874 case SpvDecorationNonReadable:
875 case SpvDecorationUniform:
876 case SpvDecorationLocation:
877 case SpvDecorationComponent:
878 case SpvDecorationOffset:
879 case SpvDecorationXfbBuffer:
880 case SpvDecorationXfbStride:
881 case SpvDecorationHlslSemanticGOOGLE:
882 vtn_warn("Decoration only allowed for struct members: %s",
883 spirv_decoration_to_string(dec->decoration));
884 break;
885
886 case SpvDecorationStream:
887 /* We don't need to do anything here, as stream is filled up when
888 * aplying the decoration to a variable, just check that if it is not a
889 * struct member, it should be a struct.
890 */
891 vtn_assert(type->base_type == vtn_base_type_struct);
892 break;
893
894 case SpvDecorationRelaxedPrecision:
895 case SpvDecorationSpecId:
896 case SpvDecorationInvariant:
897 case SpvDecorationRestrict:
898 case SpvDecorationAliased:
899 case SpvDecorationConstant:
900 case SpvDecorationIndex:
901 case SpvDecorationBinding:
902 case SpvDecorationDescriptorSet:
903 case SpvDecorationLinkageAttributes:
904 case SpvDecorationNoContraction:
905 case SpvDecorationInputAttachmentIndex:
906 vtn_warn("Decoration not allowed on types: %s",
907 spirv_decoration_to_string(dec->decoration));
908 break;
909
910 case SpvDecorationCPacked:
911 case SpvDecorationSaturatedConversion:
912 case SpvDecorationFuncParamAttr:
913 case SpvDecorationFPRoundingMode:
914 case SpvDecorationFPFastMathMode:
915 case SpvDecorationAlignment:
916 vtn_warn("Decoration only allowed for CL-style kernels: %s",
917 spirv_decoration_to_string(dec->decoration));
918 break;
919
920 default:
921 vtn_fail("Unhandled decoration");
922 }
923 }
924
925 static unsigned
926 translate_image_format(struct vtn_builder *b, SpvImageFormat format)
927 {
928 switch (format) {
929 case SpvImageFormatUnknown: return 0; /* GL_NONE */
930 case SpvImageFormatRgba32f: return 0x8814; /* GL_RGBA32F */
931 case SpvImageFormatRgba16f: return 0x881A; /* GL_RGBA16F */
932 case SpvImageFormatR32f: return 0x822E; /* GL_R32F */
933 case SpvImageFormatRgba8: return 0x8058; /* GL_RGBA8 */
934 case SpvImageFormatRgba8Snorm: return 0x8F97; /* GL_RGBA8_SNORM */
935 case SpvImageFormatRg32f: return 0x8230; /* GL_RG32F */
936 case SpvImageFormatRg16f: return 0x822F; /* GL_RG16F */
937 case SpvImageFormatR11fG11fB10f: return 0x8C3A; /* GL_R11F_G11F_B10F */
938 case SpvImageFormatR16f: return 0x822D; /* GL_R16F */
939 case SpvImageFormatRgba16: return 0x805B; /* GL_RGBA16 */
940 case SpvImageFormatRgb10A2: return 0x8059; /* GL_RGB10_A2 */
941 case SpvImageFormatRg16: return 0x822C; /* GL_RG16 */
942 case SpvImageFormatRg8: return 0x822B; /* GL_RG8 */
943 case SpvImageFormatR16: return 0x822A; /* GL_R16 */
944 case SpvImageFormatR8: return 0x8229; /* GL_R8 */
945 case SpvImageFormatRgba16Snorm: return 0x8F9B; /* GL_RGBA16_SNORM */
946 case SpvImageFormatRg16Snorm: return 0x8F99; /* GL_RG16_SNORM */
947 case SpvImageFormatRg8Snorm: return 0x8F95; /* GL_RG8_SNORM */
948 case SpvImageFormatR16Snorm: return 0x8F98; /* GL_R16_SNORM */
949 case SpvImageFormatR8Snorm: return 0x8F94; /* GL_R8_SNORM */
950 case SpvImageFormatRgba32i: return 0x8D82; /* GL_RGBA32I */
951 case SpvImageFormatRgba16i: return 0x8D88; /* GL_RGBA16I */
952 case SpvImageFormatRgba8i: return 0x8D8E; /* GL_RGBA8I */
953 case SpvImageFormatR32i: return 0x8235; /* GL_R32I */
954 case SpvImageFormatRg32i: return 0x823B; /* GL_RG32I */
955 case SpvImageFormatRg16i: return 0x8239; /* GL_RG16I */
956 case SpvImageFormatRg8i: return 0x8237; /* GL_RG8I */
957 case SpvImageFormatR16i: return 0x8233; /* GL_R16I */
958 case SpvImageFormatR8i: return 0x8231; /* GL_R8I */
959 case SpvImageFormatRgba32ui: return 0x8D70; /* GL_RGBA32UI */
960 case SpvImageFormatRgba16ui: return 0x8D76; /* GL_RGBA16UI */
961 case SpvImageFormatRgba8ui: return 0x8D7C; /* GL_RGBA8UI */
962 case SpvImageFormatR32ui: return 0x8236; /* GL_R32UI */
963 case SpvImageFormatRgb10a2ui: return 0x906F; /* GL_RGB10_A2UI */
964 case SpvImageFormatRg32ui: return 0x823C; /* GL_RG32UI */
965 case SpvImageFormatRg16ui: return 0x823A; /* GL_RG16UI */
966 case SpvImageFormatRg8ui: return 0x8238; /* GL_RG8UI */
967 case SpvImageFormatR16ui: return 0x8234; /* GL_R16UI */
968 case SpvImageFormatR8ui: return 0x8232; /* GL_R8UI */
969 default:
970 vtn_fail("Invalid image format");
971 }
972 }
973
974 static struct vtn_type *
975 vtn_type_layout_std430(struct vtn_builder *b, struct vtn_type *type,
976 uint32_t *size_out, uint32_t *align_out)
977 {
978 switch (type->base_type) {
979 case vtn_base_type_scalar: {
980 uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
981 *size_out = comp_size;
982 *align_out = comp_size;
983 return type;
984 }
985
986 case vtn_base_type_vector: {
987 uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
988 unsigned align_comps = type->length == 3 ? 4 : type->length;
989 *size_out = comp_size * type->length,
990 *align_out = comp_size * align_comps;
991 return type;
992 }
993
994 case vtn_base_type_matrix:
995 case vtn_base_type_array: {
996 /* We're going to add an array stride */
997 type = vtn_type_copy(b, type);
998 uint32_t elem_size, elem_align;
999 type->array_element = vtn_type_layout_std430(b, type->array_element,
1000 &elem_size, &elem_align);
1001 type->stride = vtn_align_u32(elem_size, elem_align);
1002 *size_out = type->stride * type->length;
1003 *align_out = elem_align;
1004 return type;
1005 }
1006
1007 case vtn_base_type_struct: {
1008 /* We're going to add member offsets */
1009 type = vtn_type_copy(b, type);
1010 uint32_t offset = 0;
1011 uint32_t align = 0;
1012 for (unsigned i = 0; i < type->length; i++) {
1013 uint32_t mem_size, mem_align;
1014 type->members[i] = vtn_type_layout_std430(b, type->members[i],
1015 &mem_size, &mem_align);
1016 offset = vtn_align_u32(offset, mem_align);
1017 type->offsets[i] = offset;
1018 offset += mem_size;
1019 align = MAX2(align, mem_align);
1020 }
1021 *size_out = offset;
1022 *align_out = align;
1023 return type;
1024 }
1025
1026 default:
1027 unreachable("Invalid SPIR-V type for std430");
1028 }
1029 }
1030
1031 static void
1032 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
1033 const uint32_t *w, unsigned count)
1034 {
1035 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_type);
1036
1037 val->type = rzalloc(b, struct vtn_type);
1038 val->type->id = w[1];
1039
1040 switch (opcode) {
1041 case SpvOpTypeVoid:
1042 val->type->base_type = vtn_base_type_void;
1043 val->type->type = glsl_void_type();
1044 break;
1045 case SpvOpTypeBool:
1046 val->type->base_type = vtn_base_type_scalar;
1047 val->type->type = glsl_bool_type();
1048 val->type->length = 1;
1049 break;
1050 case SpvOpTypeInt: {
1051 int bit_size = w[2];
1052 const bool signedness = w[3];
1053 val->type->base_type = vtn_base_type_scalar;
1054 switch (bit_size) {
1055 case 64:
1056 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1057 break;
1058 case 32:
1059 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1060 break;
1061 case 16:
1062 val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1063 break;
1064 case 8:
1065 val->type->type = (signedness ? glsl_int8_t_type() : glsl_uint8_t_type());
1066 break;
1067 default:
1068 vtn_fail("Invalid int bit size");
1069 }
1070 val->type->length = 1;
1071 break;
1072 }
1073
1074 case SpvOpTypeFloat: {
1075 int bit_size = w[2];
1076 val->type->base_type = vtn_base_type_scalar;
1077 switch (bit_size) {
1078 case 16:
1079 val->type->type = glsl_float16_t_type();
1080 break;
1081 case 32:
1082 val->type->type = glsl_float_type();
1083 break;
1084 case 64:
1085 val->type->type = glsl_double_type();
1086 break;
1087 default:
1088 vtn_fail("Invalid float bit size");
1089 }
1090 val->type->length = 1;
1091 break;
1092 }
1093
1094 case SpvOpTypeVector: {
1095 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1096 unsigned elems = w[3];
1097
1098 vtn_fail_if(base->base_type != vtn_base_type_scalar,
1099 "Base type for OpTypeVector must be a scalar");
1100 vtn_fail_if((elems < 2 || elems > 4) && (elems != 8) && (elems != 16),
1101 "Invalid component count for OpTypeVector");
1102
1103 val->type->base_type = vtn_base_type_vector;
1104 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1105 val->type->length = elems;
1106 val->type->stride = glsl_get_bit_size(base->type) / 8;
1107 val->type->array_element = base;
1108 break;
1109 }
1110
1111 case SpvOpTypeMatrix: {
1112 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1113 unsigned columns = w[3];
1114
1115 vtn_fail_if(base->base_type != vtn_base_type_vector,
1116 "Base type for OpTypeMatrix must be a vector");
1117 vtn_fail_if(columns < 2 || columns > 4,
1118 "Invalid column count for OpTypeMatrix");
1119
1120 val->type->base_type = vtn_base_type_matrix;
1121 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1122 glsl_get_vector_elements(base->type),
1123 columns);
1124 vtn_fail_if(glsl_type_is_error(val->type->type),
1125 "Unsupported base type for OpTypeMatrix");
1126 assert(!glsl_type_is_error(val->type->type));
1127 val->type->length = columns;
1128 val->type->array_element = base;
1129 val->type->row_major = false;
1130 val->type->stride = 0;
1131 break;
1132 }
1133
1134 case SpvOpTypeRuntimeArray:
1135 case SpvOpTypeArray: {
1136 struct vtn_type *array_element =
1137 vtn_value(b, w[2], vtn_value_type_type)->type;
1138
1139 if (opcode == SpvOpTypeRuntimeArray) {
1140 /* A length of 0 is used to denote unsized arrays */
1141 val->type->length = 0;
1142 } else {
1143 val->type->length =
1144 vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
1145 }
1146
1147 val->type->base_type = vtn_base_type_array;
1148 val->type->type = glsl_array_type(array_element->type, val->type->length);
1149 val->type->array_element = array_element;
1150 val->type->stride = 0;
1151 break;
1152 }
1153
1154 case SpvOpTypeStruct: {
1155 unsigned num_fields = count - 2;
1156 val->type->base_type = vtn_base_type_struct;
1157 val->type->length = num_fields;
1158 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1159 val->type->offsets = ralloc_array(b, unsigned, num_fields);
1160
1161 NIR_VLA(struct glsl_struct_field, fields, count);
1162 for (unsigned i = 0; i < num_fields; i++) {
1163 val->type->members[i] =
1164 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
1165 fields[i] = (struct glsl_struct_field) {
1166 .type = val->type->members[i]->type,
1167 .name = ralloc_asprintf(b, "field%d", i),
1168 .location = -1,
1169 };
1170 }
1171
1172 struct member_decoration_ctx ctx = {
1173 .num_fields = num_fields,
1174 .fields = fields,
1175 .type = val->type
1176 };
1177
1178 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1179 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1180
1181 const char *name = val->name ? val->name : "struct";
1182
1183 val->type->type = glsl_struct_type(fields, num_fields, name);
1184 break;
1185 }
1186
1187 case SpvOpTypeFunction: {
1188 val->type->base_type = vtn_base_type_function;
1189 val->type->type = NULL;
1190
1191 val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
1192
1193 const unsigned num_params = count - 3;
1194 val->type->length = num_params;
1195 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1196 for (unsigned i = 0; i < count - 3; i++) {
1197 val->type->params[i] =
1198 vtn_value(b, w[i + 3], vtn_value_type_type)->type;
1199 }
1200 break;
1201 }
1202
1203 case SpvOpTypePointer: {
1204 SpvStorageClass storage_class = w[2];
1205 struct vtn_type *deref_type =
1206 vtn_value(b, w[3], vtn_value_type_type)->type;
1207
1208 val->type->base_type = vtn_base_type_pointer;
1209 val->type->storage_class = storage_class;
1210 val->type->deref = deref_type;
1211
1212 if (storage_class == SpvStorageClassUniform ||
1213 storage_class == SpvStorageClassStorageBuffer) {
1214 /* These can actually be stored to nir_variables and used as SSA
1215 * values so they need a real glsl_type.
1216 */
1217 val->type->type = glsl_vector_type(GLSL_TYPE_UINT, 2);
1218 }
1219
1220 if (storage_class == SpvStorageClassPushConstant) {
1221 /* These can actually be stored to nir_variables and used as SSA
1222 * values so they need a real glsl_type.
1223 */
1224 val->type->type = glsl_uint_type();
1225 }
1226
1227 if (storage_class == SpvStorageClassWorkgroup &&
1228 b->options->lower_workgroup_access_to_offsets) {
1229 uint32_t size, align;
1230 val->type->deref = vtn_type_layout_std430(b, val->type->deref,
1231 &size, &align);
1232 val->type->length = size;
1233 val->type->align = align;
1234 /* These can actually be stored to nir_variables and used as SSA
1235 * values so they need a real glsl_type.
1236 */
1237 val->type->type = glsl_uint_type();
1238 }
1239 break;
1240 }
1241
1242 case SpvOpTypeImage: {
1243 val->type->base_type = vtn_base_type_image;
1244
1245 const struct vtn_type *sampled_type =
1246 vtn_value(b, w[2], vtn_value_type_type)->type;
1247
1248 vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1249 glsl_get_bit_size(sampled_type->type) != 32,
1250 "Sampled type of OpTypeImage must be a 32-bit scalar");
1251
1252 enum glsl_sampler_dim dim;
1253 switch ((SpvDim)w[3]) {
1254 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
1255 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
1256 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
1257 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
1258 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
1259 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
1260 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1261 default:
1262 vtn_fail("Invalid SPIR-V image dimensionality");
1263 }
1264
1265 bool is_shadow = w[4];
1266 bool is_array = w[5];
1267 bool multisampled = w[6];
1268 unsigned sampled = w[7];
1269 SpvImageFormat format = w[8];
1270
1271 if (count > 9)
1272 val->type->access_qualifier = w[9];
1273 else
1274 val->type->access_qualifier = SpvAccessQualifierReadWrite;
1275
1276 if (multisampled) {
1277 if (dim == GLSL_SAMPLER_DIM_2D)
1278 dim = GLSL_SAMPLER_DIM_MS;
1279 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1280 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1281 else
1282 vtn_fail("Unsupported multisampled image type");
1283 }
1284
1285 val->type->image_format = translate_image_format(b, format);
1286
1287 enum glsl_base_type sampled_base_type =
1288 glsl_get_base_type(sampled_type->type);
1289 if (sampled == 1) {
1290 val->type->sampled = true;
1291 val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
1292 sampled_base_type);
1293 } else if (sampled == 2) {
1294 vtn_assert(!is_shadow);
1295 val->type->sampled = false;
1296 val->type->type = glsl_image_type(dim, is_array, sampled_base_type);
1297 } else {
1298 vtn_fail("We need to know if the image will be sampled");
1299 }
1300 break;
1301 }
1302
1303 case SpvOpTypeSampledImage:
1304 val->type->base_type = vtn_base_type_sampled_image;
1305 val->type->image = vtn_value(b, w[2], vtn_value_type_type)->type;
1306 val->type->type = val->type->image->type;
1307 break;
1308
1309 case SpvOpTypeSampler:
1310 /* The actual sampler type here doesn't really matter. It gets
1311 * thrown away the moment you combine it with an image. What really
1312 * matters is that it's a sampler type as opposed to an integer type
1313 * so the backend knows what to do.
1314 */
1315 val->type->base_type = vtn_base_type_sampler;
1316 val->type->type = glsl_bare_sampler_type();
1317 break;
1318
1319 case SpvOpTypeOpaque:
1320 case SpvOpTypeEvent:
1321 case SpvOpTypeDeviceEvent:
1322 case SpvOpTypeReserveId:
1323 case SpvOpTypeQueue:
1324 case SpvOpTypePipe:
1325 default:
1326 vtn_fail("Unhandled opcode");
1327 }
1328
1329 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1330 }
1331
1332 static nir_constant *
1333 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
1334 {
1335 nir_constant *c = rzalloc(b, nir_constant);
1336
1337 /* For pointers and other typeless things, we have to return something but
1338 * it doesn't matter what.
1339 */
1340 if (!type)
1341 return c;
1342
1343 switch (glsl_get_base_type(type)) {
1344 case GLSL_TYPE_INT:
1345 case GLSL_TYPE_UINT:
1346 case GLSL_TYPE_INT16:
1347 case GLSL_TYPE_UINT16:
1348 case GLSL_TYPE_UINT8:
1349 case GLSL_TYPE_INT8:
1350 case GLSL_TYPE_INT64:
1351 case GLSL_TYPE_UINT64:
1352 case GLSL_TYPE_BOOL:
1353 case GLSL_TYPE_FLOAT:
1354 case GLSL_TYPE_FLOAT16:
1355 case GLSL_TYPE_DOUBLE:
1356 /* Nothing to do here. It's already initialized to zero */
1357 break;
1358
1359 case GLSL_TYPE_ARRAY:
1360 vtn_assert(glsl_get_length(type) > 0);
1361 c->num_elements = glsl_get_length(type);
1362 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1363
1364 c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
1365 for (unsigned i = 1; i < c->num_elements; i++)
1366 c->elements[i] = c->elements[0];
1367 break;
1368
1369 case GLSL_TYPE_STRUCT:
1370 c->num_elements = glsl_get_length(type);
1371 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1372
1373 for (unsigned i = 0; i < c->num_elements; i++) {
1374 c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
1375 }
1376 break;
1377
1378 default:
1379 vtn_fail("Invalid type for null constant");
1380 }
1381
1382 return c;
1383 }
1384
1385 static void
1386 spec_constant_decoration_cb(struct vtn_builder *b, struct vtn_value *v,
1387 int member, const struct vtn_decoration *dec,
1388 void *data)
1389 {
1390 vtn_assert(member == -1);
1391 if (dec->decoration != SpvDecorationSpecId)
1392 return;
1393
1394 struct spec_constant_value *const_value = data;
1395
1396 for (unsigned i = 0; i < b->num_specializations; i++) {
1397 if (b->specializations[i].id == dec->literals[0]) {
1398 if (const_value->is_double)
1399 const_value->data64 = b->specializations[i].data64;
1400 else
1401 const_value->data32 = b->specializations[i].data32;
1402 return;
1403 }
1404 }
1405 }
1406
1407 static uint32_t
1408 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1409 uint32_t const_value)
1410 {
1411 struct spec_constant_value data;
1412 data.is_double = false;
1413 data.data32 = const_value;
1414 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1415 return data.data32;
1416 }
1417
1418 static uint64_t
1419 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1420 uint64_t const_value)
1421 {
1422 struct spec_constant_value data;
1423 data.is_double = true;
1424 data.data64 = const_value;
1425 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1426 return data.data64;
1427 }
1428
1429 static void
1430 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1431 struct vtn_value *val,
1432 int member,
1433 const struct vtn_decoration *dec,
1434 void *data)
1435 {
1436 vtn_assert(member == -1);
1437 if (dec->decoration != SpvDecorationBuiltIn ||
1438 dec->literals[0] != SpvBuiltInWorkgroupSize)
1439 return;
1440
1441 vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1442
1443 b->shader->info.cs.local_size[0] = val->constant->values[0].u32[0];
1444 b->shader->info.cs.local_size[1] = val->constant->values[0].u32[1];
1445 b->shader->info.cs.local_size[2] = val->constant->values[0].u32[2];
1446 }
1447
1448 static void
1449 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1450 const uint32_t *w, unsigned count)
1451 {
1452 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1453 val->constant = rzalloc(b, nir_constant);
1454 switch (opcode) {
1455 case SpvOpConstantTrue:
1456 case SpvOpConstantFalse:
1457 case SpvOpSpecConstantTrue:
1458 case SpvOpSpecConstantFalse: {
1459 vtn_fail_if(val->type->type != glsl_bool_type(),
1460 "Result type of %s must be OpTypeBool",
1461 spirv_op_to_string(opcode));
1462
1463 uint32_t int_val = (opcode == SpvOpConstantTrue ||
1464 opcode == SpvOpSpecConstantTrue);
1465
1466 if (opcode == SpvOpSpecConstantTrue ||
1467 opcode == SpvOpSpecConstantFalse)
1468 int_val = get_specialization(b, val, int_val);
1469
1470 val->constant->values[0].u32[0] = int_val ? NIR_TRUE : NIR_FALSE;
1471 break;
1472 }
1473
1474 case SpvOpConstant: {
1475 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1476 "Result type of %s must be a scalar",
1477 spirv_op_to_string(opcode));
1478 int bit_size = glsl_get_bit_size(val->type->type);
1479 switch (bit_size) {
1480 case 64:
1481 val->constant->values->u64[0] = vtn_u64_literal(&w[3]);
1482 break;
1483 case 32:
1484 val->constant->values->u32[0] = w[3];
1485 break;
1486 case 16:
1487 val->constant->values->u16[0] = w[3];
1488 break;
1489 case 8:
1490 val->constant->values->u8[0] = w[3];
1491 break;
1492 default:
1493 vtn_fail("Unsupported SpvOpConstant bit size");
1494 }
1495 break;
1496 }
1497
1498 case SpvOpSpecConstant: {
1499 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1500 "Result type of %s must be a scalar",
1501 spirv_op_to_string(opcode));
1502 int bit_size = glsl_get_bit_size(val->type->type);
1503 switch (bit_size) {
1504 case 64:
1505 val->constant->values[0].u64[0] =
1506 get_specialization64(b, val, vtn_u64_literal(&w[3]));
1507 break;
1508 case 32:
1509 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1510 break;
1511 case 16:
1512 val->constant->values[0].u16[0] = get_specialization(b, val, w[3]);
1513 break;
1514 case 8:
1515 val->constant->values[0].u8[0] = get_specialization(b, val, w[3]);
1516 break;
1517 default:
1518 vtn_fail("Unsupported SpvOpSpecConstant bit size");
1519 }
1520 break;
1521 }
1522
1523 case SpvOpSpecConstantComposite:
1524 case SpvOpConstantComposite: {
1525 unsigned elem_count = count - 3;
1526 vtn_fail_if(elem_count != val->type->length,
1527 "%s has %u constituents, expected %u",
1528 spirv_op_to_string(opcode), elem_count, val->type->length);
1529
1530 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1531 for (unsigned i = 0; i < elem_count; i++) {
1532 struct vtn_value *val = vtn_untyped_value(b, w[i + 3]);
1533
1534 if (val->value_type == vtn_value_type_constant) {
1535 elems[i] = val->constant;
1536 } else {
1537 vtn_fail_if(val->value_type != vtn_value_type_undef,
1538 "only constants or undefs allowed for "
1539 "SpvOpConstantComposite");
1540 /* to make it easier, just insert a NULL constant for now */
1541 elems[i] = vtn_null_constant(b, val->type->type);
1542 }
1543 }
1544
1545 switch (val->type->base_type) {
1546 case vtn_base_type_vector: {
1547 assert(glsl_type_is_vector(val->type->type));
1548 int bit_size = glsl_get_bit_size(val->type->type);
1549 for (unsigned i = 0; i < elem_count; i++) {
1550 switch (bit_size) {
1551 case 64:
1552 val->constant->values[0].u64[i] = elems[i]->values[0].u64[0];
1553 break;
1554 case 32:
1555 val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1556 break;
1557 case 16:
1558 val->constant->values[0].u16[i] = elems[i]->values[0].u16[0];
1559 break;
1560 case 8:
1561 val->constant->values[0].u8[i] = elems[i]->values[0].u8[0];
1562 break;
1563 default:
1564 vtn_fail("Invalid SpvOpConstantComposite bit size");
1565 }
1566 }
1567 break;
1568 }
1569
1570 case vtn_base_type_matrix:
1571 assert(glsl_type_is_matrix(val->type->type));
1572 for (unsigned i = 0; i < elem_count; i++)
1573 val->constant->values[i] = elems[i]->values[0];
1574 break;
1575
1576 case vtn_base_type_struct:
1577 case vtn_base_type_array:
1578 ralloc_steal(val->constant, elems);
1579 val->constant->num_elements = elem_count;
1580 val->constant->elements = elems;
1581 break;
1582
1583 default:
1584 vtn_fail("Result type of %s must be a composite type",
1585 spirv_op_to_string(opcode));
1586 }
1587 break;
1588 }
1589
1590 case SpvOpSpecConstantOp: {
1591 SpvOp opcode = get_specialization(b, val, w[3]);
1592 switch (opcode) {
1593 case SpvOpVectorShuffle: {
1594 struct vtn_value *v0 = &b->values[w[4]];
1595 struct vtn_value *v1 = &b->values[w[5]];
1596
1597 vtn_assert(v0->value_type == vtn_value_type_constant ||
1598 v0->value_type == vtn_value_type_undef);
1599 vtn_assert(v1->value_type == vtn_value_type_constant ||
1600 v1->value_type == vtn_value_type_undef);
1601
1602 unsigned len0 = glsl_get_vector_elements(v0->type->type);
1603 unsigned len1 = glsl_get_vector_elements(v1->type->type);
1604
1605 vtn_assert(len0 + len1 < 16);
1606
1607 unsigned bit_size = glsl_get_bit_size(val->type->type);
1608 unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1609 unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1610
1611 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1612 (void)bit_size0; (void)bit_size1;
1613
1614 if (bit_size == 64) {
1615 uint64_t u64[8];
1616 if (v0->value_type == vtn_value_type_constant) {
1617 for (unsigned i = 0; i < len0; i++)
1618 u64[i] = v0->constant->values[0].u64[i];
1619 }
1620 if (v1->value_type == vtn_value_type_constant) {
1621 for (unsigned i = 0; i < len1; i++)
1622 u64[len0 + i] = v1->constant->values[0].u64[i];
1623 }
1624
1625 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1626 uint32_t comp = w[i + 6];
1627 /* If component is not used, set the value to a known constant
1628 * to detect if it is wrongly used.
1629 */
1630 if (comp == (uint32_t)-1)
1631 val->constant->values[0].u64[j] = 0xdeadbeefdeadbeef;
1632 else
1633 val->constant->values[0].u64[j] = u64[comp];
1634 }
1635 } else {
1636 /* This is for both 32-bit and 16-bit values */
1637 uint32_t u32[8];
1638 if (v0->value_type == vtn_value_type_constant) {
1639 for (unsigned i = 0; i < len0; i++)
1640 u32[i] = v0->constant->values[0].u32[i];
1641 }
1642 if (v1->value_type == vtn_value_type_constant) {
1643 for (unsigned i = 0; i < len1; i++)
1644 u32[len0 + i] = v1->constant->values[0].u32[i];
1645 }
1646
1647 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1648 uint32_t comp = w[i + 6];
1649 /* If component is not used, set the value to a known constant
1650 * to detect if it is wrongly used.
1651 */
1652 if (comp == (uint32_t)-1)
1653 val->constant->values[0].u32[j] = 0xdeadbeef;
1654 else
1655 val->constant->values[0].u32[j] = u32[comp];
1656 }
1657 }
1658 break;
1659 }
1660
1661 case SpvOpCompositeExtract:
1662 case SpvOpCompositeInsert: {
1663 struct vtn_value *comp;
1664 unsigned deref_start;
1665 struct nir_constant **c;
1666 if (opcode == SpvOpCompositeExtract) {
1667 comp = vtn_value(b, w[4], vtn_value_type_constant);
1668 deref_start = 5;
1669 c = &comp->constant;
1670 } else {
1671 comp = vtn_value(b, w[5], vtn_value_type_constant);
1672 deref_start = 6;
1673 val->constant = nir_constant_clone(comp->constant,
1674 (nir_variable *)b);
1675 c = &val->constant;
1676 }
1677
1678 int elem = -1;
1679 int col = 0;
1680 const struct vtn_type *type = comp->type;
1681 for (unsigned i = deref_start; i < count; i++) {
1682 vtn_fail_if(w[i] > type->length,
1683 "%uth index of %s is %u but the type has only "
1684 "%u elements", i - deref_start,
1685 spirv_op_to_string(opcode), w[i], type->length);
1686
1687 switch (type->base_type) {
1688 case vtn_base_type_vector:
1689 elem = w[i];
1690 type = type->array_element;
1691 break;
1692
1693 case vtn_base_type_matrix:
1694 assert(col == 0 && elem == -1);
1695 col = w[i];
1696 elem = 0;
1697 type = type->array_element;
1698 break;
1699
1700 case vtn_base_type_array:
1701 c = &(*c)->elements[w[i]];
1702 type = type->array_element;
1703 break;
1704
1705 case vtn_base_type_struct:
1706 c = &(*c)->elements[w[i]];
1707 type = type->members[w[i]];
1708 break;
1709
1710 default:
1711 vtn_fail("%s must only index into composite types",
1712 spirv_op_to_string(opcode));
1713 }
1714 }
1715
1716 if (opcode == SpvOpCompositeExtract) {
1717 if (elem == -1) {
1718 val->constant = *c;
1719 } else {
1720 unsigned num_components = type->length;
1721 unsigned bit_size = glsl_get_bit_size(type->type);
1722 for (unsigned i = 0; i < num_components; i++)
1723 switch(bit_size) {
1724 case 64:
1725 val->constant->values[0].u64[i] = (*c)->values[col].u64[elem + i];
1726 break;
1727 case 32:
1728 val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1729 break;
1730 case 16:
1731 val->constant->values[0].u16[i] = (*c)->values[col].u16[elem + i];
1732 break;
1733 case 8:
1734 val->constant->values[0].u8[i] = (*c)->values[col].u8[elem + i];
1735 break;
1736 default:
1737 vtn_fail("Invalid SpvOpCompositeExtract bit size");
1738 }
1739 }
1740 } else {
1741 struct vtn_value *insert =
1742 vtn_value(b, w[4], vtn_value_type_constant);
1743 vtn_assert(insert->type == type);
1744 if (elem == -1) {
1745 *c = insert->constant;
1746 } else {
1747 unsigned num_components = type->length;
1748 unsigned bit_size = glsl_get_bit_size(type->type);
1749 for (unsigned i = 0; i < num_components; i++)
1750 switch (bit_size) {
1751 case 64:
1752 (*c)->values[col].u64[elem + i] = insert->constant->values[0].u64[i];
1753 break;
1754 case 32:
1755 (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1756 break;
1757 case 16:
1758 (*c)->values[col].u16[elem + i] = insert->constant->values[0].u16[i];
1759 break;
1760 case 8:
1761 (*c)->values[col].u8[elem + i] = insert->constant->values[0].u8[i];
1762 break;
1763 default:
1764 vtn_fail("Invalid SpvOpCompositeInsert bit size");
1765 }
1766 }
1767 }
1768 break;
1769 }
1770
1771 default: {
1772 bool swap;
1773 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
1774 nir_alu_type src_alu_type = dst_alu_type;
1775 unsigned num_components = glsl_get_vector_elements(val->type->type);
1776 unsigned bit_size;
1777
1778 vtn_assert(count <= 7);
1779
1780 switch (opcode) {
1781 case SpvOpSConvert:
1782 case SpvOpFConvert:
1783 /* We have a source in a conversion */
1784 src_alu_type =
1785 nir_get_nir_type_for_glsl_type(
1786 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1787 /* We use the bitsize of the conversion source to evaluate the opcode later */
1788 bit_size = glsl_get_bit_size(
1789 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1790 break;
1791 default:
1792 bit_size = glsl_get_bit_size(val->type->type);
1793 };
1794
1795 nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
1796 nir_alu_type_get_type_size(src_alu_type),
1797 nir_alu_type_get_type_size(dst_alu_type));
1798 nir_const_value src[4];
1799
1800 for (unsigned i = 0; i < count - 4; i++) {
1801 struct vtn_value *src_val =
1802 vtn_value(b, w[4 + i], vtn_value_type_constant);
1803
1804 /* If this is an unsized source, pull the bit size from the
1805 * source; otherwise, we'll use the bit size from the destination.
1806 */
1807 if (!nir_alu_type_get_type_size(nir_op_infos[op].input_types[i]))
1808 bit_size = glsl_get_bit_size(src_val->type->type);
1809
1810 unsigned j = swap ? 1 - i : i;
1811 src[j] = src_val->constant->values[0];
1812 }
1813
1814 val->constant->values[0] =
1815 nir_eval_const_opcode(op, num_components, bit_size, src);
1816 break;
1817 } /* default */
1818 }
1819 break;
1820 }
1821
1822 case SpvOpConstantNull:
1823 val->constant = vtn_null_constant(b, val->type->type);
1824 break;
1825
1826 case SpvOpConstantSampler:
1827 vtn_fail("OpConstantSampler requires Kernel Capability");
1828 break;
1829
1830 default:
1831 vtn_fail("Unhandled opcode");
1832 }
1833
1834 /* Now that we have the value, update the workgroup size if needed */
1835 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1836 }
1837
1838 struct vtn_ssa_value *
1839 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1840 {
1841 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1842 val->type = type;
1843
1844 if (!glsl_type_is_vector_or_scalar(type)) {
1845 unsigned elems = glsl_get_length(type);
1846 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1847 for (unsigned i = 0; i < elems; i++) {
1848 const struct glsl_type *child_type;
1849
1850 switch (glsl_get_base_type(type)) {
1851 case GLSL_TYPE_INT:
1852 case GLSL_TYPE_UINT:
1853 case GLSL_TYPE_INT16:
1854 case GLSL_TYPE_UINT16:
1855 case GLSL_TYPE_UINT8:
1856 case GLSL_TYPE_INT8:
1857 case GLSL_TYPE_INT64:
1858 case GLSL_TYPE_UINT64:
1859 case GLSL_TYPE_BOOL:
1860 case GLSL_TYPE_FLOAT:
1861 case GLSL_TYPE_FLOAT16:
1862 case GLSL_TYPE_DOUBLE:
1863 child_type = glsl_get_column_type(type);
1864 break;
1865 case GLSL_TYPE_ARRAY:
1866 child_type = glsl_get_array_element(type);
1867 break;
1868 case GLSL_TYPE_STRUCT:
1869 child_type = glsl_get_struct_field(type, i);
1870 break;
1871 default:
1872 vtn_fail("unkown base type");
1873 }
1874
1875 val->elems[i] = vtn_create_ssa_value(b, child_type);
1876 }
1877 }
1878
1879 return val;
1880 }
1881
1882 static nir_tex_src
1883 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1884 {
1885 nir_tex_src src;
1886 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
1887 src.src_type = type;
1888 return src;
1889 }
1890
1891 static void
1892 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
1893 const uint32_t *w, unsigned count)
1894 {
1895 if (opcode == SpvOpSampledImage) {
1896 struct vtn_value *val =
1897 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
1898 val->sampled_image = ralloc(b, struct vtn_sampled_image);
1899 val->sampled_image->type =
1900 vtn_value(b, w[1], vtn_value_type_type)->type;
1901 val->sampled_image->image =
1902 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
1903 val->sampled_image->sampler =
1904 vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
1905 return;
1906 } else if (opcode == SpvOpImage) {
1907 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
1908 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
1909 if (src_val->value_type == vtn_value_type_sampled_image) {
1910 val->pointer = src_val->sampled_image->image;
1911 } else {
1912 vtn_assert(src_val->value_type == vtn_value_type_pointer);
1913 val->pointer = src_val->pointer;
1914 }
1915 return;
1916 }
1917
1918 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1919 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1920
1921 struct vtn_sampled_image sampled;
1922 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
1923 if (sampled_val->value_type == vtn_value_type_sampled_image) {
1924 sampled = *sampled_val->sampled_image;
1925 } else {
1926 vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
1927 sampled.type = sampled_val->pointer->type;
1928 sampled.image = NULL;
1929 sampled.sampler = sampled_val->pointer;
1930 }
1931
1932 const struct glsl_type *image_type = sampled.type->type;
1933 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
1934 const bool is_array = glsl_sampler_type_is_array(image_type);
1935
1936 /* Figure out the base texture operation */
1937 nir_texop texop;
1938 switch (opcode) {
1939 case SpvOpImageSampleImplicitLod:
1940 case SpvOpImageSampleDrefImplicitLod:
1941 case SpvOpImageSampleProjImplicitLod:
1942 case SpvOpImageSampleProjDrefImplicitLod:
1943 texop = nir_texop_tex;
1944 break;
1945
1946 case SpvOpImageSampleExplicitLod:
1947 case SpvOpImageSampleDrefExplicitLod:
1948 case SpvOpImageSampleProjExplicitLod:
1949 case SpvOpImageSampleProjDrefExplicitLod:
1950 texop = nir_texop_txl;
1951 break;
1952
1953 case SpvOpImageFetch:
1954 if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
1955 texop = nir_texop_txf_ms;
1956 } else {
1957 texop = nir_texop_txf;
1958 }
1959 break;
1960
1961 case SpvOpImageGather:
1962 case SpvOpImageDrefGather:
1963 texop = nir_texop_tg4;
1964 break;
1965
1966 case SpvOpImageQuerySizeLod:
1967 case SpvOpImageQuerySize:
1968 texop = nir_texop_txs;
1969 break;
1970
1971 case SpvOpImageQueryLod:
1972 texop = nir_texop_lod;
1973 break;
1974
1975 case SpvOpImageQueryLevels:
1976 texop = nir_texop_query_levels;
1977 break;
1978
1979 case SpvOpImageQuerySamples:
1980 texop = nir_texop_texture_samples;
1981 break;
1982
1983 default:
1984 vtn_fail("Unhandled opcode");
1985 }
1986
1987 nir_tex_src srcs[10]; /* 10 should be enough */
1988 nir_tex_src *p = srcs;
1989
1990 nir_deref_instr *sampler = vtn_pointer_to_deref(b, sampled.sampler);
1991 nir_deref_instr *texture =
1992 sampled.image ? vtn_pointer_to_deref(b, sampled.image) : sampler;
1993
1994 p->src = nir_src_for_ssa(&texture->dest.ssa);
1995 p->src_type = nir_tex_src_texture_deref;
1996 p++;
1997
1998 switch (texop) {
1999 case nir_texop_tex:
2000 case nir_texop_txb:
2001 case nir_texop_txl:
2002 case nir_texop_txd:
2003 case nir_texop_tg4:
2004 /* These operations require a sampler */
2005 p->src = nir_src_for_ssa(&sampler->dest.ssa);
2006 p->src_type = nir_tex_src_sampler_deref;
2007 p++;
2008 break;
2009 case nir_texop_txf:
2010 case nir_texop_txf_ms:
2011 case nir_texop_txs:
2012 case nir_texop_lod:
2013 case nir_texop_query_levels:
2014 case nir_texop_texture_samples:
2015 case nir_texop_samples_identical:
2016 /* These don't */
2017 break;
2018 case nir_texop_txf_ms_mcs:
2019 vtn_fail("unexpected nir_texop_txf_ms_mcs");
2020 }
2021
2022 unsigned idx = 4;
2023
2024 struct nir_ssa_def *coord;
2025 unsigned coord_components;
2026 switch (opcode) {
2027 case SpvOpImageSampleImplicitLod:
2028 case SpvOpImageSampleExplicitLod:
2029 case SpvOpImageSampleDrefImplicitLod:
2030 case SpvOpImageSampleDrefExplicitLod:
2031 case SpvOpImageSampleProjImplicitLod:
2032 case SpvOpImageSampleProjExplicitLod:
2033 case SpvOpImageSampleProjDrefImplicitLod:
2034 case SpvOpImageSampleProjDrefExplicitLod:
2035 case SpvOpImageFetch:
2036 case SpvOpImageGather:
2037 case SpvOpImageDrefGather:
2038 case SpvOpImageQueryLod: {
2039 /* All these types have the coordinate as their first real argument */
2040 switch (sampler_dim) {
2041 case GLSL_SAMPLER_DIM_1D:
2042 case GLSL_SAMPLER_DIM_BUF:
2043 coord_components = 1;
2044 break;
2045 case GLSL_SAMPLER_DIM_2D:
2046 case GLSL_SAMPLER_DIM_RECT:
2047 case GLSL_SAMPLER_DIM_MS:
2048 coord_components = 2;
2049 break;
2050 case GLSL_SAMPLER_DIM_3D:
2051 case GLSL_SAMPLER_DIM_CUBE:
2052 coord_components = 3;
2053 break;
2054 default:
2055 vtn_fail("Invalid sampler type");
2056 }
2057
2058 if (is_array && texop != nir_texop_lod)
2059 coord_components++;
2060
2061 coord = vtn_ssa_value(b, w[idx++])->def;
2062 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
2063 (1 << coord_components) - 1));
2064 p->src_type = nir_tex_src_coord;
2065 p++;
2066 break;
2067 }
2068
2069 default:
2070 coord = NULL;
2071 coord_components = 0;
2072 break;
2073 }
2074
2075 switch (opcode) {
2076 case SpvOpImageSampleProjImplicitLod:
2077 case SpvOpImageSampleProjExplicitLod:
2078 case SpvOpImageSampleProjDrefImplicitLod:
2079 case SpvOpImageSampleProjDrefExplicitLod:
2080 /* These have the projector as the last coordinate component */
2081 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
2082 p->src_type = nir_tex_src_projector;
2083 p++;
2084 break;
2085
2086 default:
2087 break;
2088 }
2089
2090 bool is_shadow = false;
2091 unsigned gather_component = 0;
2092 switch (opcode) {
2093 case SpvOpImageSampleDrefImplicitLod:
2094 case SpvOpImageSampleDrefExplicitLod:
2095 case SpvOpImageSampleProjDrefImplicitLod:
2096 case SpvOpImageSampleProjDrefExplicitLod:
2097 case SpvOpImageDrefGather:
2098 /* These all have an explicit depth value as their next source */
2099 is_shadow = true;
2100 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2101 break;
2102
2103 case SpvOpImageGather:
2104 /* This has a component as its next source */
2105 gather_component =
2106 vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
2107 break;
2108
2109 default:
2110 break;
2111 }
2112
2113 /* For OpImageQuerySizeLod, we always have an LOD */
2114 if (opcode == SpvOpImageQuerySizeLod)
2115 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2116
2117 /* Now we need to handle some number of optional arguments */
2118 const struct vtn_ssa_value *gather_offsets = NULL;
2119 if (idx < count) {
2120 uint32_t operands = w[idx++];
2121
2122 if (operands & SpvImageOperandsBiasMask) {
2123 vtn_assert(texop == nir_texop_tex);
2124 texop = nir_texop_txb;
2125 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
2126 }
2127
2128 if (operands & SpvImageOperandsLodMask) {
2129 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2130 texop == nir_texop_txs);
2131 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2132 }
2133
2134 if (operands & SpvImageOperandsGradMask) {
2135 vtn_assert(texop == nir_texop_txl);
2136 texop = nir_texop_txd;
2137 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
2138 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
2139 }
2140
2141 if (operands & SpvImageOperandsOffsetMask ||
2142 operands & SpvImageOperandsConstOffsetMask)
2143 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
2144
2145 if (operands & SpvImageOperandsConstOffsetsMask) {
2146 nir_tex_src none = {0};
2147 gather_offsets = vtn_ssa_value(b, w[idx++]);
2148 (*p++) = none;
2149 }
2150
2151 if (operands & SpvImageOperandsSampleMask) {
2152 vtn_assert(texop == nir_texop_txf_ms);
2153 texop = nir_texop_txf_ms;
2154 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2155 }
2156 }
2157 /* We should have now consumed exactly all of the arguments */
2158 vtn_assert(idx == count);
2159
2160 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2161 instr->op = texop;
2162
2163 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2164
2165 instr->coord_components = coord_components;
2166 instr->sampler_dim = sampler_dim;
2167 instr->is_array = is_array;
2168 instr->is_shadow = is_shadow;
2169 instr->is_new_style_shadow =
2170 is_shadow && glsl_get_components(ret_type->type) == 1;
2171 instr->component = gather_component;
2172
2173 switch (glsl_get_sampler_result_type(image_type)) {
2174 case GLSL_TYPE_FLOAT: instr->dest_type = nir_type_float; break;
2175 case GLSL_TYPE_INT: instr->dest_type = nir_type_int; break;
2176 case GLSL_TYPE_UINT: instr->dest_type = nir_type_uint; break;
2177 case GLSL_TYPE_BOOL: instr->dest_type = nir_type_bool; break;
2178 default:
2179 vtn_fail("Invalid base type for sampler result");
2180 }
2181
2182 nir_ssa_dest_init(&instr->instr, &instr->dest,
2183 nir_tex_instr_dest_size(instr), 32, NULL);
2184
2185 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2186 nir_tex_instr_dest_size(instr));
2187
2188 nir_ssa_def *def;
2189 nir_instr *instruction;
2190 if (gather_offsets) {
2191 vtn_assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
2192 vtn_assert(glsl_get_length(gather_offsets->type) == 4);
2193 nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
2194
2195 /* Copy the current instruction 4x */
2196 for (uint32_t i = 1; i < 4; i++) {
2197 instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
2198 instrs[i]->op = instr->op;
2199 instrs[i]->coord_components = instr->coord_components;
2200 instrs[i]->sampler_dim = instr->sampler_dim;
2201 instrs[i]->is_array = instr->is_array;
2202 instrs[i]->is_shadow = instr->is_shadow;
2203 instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
2204 instrs[i]->component = instr->component;
2205 instrs[i]->dest_type = instr->dest_type;
2206
2207 memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
2208
2209 nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
2210 nir_tex_instr_dest_size(instr), 32, NULL);
2211 }
2212
2213 /* Fill in the last argument with the offset from the passed in offsets
2214 * and insert the instruction into the stream.
2215 */
2216 for (uint32_t i = 0; i < 4; i++) {
2217 nir_tex_src src;
2218 src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
2219 src.src_type = nir_tex_src_offset;
2220 instrs[i]->src[instrs[i]->num_srcs - 1] = src;
2221 nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
2222 }
2223
2224 /* Combine the results of the 4 instructions by taking their .w
2225 * components
2226 */
2227 nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
2228 nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
2229 vec4->dest.write_mask = 0xf;
2230 for (uint32_t i = 0; i < 4; i++) {
2231 vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
2232 vec4->src[i].swizzle[0] = 3;
2233 }
2234 def = &vec4->dest.dest.ssa;
2235 instruction = &vec4->instr;
2236 } else {
2237 def = &instr->dest.ssa;
2238 instruction = &instr->instr;
2239 }
2240
2241 val->ssa = vtn_create_ssa_value(b, ret_type->type);
2242 val->ssa->def = def;
2243
2244 nir_builder_instr_insert(&b->nb, instruction);
2245 }
2246
2247 static void
2248 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2249 const uint32_t *w, nir_src *src)
2250 {
2251 switch (opcode) {
2252 case SpvOpAtomicIIncrement:
2253 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2254 break;
2255
2256 case SpvOpAtomicIDecrement:
2257 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2258 break;
2259
2260 case SpvOpAtomicISub:
2261 src[0] =
2262 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
2263 break;
2264
2265 case SpvOpAtomicCompareExchange:
2266 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
2267 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
2268 break;
2269
2270 case SpvOpAtomicExchange:
2271 case SpvOpAtomicIAdd:
2272 case SpvOpAtomicSMin:
2273 case SpvOpAtomicUMin:
2274 case SpvOpAtomicSMax:
2275 case SpvOpAtomicUMax:
2276 case SpvOpAtomicAnd:
2277 case SpvOpAtomicOr:
2278 case SpvOpAtomicXor:
2279 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
2280 break;
2281
2282 default:
2283 vtn_fail("Invalid SPIR-V atomic");
2284 }
2285 }
2286
2287 static nir_ssa_def *
2288 get_image_coord(struct vtn_builder *b, uint32_t value)
2289 {
2290 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
2291
2292 /* The image_load_store intrinsics assume a 4-dim coordinate */
2293 unsigned dim = glsl_get_vector_elements(coord->type);
2294 unsigned swizzle[4];
2295 for (unsigned i = 0; i < 4; i++)
2296 swizzle[i] = MIN2(i, dim - 1);
2297
2298 return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
2299 }
2300
2301 static nir_ssa_def *
2302 expand_to_vec4(nir_builder *b, nir_ssa_def *value)
2303 {
2304 if (value->num_components == 4)
2305 return value;
2306
2307 unsigned swiz[4];
2308 for (unsigned i = 0; i < 4; i++)
2309 swiz[i] = i < value->num_components ? i : 0;
2310 return nir_swizzle(b, value, swiz, 4, false);
2311 }
2312
2313 static void
2314 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2315 const uint32_t *w, unsigned count)
2316 {
2317 /* Just get this one out of the way */
2318 if (opcode == SpvOpImageTexelPointer) {
2319 struct vtn_value *val =
2320 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2321 val->image = ralloc(b, struct vtn_image_pointer);
2322
2323 val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2324 val->image->coord = get_image_coord(b, w[4]);
2325 val->image->sample = vtn_ssa_value(b, w[5])->def;
2326 return;
2327 }
2328
2329 struct vtn_image_pointer image;
2330
2331 switch (opcode) {
2332 case SpvOpAtomicExchange:
2333 case SpvOpAtomicCompareExchange:
2334 case SpvOpAtomicCompareExchangeWeak:
2335 case SpvOpAtomicIIncrement:
2336 case SpvOpAtomicIDecrement:
2337 case SpvOpAtomicIAdd:
2338 case SpvOpAtomicISub:
2339 case SpvOpAtomicLoad:
2340 case SpvOpAtomicSMin:
2341 case SpvOpAtomicUMin:
2342 case SpvOpAtomicSMax:
2343 case SpvOpAtomicUMax:
2344 case SpvOpAtomicAnd:
2345 case SpvOpAtomicOr:
2346 case SpvOpAtomicXor:
2347 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2348 break;
2349
2350 case SpvOpAtomicStore:
2351 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2352 break;
2353
2354 case SpvOpImageQuerySize:
2355 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2356 image.coord = NULL;
2357 image.sample = NULL;
2358 break;
2359
2360 case SpvOpImageRead:
2361 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2362 image.coord = get_image_coord(b, w[4]);
2363
2364 if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
2365 vtn_assert(w[5] == SpvImageOperandsSampleMask);
2366 image.sample = vtn_ssa_value(b, w[6])->def;
2367 } else {
2368 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2369 }
2370 break;
2371
2372 case SpvOpImageWrite:
2373 image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2374 image.coord = get_image_coord(b, w[2]);
2375
2376 /* texel = w[3] */
2377
2378 if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
2379 vtn_assert(w[4] == SpvImageOperandsSampleMask);
2380 image.sample = vtn_ssa_value(b, w[5])->def;
2381 } else {
2382 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2383 }
2384 break;
2385
2386 default:
2387 vtn_fail("Invalid image opcode");
2388 }
2389
2390 nir_intrinsic_op op;
2391 switch (opcode) {
2392 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_deref_##N; break;
2393 OP(ImageQuerySize, size)
2394 OP(ImageRead, load)
2395 OP(ImageWrite, store)
2396 OP(AtomicLoad, load)
2397 OP(AtomicStore, store)
2398 OP(AtomicExchange, atomic_exchange)
2399 OP(AtomicCompareExchange, atomic_comp_swap)
2400 OP(AtomicIIncrement, atomic_add)
2401 OP(AtomicIDecrement, atomic_add)
2402 OP(AtomicIAdd, atomic_add)
2403 OP(AtomicISub, atomic_add)
2404 OP(AtomicSMin, atomic_min)
2405 OP(AtomicUMin, atomic_min)
2406 OP(AtomicSMax, atomic_max)
2407 OP(AtomicUMax, atomic_max)
2408 OP(AtomicAnd, atomic_and)
2409 OP(AtomicOr, atomic_or)
2410 OP(AtomicXor, atomic_xor)
2411 #undef OP
2412 default:
2413 vtn_fail("Invalid image opcode");
2414 }
2415
2416 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2417
2418 nir_deref_instr *image_deref = vtn_pointer_to_deref(b, image.image);
2419 intrin->src[0] = nir_src_for_ssa(&image_deref->dest.ssa);
2420
2421 /* ImageQuerySize doesn't take any extra parameters */
2422 if (opcode != SpvOpImageQuerySize) {
2423 /* The image coordinate is always 4 components but we may not have that
2424 * many. Swizzle to compensate.
2425 */
2426 intrin->src[1] = nir_src_for_ssa(expand_to_vec4(&b->nb, image.coord));
2427 intrin->src[2] = nir_src_for_ssa(image.sample);
2428 }
2429
2430 switch (opcode) {
2431 case SpvOpAtomicLoad:
2432 case SpvOpImageQuerySize:
2433 case SpvOpImageRead:
2434 break;
2435 case SpvOpAtomicStore:
2436 case SpvOpImageWrite: {
2437 const uint32_t value_id = opcode == SpvOpAtomicStore ? w[4] : w[3];
2438 nir_ssa_def *value = vtn_ssa_value(b, value_id)->def;
2439 /* nir_intrinsic_image_deref_store always takes a vec4 value */
2440 assert(op == nir_intrinsic_image_deref_store);
2441 intrin->num_components = 4;
2442 intrin->src[3] = nir_src_for_ssa(expand_to_vec4(&b->nb, value));
2443 break;
2444 }
2445
2446 case SpvOpAtomicCompareExchange:
2447 case SpvOpAtomicIIncrement:
2448 case SpvOpAtomicIDecrement:
2449 case SpvOpAtomicExchange:
2450 case SpvOpAtomicIAdd:
2451 case SpvOpAtomicISub:
2452 case SpvOpAtomicSMin:
2453 case SpvOpAtomicUMin:
2454 case SpvOpAtomicSMax:
2455 case SpvOpAtomicUMax:
2456 case SpvOpAtomicAnd:
2457 case SpvOpAtomicOr:
2458 case SpvOpAtomicXor:
2459 fill_common_atomic_sources(b, opcode, w, &intrin->src[3]);
2460 break;
2461
2462 default:
2463 vtn_fail("Invalid image opcode");
2464 }
2465
2466 if (opcode != SpvOpImageWrite && opcode != SpvOpAtomicStore) {
2467 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2468 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2469
2470 unsigned dest_components = glsl_get_vector_elements(type->type);
2471 intrin->num_components = nir_intrinsic_infos[op].dest_components;
2472 if (intrin->num_components == 0)
2473 intrin->num_components = dest_components;
2474
2475 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2476 intrin->num_components, 32, NULL);
2477
2478 nir_builder_instr_insert(&b->nb, &intrin->instr);
2479
2480 nir_ssa_def *result = &intrin->dest.ssa;
2481 if (intrin->num_components != dest_components)
2482 result = nir_channels(&b->nb, result, (1 << dest_components) - 1);
2483
2484 val->ssa = vtn_create_ssa_value(b, type->type);
2485 val->ssa->def = result;
2486 } else {
2487 nir_builder_instr_insert(&b->nb, &intrin->instr);
2488 }
2489 }
2490
2491 static nir_intrinsic_op
2492 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2493 {
2494 switch (opcode) {
2495 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
2496 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
2497 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2498 OP(AtomicExchange, atomic_exchange)
2499 OP(AtomicCompareExchange, atomic_comp_swap)
2500 OP(AtomicIIncrement, atomic_add)
2501 OP(AtomicIDecrement, atomic_add)
2502 OP(AtomicIAdd, atomic_add)
2503 OP(AtomicISub, atomic_add)
2504 OP(AtomicSMin, atomic_imin)
2505 OP(AtomicUMin, atomic_umin)
2506 OP(AtomicSMax, atomic_imax)
2507 OP(AtomicUMax, atomic_umax)
2508 OP(AtomicAnd, atomic_and)
2509 OP(AtomicOr, atomic_or)
2510 OP(AtomicXor, atomic_xor)
2511 #undef OP
2512 default:
2513 vtn_fail("Invalid SSBO atomic");
2514 }
2515 }
2516
2517 static nir_intrinsic_op
2518 get_uniform_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2519 {
2520 switch (opcode) {
2521 #define OP(S, N) case SpvOp##S: return nir_intrinsic_atomic_counter_ ##N;
2522 OP(AtomicLoad, read_deref)
2523 OP(AtomicExchange, exchange)
2524 OP(AtomicCompareExchange, comp_swap)
2525 OP(AtomicIIncrement, inc_deref)
2526 OP(AtomicIDecrement, post_dec_deref)
2527 OP(AtomicIAdd, add_deref)
2528 OP(AtomicISub, add_deref)
2529 OP(AtomicUMin, min_deref)
2530 OP(AtomicUMax, max_deref)
2531 OP(AtomicAnd, and_deref)
2532 OP(AtomicOr, or_deref)
2533 OP(AtomicXor, xor_deref)
2534 #undef OP
2535 default:
2536 /* We left the following out: AtomicStore, AtomicSMin and
2537 * AtomicSmax. Right now there are not nir intrinsics for them. At this
2538 * moment Atomic Counter support is needed for ARB_spirv support, so is
2539 * only need to support GLSL Atomic Counters that are uints and don't
2540 * allow direct storage.
2541 */
2542 unreachable("Invalid uniform atomic");
2543 }
2544 }
2545
2546 static nir_intrinsic_op
2547 get_shared_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2548 {
2549 switch (opcode) {
2550 case SpvOpAtomicLoad: return nir_intrinsic_load_shared;
2551 case SpvOpAtomicStore: return nir_intrinsic_store_shared;
2552 #define OP(S, N) case SpvOp##S: return nir_intrinsic_shared_##N;
2553 OP(AtomicExchange, atomic_exchange)
2554 OP(AtomicCompareExchange, atomic_comp_swap)
2555 OP(AtomicIIncrement, atomic_add)
2556 OP(AtomicIDecrement, atomic_add)
2557 OP(AtomicIAdd, atomic_add)
2558 OP(AtomicISub, atomic_add)
2559 OP(AtomicSMin, atomic_imin)
2560 OP(AtomicUMin, atomic_umin)
2561 OP(AtomicSMax, atomic_imax)
2562 OP(AtomicUMax, atomic_umax)
2563 OP(AtomicAnd, atomic_and)
2564 OP(AtomicOr, atomic_or)
2565 OP(AtomicXor, atomic_xor)
2566 #undef OP
2567 default:
2568 vtn_fail("Invalid shared atomic");
2569 }
2570 }
2571
2572 static nir_intrinsic_op
2573 get_deref_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2574 {
2575 switch (opcode) {
2576 case SpvOpAtomicLoad: return nir_intrinsic_load_deref;
2577 case SpvOpAtomicStore: return nir_intrinsic_store_deref;
2578 #define OP(S, N) case SpvOp##S: return nir_intrinsic_deref_##N;
2579 OP(AtomicExchange, atomic_exchange)
2580 OP(AtomicCompareExchange, atomic_comp_swap)
2581 OP(AtomicIIncrement, atomic_add)
2582 OP(AtomicIDecrement, atomic_add)
2583 OP(AtomicIAdd, atomic_add)
2584 OP(AtomicISub, atomic_add)
2585 OP(AtomicSMin, atomic_imin)
2586 OP(AtomicUMin, atomic_umin)
2587 OP(AtomicSMax, atomic_imax)
2588 OP(AtomicUMax, atomic_umax)
2589 OP(AtomicAnd, atomic_and)
2590 OP(AtomicOr, atomic_or)
2591 OP(AtomicXor, atomic_xor)
2592 #undef OP
2593 default:
2594 vtn_fail("Invalid shared atomic");
2595 }
2596 }
2597
2598 /*
2599 * Handles shared atomics, ssbo atomics and atomic counters.
2600 */
2601 static void
2602 vtn_handle_atomics(struct vtn_builder *b, SpvOp opcode,
2603 const uint32_t *w, unsigned count)
2604 {
2605 struct vtn_pointer *ptr;
2606 nir_intrinsic_instr *atomic;
2607
2608 switch (opcode) {
2609 case SpvOpAtomicLoad:
2610 case SpvOpAtomicExchange:
2611 case SpvOpAtomicCompareExchange:
2612 case SpvOpAtomicCompareExchangeWeak:
2613 case SpvOpAtomicIIncrement:
2614 case SpvOpAtomicIDecrement:
2615 case SpvOpAtomicIAdd:
2616 case SpvOpAtomicISub:
2617 case SpvOpAtomicSMin:
2618 case SpvOpAtomicUMin:
2619 case SpvOpAtomicSMax:
2620 case SpvOpAtomicUMax:
2621 case SpvOpAtomicAnd:
2622 case SpvOpAtomicOr:
2623 case SpvOpAtomicXor:
2624 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2625 break;
2626
2627 case SpvOpAtomicStore:
2628 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2629 break;
2630
2631 default:
2632 vtn_fail("Invalid SPIR-V atomic");
2633 }
2634
2635 /*
2636 SpvScope scope = w[4];
2637 SpvMemorySemanticsMask semantics = w[5];
2638 */
2639
2640 /* uniform as "atomic counter uniform" */
2641 if (ptr->mode == vtn_variable_mode_uniform) {
2642 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
2643 const struct glsl_type *deref_type = deref->type;
2644 nir_intrinsic_op op = get_uniform_nir_atomic_op(b, opcode);
2645 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2646 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
2647
2648 /* SSBO needs to initialize index/offset. In this case we don't need to,
2649 * as that info is already stored on the ptr->var->var nir_variable (see
2650 * vtn_create_variable)
2651 */
2652
2653 switch (opcode) {
2654 case SpvOpAtomicLoad:
2655 atomic->num_components = glsl_get_vector_elements(deref_type);
2656 break;
2657
2658 case SpvOpAtomicStore:
2659 atomic->num_components = glsl_get_vector_elements(deref_type);
2660 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2661 break;
2662
2663 case SpvOpAtomicExchange:
2664 case SpvOpAtomicCompareExchange:
2665 case SpvOpAtomicCompareExchangeWeak:
2666 case SpvOpAtomicIIncrement:
2667 case SpvOpAtomicIDecrement:
2668 case SpvOpAtomicIAdd:
2669 case SpvOpAtomicISub:
2670 case SpvOpAtomicSMin:
2671 case SpvOpAtomicUMin:
2672 case SpvOpAtomicSMax:
2673 case SpvOpAtomicUMax:
2674 case SpvOpAtomicAnd:
2675 case SpvOpAtomicOr:
2676 case SpvOpAtomicXor:
2677 /* Nothing: we don't need to call fill_common_atomic_sources here, as
2678 * atomic counter uniforms doesn't have sources
2679 */
2680 break;
2681
2682 default:
2683 unreachable("Invalid SPIR-V atomic");
2684
2685 }
2686 } else if (ptr->mode == vtn_variable_mode_workgroup &&
2687 !b->options->lower_workgroup_access_to_offsets) {
2688 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
2689 const struct glsl_type *deref_type = deref->type;
2690 nir_intrinsic_op op = get_deref_nir_atomic_op(b, opcode);
2691 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2692 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
2693
2694 switch (opcode) {
2695 case SpvOpAtomicLoad:
2696 atomic->num_components = glsl_get_vector_elements(deref_type);
2697 break;
2698
2699 case SpvOpAtomicStore:
2700 atomic->num_components = glsl_get_vector_elements(deref_type);
2701 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2702 atomic->src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2703 break;
2704
2705 case SpvOpAtomicExchange:
2706 case SpvOpAtomicCompareExchange:
2707 case SpvOpAtomicCompareExchangeWeak:
2708 case SpvOpAtomicIIncrement:
2709 case SpvOpAtomicIDecrement:
2710 case SpvOpAtomicIAdd:
2711 case SpvOpAtomicISub:
2712 case SpvOpAtomicSMin:
2713 case SpvOpAtomicUMin:
2714 case SpvOpAtomicSMax:
2715 case SpvOpAtomicUMax:
2716 case SpvOpAtomicAnd:
2717 case SpvOpAtomicOr:
2718 case SpvOpAtomicXor:
2719 fill_common_atomic_sources(b, opcode, w, &atomic->src[1]);
2720 break;
2721
2722 default:
2723 vtn_fail("Invalid SPIR-V atomic");
2724
2725 }
2726 } else {
2727 nir_ssa_def *offset, *index;
2728 offset = vtn_pointer_to_offset(b, ptr, &index);
2729
2730 nir_intrinsic_op op;
2731 if (ptr->mode == vtn_variable_mode_ssbo) {
2732 op = get_ssbo_nir_atomic_op(b, opcode);
2733 } else {
2734 vtn_assert(ptr->mode == vtn_variable_mode_workgroup &&
2735 b->options->lower_workgroup_access_to_offsets);
2736 op = get_shared_nir_atomic_op(b, opcode);
2737 }
2738
2739 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2740
2741 int src = 0;
2742 switch (opcode) {
2743 case SpvOpAtomicLoad:
2744 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2745 if (ptr->mode == vtn_variable_mode_ssbo)
2746 atomic->src[src++] = nir_src_for_ssa(index);
2747 atomic->src[src++] = nir_src_for_ssa(offset);
2748 break;
2749
2750 case SpvOpAtomicStore:
2751 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2752 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2753 atomic->src[src++] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2754 if (ptr->mode == vtn_variable_mode_ssbo)
2755 atomic->src[src++] = nir_src_for_ssa(index);
2756 atomic->src[src++] = nir_src_for_ssa(offset);
2757 break;
2758
2759 case SpvOpAtomicExchange:
2760 case SpvOpAtomicCompareExchange:
2761 case SpvOpAtomicCompareExchangeWeak:
2762 case SpvOpAtomicIIncrement:
2763 case SpvOpAtomicIDecrement:
2764 case SpvOpAtomicIAdd:
2765 case SpvOpAtomicISub:
2766 case SpvOpAtomicSMin:
2767 case SpvOpAtomicUMin:
2768 case SpvOpAtomicSMax:
2769 case SpvOpAtomicUMax:
2770 case SpvOpAtomicAnd:
2771 case SpvOpAtomicOr:
2772 case SpvOpAtomicXor:
2773 if (ptr->mode == vtn_variable_mode_ssbo)
2774 atomic->src[src++] = nir_src_for_ssa(index);
2775 atomic->src[src++] = nir_src_for_ssa(offset);
2776 fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
2777 break;
2778
2779 default:
2780 vtn_fail("Invalid SPIR-V atomic");
2781 }
2782 }
2783
2784 if (opcode != SpvOpAtomicStore) {
2785 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2786
2787 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2788 glsl_get_vector_elements(type->type),
2789 glsl_get_bit_size(type->type), NULL);
2790
2791 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2792 val->ssa = rzalloc(b, struct vtn_ssa_value);
2793 val->ssa->def = &atomic->dest.ssa;
2794 val->ssa->type = type->type;
2795 }
2796
2797 nir_builder_instr_insert(&b->nb, &atomic->instr);
2798 }
2799
2800 static nir_alu_instr *
2801 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
2802 {
2803 nir_op op;
2804 switch (num_components) {
2805 case 1: op = nir_op_imov; break;
2806 case 2: op = nir_op_vec2; break;
2807 case 3: op = nir_op_vec3; break;
2808 case 4: op = nir_op_vec4; break;
2809 default: vtn_fail("bad vector size");
2810 }
2811
2812 nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
2813 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2814 bit_size, NULL);
2815 vec->dest.write_mask = (1 << num_components) - 1;
2816
2817 return vec;
2818 }
2819
2820 struct vtn_ssa_value *
2821 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2822 {
2823 if (src->transposed)
2824 return src->transposed;
2825
2826 struct vtn_ssa_value *dest =
2827 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2828
2829 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2830 nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
2831 glsl_get_bit_size(src->type));
2832 if (glsl_type_is_vector_or_scalar(src->type)) {
2833 vec->src[0].src = nir_src_for_ssa(src->def);
2834 vec->src[0].swizzle[0] = i;
2835 } else {
2836 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2837 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2838 vec->src[j].swizzle[0] = i;
2839 }
2840 }
2841 nir_builder_instr_insert(&b->nb, &vec->instr);
2842 dest->elems[i]->def = &vec->dest.dest.ssa;
2843 }
2844
2845 dest->transposed = src;
2846
2847 return dest;
2848 }
2849
2850 nir_ssa_def *
2851 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2852 {
2853 return nir_channel(&b->nb, src, index);
2854 }
2855
2856 nir_ssa_def *
2857 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2858 unsigned index)
2859 {
2860 nir_alu_instr *vec = create_vec(b, src->num_components,
2861 src->bit_size);
2862
2863 for (unsigned i = 0; i < src->num_components; i++) {
2864 if (i == index) {
2865 vec->src[i].src = nir_src_for_ssa(insert);
2866 } else {
2867 vec->src[i].src = nir_src_for_ssa(src);
2868 vec->src[i].swizzle[0] = i;
2869 }
2870 }
2871
2872 nir_builder_instr_insert(&b->nb, &vec->instr);
2873
2874 return &vec->dest.dest.ssa;
2875 }
2876
2877 nir_ssa_def *
2878 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2879 nir_ssa_def *index)
2880 {
2881 nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
2882 for (unsigned i = 1; i < src->num_components; i++)
2883 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2884 vtn_vector_extract(b, src, i), dest);
2885
2886 return dest;
2887 }
2888
2889 nir_ssa_def *
2890 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2891 nir_ssa_def *insert, nir_ssa_def *index)
2892 {
2893 nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
2894 for (unsigned i = 1; i < src->num_components; i++)
2895 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2896 vtn_vector_insert(b, src, insert, i), dest);
2897
2898 return dest;
2899 }
2900
2901 static nir_ssa_def *
2902 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
2903 nir_ssa_def *src0, nir_ssa_def *src1,
2904 const uint32_t *indices)
2905 {
2906 nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
2907
2908 for (unsigned i = 0; i < num_components; i++) {
2909 uint32_t index = indices[i];
2910 if (index == 0xffffffff) {
2911 vec->src[i].src =
2912 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
2913 } else if (index < src0->num_components) {
2914 vec->src[i].src = nir_src_for_ssa(src0);
2915 vec->src[i].swizzle[0] = index;
2916 } else {
2917 vec->src[i].src = nir_src_for_ssa(src1);
2918 vec->src[i].swizzle[0] = index - src0->num_components;
2919 }
2920 }
2921
2922 nir_builder_instr_insert(&b->nb, &vec->instr);
2923
2924 return &vec->dest.dest.ssa;
2925 }
2926
2927 /*
2928 * Concatentates a number of vectors/scalars together to produce a vector
2929 */
2930 static nir_ssa_def *
2931 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
2932 unsigned num_srcs, nir_ssa_def **srcs)
2933 {
2934 nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
2935
2936 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2937 *
2938 * "When constructing a vector, there must be at least two Constituent
2939 * operands."
2940 */
2941 vtn_assert(num_srcs >= 2);
2942
2943 unsigned dest_idx = 0;
2944 for (unsigned i = 0; i < num_srcs; i++) {
2945 nir_ssa_def *src = srcs[i];
2946 vtn_assert(dest_idx + src->num_components <= num_components);
2947 for (unsigned j = 0; j < src->num_components; j++) {
2948 vec->src[dest_idx].src = nir_src_for_ssa(src);
2949 vec->src[dest_idx].swizzle[0] = j;
2950 dest_idx++;
2951 }
2952 }
2953
2954 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2955 *
2956 * "When constructing a vector, the total number of components in all
2957 * the operands must equal the number of components in Result Type."
2958 */
2959 vtn_assert(dest_idx == num_components);
2960
2961 nir_builder_instr_insert(&b->nb, &vec->instr);
2962
2963 return &vec->dest.dest.ssa;
2964 }
2965
2966 static struct vtn_ssa_value *
2967 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
2968 {
2969 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
2970 dest->type = src->type;
2971
2972 if (glsl_type_is_vector_or_scalar(src->type)) {
2973 dest->def = src->def;
2974 } else {
2975 unsigned elems = glsl_get_length(src->type);
2976
2977 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
2978 for (unsigned i = 0; i < elems; i++)
2979 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
2980 }
2981
2982 return dest;
2983 }
2984
2985 static struct vtn_ssa_value *
2986 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
2987 struct vtn_ssa_value *insert, const uint32_t *indices,
2988 unsigned num_indices)
2989 {
2990 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
2991
2992 struct vtn_ssa_value *cur = dest;
2993 unsigned i;
2994 for (i = 0; i < num_indices - 1; i++) {
2995 cur = cur->elems[indices[i]];
2996 }
2997
2998 if (glsl_type_is_vector_or_scalar(cur->type)) {
2999 /* According to the SPIR-V spec, OpCompositeInsert may work down to
3000 * the component granularity. In that case, the last index will be
3001 * the index to insert the scalar into the vector.
3002 */
3003
3004 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
3005 } else {
3006 cur->elems[indices[i]] = insert;
3007 }
3008
3009 return dest;
3010 }
3011
3012 static struct vtn_ssa_value *
3013 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
3014 const uint32_t *indices, unsigned num_indices)
3015 {
3016 struct vtn_ssa_value *cur = src;
3017 for (unsigned i = 0; i < num_indices; i++) {
3018 if (glsl_type_is_vector_or_scalar(cur->type)) {
3019 vtn_assert(i == num_indices - 1);
3020 /* According to the SPIR-V spec, OpCompositeExtract may work down to
3021 * the component granularity. The last index will be the index of the
3022 * vector to extract.
3023 */
3024
3025 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
3026 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
3027 ret->def = vtn_vector_extract(b, cur->def, indices[i]);
3028 return ret;
3029 } else {
3030 cur = cur->elems[indices[i]];
3031 }
3032 }
3033
3034 return cur;
3035 }
3036
3037 static void
3038 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
3039 const uint32_t *w, unsigned count)
3040 {
3041 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
3042 const struct glsl_type *type =
3043 vtn_value(b, w[1], vtn_value_type_type)->type->type;
3044 val->ssa = vtn_create_ssa_value(b, type);
3045
3046 switch (opcode) {
3047 case SpvOpVectorExtractDynamic:
3048 val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
3049 vtn_ssa_value(b, w[4])->def);
3050 break;
3051
3052 case SpvOpVectorInsertDynamic:
3053 val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
3054 vtn_ssa_value(b, w[4])->def,
3055 vtn_ssa_value(b, w[5])->def);
3056 break;
3057
3058 case SpvOpVectorShuffle:
3059 val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
3060 vtn_ssa_value(b, w[3])->def,
3061 vtn_ssa_value(b, w[4])->def,
3062 w + 5);
3063 break;
3064
3065 case SpvOpCompositeConstruct: {
3066 unsigned elems = count - 3;
3067 assume(elems >= 1);
3068 if (glsl_type_is_vector_or_scalar(type)) {
3069 nir_ssa_def *srcs[NIR_MAX_VEC_COMPONENTS];
3070 for (unsigned i = 0; i < elems; i++)
3071 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
3072 val->ssa->def =
3073 vtn_vector_construct(b, glsl_get_vector_elements(type),
3074 elems, srcs);
3075 } else {
3076 val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
3077 for (unsigned i = 0; i < elems; i++)
3078 val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
3079 }
3080 break;
3081 }
3082 case SpvOpCompositeExtract:
3083 val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
3084 w + 4, count - 4);
3085 break;
3086
3087 case SpvOpCompositeInsert:
3088 val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
3089 vtn_ssa_value(b, w[3]),
3090 w + 5, count - 5);
3091 break;
3092
3093 case SpvOpCopyObject:
3094 val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
3095 break;
3096
3097 default:
3098 vtn_fail("unknown composite operation");
3099 }
3100 }
3101
3102 static void
3103 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
3104 {
3105 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
3106 nir_builder_instr_insert(&b->nb, &intrin->instr);
3107 }
3108
3109 static void
3110 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
3111 SpvMemorySemanticsMask semantics)
3112 {
3113 static const SpvMemorySemanticsMask all_memory_semantics =
3114 SpvMemorySemanticsUniformMemoryMask |
3115 SpvMemorySemanticsWorkgroupMemoryMask |
3116 SpvMemorySemanticsAtomicCounterMemoryMask |
3117 SpvMemorySemanticsImageMemoryMask;
3118
3119 /* If we're not actually doing a memory barrier, bail */
3120 if (!(semantics & all_memory_semantics))
3121 return;
3122
3123 /* GL and Vulkan don't have these */
3124 vtn_assert(scope != SpvScopeCrossDevice);
3125
3126 if (scope == SpvScopeSubgroup)
3127 return; /* Nothing to do here */
3128
3129 if (scope == SpvScopeWorkgroup) {
3130 vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
3131 return;
3132 }
3133
3134 /* There's only two scopes thing left */
3135 vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
3136
3137 if ((semantics & all_memory_semantics) == all_memory_semantics) {
3138 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3139 return;
3140 }
3141
3142 /* Issue a bunch of more specific barriers */
3143 uint32_t bits = semantics;
3144 while (bits) {
3145 SpvMemorySemanticsMask semantic = 1 << u_bit_scan(&bits);
3146 switch (semantic) {
3147 case SpvMemorySemanticsUniformMemoryMask:
3148 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3149 break;
3150 case SpvMemorySemanticsWorkgroupMemoryMask:
3151 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3152 break;
3153 case SpvMemorySemanticsAtomicCounterMemoryMask:
3154 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3155 break;
3156 case SpvMemorySemanticsImageMemoryMask:
3157 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3158 break;
3159 default:
3160 break;;
3161 }
3162 }
3163 }
3164
3165 static void
3166 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3167 const uint32_t *w, unsigned count)
3168 {
3169 switch (opcode) {
3170 case SpvOpEmitVertex:
3171 case SpvOpEmitStreamVertex:
3172 case SpvOpEndPrimitive:
3173 case SpvOpEndStreamPrimitive: {
3174 nir_intrinsic_op intrinsic_op;
3175 switch (opcode) {
3176 case SpvOpEmitVertex:
3177 case SpvOpEmitStreamVertex:
3178 intrinsic_op = nir_intrinsic_emit_vertex;
3179 break;
3180 case SpvOpEndPrimitive:
3181 case SpvOpEndStreamPrimitive:
3182 intrinsic_op = nir_intrinsic_end_primitive;
3183 break;
3184 default:
3185 unreachable("Invalid opcode");
3186 }
3187
3188 nir_intrinsic_instr *intrin =
3189 nir_intrinsic_instr_create(b->shader, intrinsic_op);
3190
3191 switch (opcode) {
3192 case SpvOpEmitStreamVertex:
3193 case SpvOpEndStreamPrimitive: {
3194 unsigned stream = vtn_constant_value(b, w[1])->values[0].u32[0];
3195 nir_intrinsic_set_stream_id(intrin, stream);
3196 break;
3197 }
3198
3199 default:
3200 break;
3201 }
3202
3203 nir_builder_instr_insert(&b->nb, &intrin->instr);
3204 break;
3205 }
3206
3207 case SpvOpMemoryBarrier: {
3208 SpvScope scope = vtn_constant_value(b, w[1])->values[0].u32[0];
3209 SpvMemorySemanticsMask semantics =
3210 vtn_constant_value(b, w[2])->values[0].u32[0];
3211 vtn_emit_memory_barrier(b, scope, semantics);
3212 return;
3213 }
3214
3215 case SpvOpControlBarrier: {
3216 SpvScope execution_scope =
3217 vtn_constant_value(b, w[1])->values[0].u32[0];
3218 if (execution_scope == SpvScopeWorkgroup)
3219 vtn_emit_barrier(b, nir_intrinsic_barrier);
3220
3221 SpvScope memory_scope =
3222 vtn_constant_value(b, w[2])->values[0].u32[0];
3223 SpvMemorySemanticsMask memory_semantics =
3224 vtn_constant_value(b, w[3])->values[0].u32[0];
3225 vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3226 break;
3227 }
3228
3229 default:
3230 unreachable("unknown barrier instruction");
3231 }
3232 }
3233
3234 static unsigned
3235 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
3236 SpvExecutionMode mode)
3237 {
3238 switch (mode) {
3239 case SpvExecutionModeInputPoints:
3240 case SpvExecutionModeOutputPoints:
3241 return 0; /* GL_POINTS */
3242 case SpvExecutionModeInputLines:
3243 return 1; /* GL_LINES */
3244 case SpvExecutionModeInputLinesAdjacency:
3245 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
3246 case SpvExecutionModeTriangles:
3247 return 4; /* GL_TRIANGLES */
3248 case SpvExecutionModeInputTrianglesAdjacency:
3249 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
3250 case SpvExecutionModeQuads:
3251 return 7; /* GL_QUADS */
3252 case SpvExecutionModeIsolines:
3253 return 0x8E7A; /* GL_ISOLINES */
3254 case SpvExecutionModeOutputLineStrip:
3255 return 3; /* GL_LINE_STRIP */
3256 case SpvExecutionModeOutputTriangleStrip:
3257 return 5; /* GL_TRIANGLE_STRIP */
3258 default:
3259 vtn_fail("Invalid primitive type");
3260 }
3261 }
3262
3263 static unsigned
3264 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
3265 SpvExecutionMode mode)
3266 {
3267 switch (mode) {
3268 case SpvExecutionModeInputPoints:
3269 return 1;
3270 case SpvExecutionModeInputLines:
3271 return 2;
3272 case SpvExecutionModeInputLinesAdjacency:
3273 return 4;
3274 case SpvExecutionModeTriangles:
3275 return 3;
3276 case SpvExecutionModeInputTrianglesAdjacency:
3277 return 6;
3278 default:
3279 vtn_fail("Invalid GS input mode");
3280 }
3281 }
3282
3283 static gl_shader_stage
3284 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
3285 {
3286 switch (model) {
3287 case SpvExecutionModelVertex:
3288 return MESA_SHADER_VERTEX;
3289 case SpvExecutionModelTessellationControl:
3290 return MESA_SHADER_TESS_CTRL;
3291 case SpvExecutionModelTessellationEvaluation:
3292 return MESA_SHADER_TESS_EVAL;
3293 case SpvExecutionModelGeometry:
3294 return MESA_SHADER_GEOMETRY;
3295 case SpvExecutionModelFragment:
3296 return MESA_SHADER_FRAGMENT;
3297 case SpvExecutionModelGLCompute:
3298 return MESA_SHADER_COMPUTE;
3299 default:
3300 vtn_fail("Unsupported execution model");
3301 }
3302 }
3303
3304 #define spv_check_supported(name, cap) do { \
3305 if (!(b->options && b->options->caps.name)) \
3306 vtn_warn("Unsupported SPIR-V capability: %s", \
3307 spirv_capability_to_string(cap)); \
3308 } while(0)
3309
3310
3311 void
3312 vtn_handle_entry_point(struct vtn_builder *b, const uint32_t *w,
3313 unsigned count)
3314 {
3315 struct vtn_value *entry_point = &b->values[w[2]];
3316 /* Let this be a name label regardless */
3317 unsigned name_words;
3318 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
3319
3320 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
3321 stage_for_execution_model(b, w[1]) != b->entry_point_stage)
3322 return;
3323
3324 vtn_assert(b->entry_point == NULL);
3325 b->entry_point = entry_point;
3326 }
3327
3328 static bool
3329 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
3330 const uint32_t *w, unsigned count)
3331 {
3332 switch (opcode) {
3333 case SpvOpSource: {
3334 const char *lang;
3335 switch (w[1]) {
3336 default:
3337 case SpvSourceLanguageUnknown: lang = "unknown"; break;
3338 case SpvSourceLanguageESSL: lang = "ESSL"; break;
3339 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
3340 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
3341 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
3342 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
3343 }
3344
3345 uint32_t version = w[2];
3346
3347 const char *file =
3348 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
3349
3350 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
3351 break;
3352 }
3353
3354 case SpvOpSourceExtension:
3355 case SpvOpSourceContinued:
3356 case SpvOpExtension:
3357 case SpvOpModuleProcessed:
3358 /* Unhandled, but these are for debug so that's ok. */
3359 break;
3360
3361 case SpvOpCapability: {
3362 SpvCapability cap = w[1];
3363 switch (cap) {
3364 case SpvCapabilityMatrix:
3365 case SpvCapabilityShader:
3366 case SpvCapabilityGeometry:
3367 case SpvCapabilityGeometryPointSize:
3368 case SpvCapabilityUniformBufferArrayDynamicIndexing:
3369 case SpvCapabilitySampledImageArrayDynamicIndexing:
3370 case SpvCapabilityStorageBufferArrayDynamicIndexing:
3371 case SpvCapabilityStorageImageArrayDynamicIndexing:
3372 case SpvCapabilityImageRect:
3373 case SpvCapabilitySampledRect:
3374 case SpvCapabilitySampled1D:
3375 case SpvCapabilityImage1D:
3376 case SpvCapabilitySampledCubeArray:
3377 case SpvCapabilityImageCubeArray:
3378 case SpvCapabilitySampledBuffer:
3379 case SpvCapabilityImageBuffer:
3380 case SpvCapabilityImageQuery:
3381 case SpvCapabilityDerivativeControl:
3382 case SpvCapabilityInterpolationFunction:
3383 case SpvCapabilityMultiViewport:
3384 case SpvCapabilitySampleRateShading:
3385 case SpvCapabilityClipDistance:
3386 case SpvCapabilityCullDistance:
3387 case SpvCapabilityInputAttachment:
3388 case SpvCapabilityImageGatherExtended:
3389 case SpvCapabilityStorageImageExtendedFormats:
3390 break;
3391
3392 case SpvCapabilityLinkage:
3393 case SpvCapabilityVector16:
3394 case SpvCapabilityFloat16Buffer:
3395 case SpvCapabilityFloat16:
3396 case SpvCapabilityInt64Atomics:
3397 case SpvCapabilityStorageImageMultisample:
3398 case SpvCapabilityInt8:
3399 case SpvCapabilitySparseResidency:
3400 case SpvCapabilityMinLod:
3401 vtn_warn("Unsupported SPIR-V capability: %s",
3402 spirv_capability_to_string(cap));
3403 break;
3404
3405 case SpvCapabilityAtomicStorage:
3406 spv_check_supported(atomic_storage, cap);
3407 break;
3408
3409 case SpvCapabilityFloat64:
3410 spv_check_supported(float64, cap);
3411 break;
3412 case SpvCapabilityInt64:
3413 spv_check_supported(int64, cap);
3414 break;
3415 case SpvCapabilityInt16:
3416 spv_check_supported(int16, cap);
3417 break;
3418
3419 case SpvCapabilityTransformFeedback:
3420 spv_check_supported(transform_feedback, cap);
3421 break;
3422
3423 case SpvCapabilityGeometryStreams:
3424 spv_check_supported(geometry_streams, cap);
3425 break;
3426
3427 case SpvCapabilityAddresses:
3428 case SpvCapabilityKernel:
3429 case SpvCapabilityImageBasic:
3430 case SpvCapabilityImageReadWrite:
3431 case SpvCapabilityImageMipmap:
3432 case SpvCapabilityPipes:
3433 case SpvCapabilityGroups:
3434 case SpvCapabilityDeviceEnqueue:
3435 case SpvCapabilityLiteralSampler:
3436 case SpvCapabilityGenericPointer:
3437 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
3438 spirv_capability_to_string(cap));
3439 break;
3440
3441 case SpvCapabilityImageMSArray:
3442 spv_check_supported(image_ms_array, cap);
3443 break;
3444
3445 case SpvCapabilityTessellation:
3446 case SpvCapabilityTessellationPointSize:
3447 spv_check_supported(tessellation, cap);
3448 break;
3449
3450 case SpvCapabilityDrawParameters:
3451 spv_check_supported(draw_parameters, cap);
3452 break;
3453
3454 case SpvCapabilityStorageImageReadWithoutFormat:
3455 spv_check_supported(image_read_without_format, cap);
3456 break;
3457
3458 case SpvCapabilityStorageImageWriteWithoutFormat:
3459 spv_check_supported(image_write_without_format, cap);
3460 break;
3461
3462 case SpvCapabilityDeviceGroup:
3463 spv_check_supported(device_group, cap);
3464 break;
3465
3466 case SpvCapabilityMultiView:
3467 spv_check_supported(multiview, cap);
3468 break;
3469
3470 case SpvCapabilityGroupNonUniform:
3471 spv_check_supported(subgroup_basic, cap);
3472 break;
3473
3474 case SpvCapabilityGroupNonUniformVote:
3475 spv_check_supported(subgroup_vote, cap);
3476 break;
3477
3478 case SpvCapabilitySubgroupBallotKHR:
3479 case SpvCapabilityGroupNonUniformBallot:
3480 spv_check_supported(subgroup_ballot, cap);
3481 break;
3482
3483 case SpvCapabilityGroupNonUniformShuffle:
3484 case SpvCapabilityGroupNonUniformShuffleRelative:
3485 spv_check_supported(subgroup_shuffle, cap);
3486 break;
3487
3488 case SpvCapabilityGroupNonUniformQuad:
3489 spv_check_supported(subgroup_quad, cap);
3490 break;
3491
3492 case SpvCapabilityGroupNonUniformArithmetic:
3493 case SpvCapabilityGroupNonUniformClustered:
3494 spv_check_supported(subgroup_arithmetic, cap);
3495 break;
3496
3497 case SpvCapabilityVariablePointersStorageBuffer:
3498 case SpvCapabilityVariablePointers:
3499 spv_check_supported(variable_pointers, cap);
3500 break;
3501
3502 case SpvCapabilityStorageUniformBufferBlock16:
3503 case SpvCapabilityStorageUniform16:
3504 case SpvCapabilityStoragePushConstant16:
3505 case SpvCapabilityStorageInputOutput16:
3506 spv_check_supported(storage_16bit, cap);
3507 break;
3508
3509 case SpvCapabilityShaderViewportIndexLayerEXT:
3510 spv_check_supported(shader_viewport_index_layer, cap);
3511 break;
3512
3513 case SpvCapabilityStorageBuffer8BitAccess:
3514 case SpvCapabilityUniformAndStorageBuffer8BitAccess:
3515 case SpvCapabilityStoragePushConstant8:
3516 spv_check_supported(storage_8bit, cap);
3517 break;
3518
3519 case SpvCapabilityInputAttachmentArrayDynamicIndexingEXT:
3520 case SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT:
3521 case SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT:
3522 spv_check_supported(descriptor_array_dynamic_indexing, cap);
3523 break;
3524
3525 case SpvCapabilityRuntimeDescriptorArrayEXT:
3526 spv_check_supported(runtime_descriptor_array, cap);
3527 break;
3528
3529 case SpvCapabilityStencilExportEXT:
3530 spv_check_supported(stencil_export, cap);
3531 break;
3532
3533 case SpvCapabilitySampleMaskPostDepthCoverage:
3534 spv_check_supported(post_depth_coverage, cap);
3535 break;
3536
3537 default:
3538 vtn_fail("Unhandled capability");
3539 }
3540 break;
3541 }
3542
3543 case SpvOpExtInstImport:
3544 vtn_handle_extension(b, opcode, w, count);
3545 break;
3546
3547 case SpvOpMemoryModel:
3548 vtn_assert(w[1] == SpvAddressingModelLogical);
3549 vtn_assert(w[2] == SpvMemoryModelSimple ||
3550 w[2] == SpvMemoryModelGLSL450);
3551 break;
3552
3553 case SpvOpEntryPoint:
3554 vtn_handle_entry_point(b, w, count);
3555 break;
3556
3557 case SpvOpString:
3558 vtn_push_value(b, w[1], vtn_value_type_string)->str =
3559 vtn_string_literal(b, &w[2], count - 2, NULL);
3560 break;
3561
3562 case SpvOpName:
3563 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
3564 break;
3565
3566 case SpvOpMemberName:
3567 /* TODO */
3568 break;
3569
3570 case SpvOpExecutionMode:
3571 case SpvOpDecorationGroup:
3572 case SpvOpDecorate:
3573 case SpvOpMemberDecorate:
3574 case SpvOpGroupDecorate:
3575 case SpvOpGroupMemberDecorate:
3576 case SpvOpDecorateStringGOOGLE:
3577 case SpvOpMemberDecorateStringGOOGLE:
3578 vtn_handle_decoration(b, opcode, w, count);
3579 break;
3580
3581 default:
3582 return false; /* End of preamble */
3583 }
3584
3585 return true;
3586 }
3587
3588 static void
3589 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
3590 const struct vtn_decoration *mode, void *data)
3591 {
3592 vtn_assert(b->entry_point == entry_point);
3593
3594 switch(mode->exec_mode) {
3595 case SpvExecutionModeOriginUpperLeft:
3596 case SpvExecutionModeOriginLowerLeft:
3597 b->origin_upper_left =
3598 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
3599 break;
3600
3601 case SpvExecutionModeEarlyFragmentTests:
3602 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3603 b->shader->info.fs.early_fragment_tests = true;
3604 break;
3605
3606 case SpvExecutionModePostDepthCoverage:
3607 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3608 b->shader->info.fs.post_depth_coverage = true;
3609 break;
3610
3611 case SpvExecutionModeInvocations:
3612 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3613 b->shader->info.gs.invocations = MAX2(1, mode->literals[0]);
3614 break;
3615
3616 case SpvExecutionModeDepthReplacing:
3617 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3618 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
3619 break;
3620 case SpvExecutionModeDepthGreater:
3621 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3622 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
3623 break;
3624 case SpvExecutionModeDepthLess:
3625 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3626 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
3627 break;
3628 case SpvExecutionModeDepthUnchanged:
3629 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3630 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3631 break;
3632
3633 case SpvExecutionModeLocalSize:
3634 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
3635 b->shader->info.cs.local_size[0] = mode->literals[0];
3636 b->shader->info.cs.local_size[1] = mode->literals[1];
3637 b->shader->info.cs.local_size[2] = mode->literals[2];
3638 break;
3639 case SpvExecutionModeLocalSizeHint:
3640 break; /* Nothing to do with this */
3641
3642 case SpvExecutionModeOutputVertices:
3643 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3644 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3645 b->shader->info.tess.tcs_vertices_out = mode->literals[0];
3646 } else {
3647 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3648 b->shader->info.gs.vertices_out = mode->literals[0];
3649 }
3650 break;
3651
3652 case SpvExecutionModeInputPoints:
3653 case SpvExecutionModeInputLines:
3654 case SpvExecutionModeInputLinesAdjacency:
3655 case SpvExecutionModeTriangles:
3656 case SpvExecutionModeInputTrianglesAdjacency:
3657 case SpvExecutionModeQuads:
3658 case SpvExecutionModeIsolines:
3659 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3660 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3661 b->shader->info.tess.primitive_mode =
3662 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3663 } else {
3664 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3665 b->shader->info.gs.vertices_in =
3666 vertices_in_from_spv_execution_mode(b, mode->exec_mode);
3667 b->shader->info.gs.input_primitive =
3668 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3669 }
3670 break;
3671
3672 case SpvExecutionModeOutputPoints:
3673 case SpvExecutionModeOutputLineStrip:
3674 case SpvExecutionModeOutputTriangleStrip:
3675 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3676 b->shader->info.gs.output_primitive =
3677 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3678 break;
3679
3680 case SpvExecutionModeSpacingEqual:
3681 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3682 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3683 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
3684 break;
3685 case SpvExecutionModeSpacingFractionalEven:
3686 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3687 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3688 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
3689 break;
3690 case SpvExecutionModeSpacingFractionalOdd:
3691 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3692 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3693 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
3694 break;
3695 case SpvExecutionModeVertexOrderCw:
3696 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3697 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3698 b->shader->info.tess.ccw = false;
3699 break;
3700 case SpvExecutionModeVertexOrderCcw:
3701 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3702 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3703 b->shader->info.tess.ccw = true;
3704 break;
3705 case SpvExecutionModePointMode:
3706 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3707 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3708 b->shader->info.tess.point_mode = true;
3709 break;
3710
3711 case SpvExecutionModePixelCenterInteger:
3712 b->pixel_center_integer = true;
3713 break;
3714
3715 case SpvExecutionModeXfb:
3716 b->shader->info.has_transform_feedback_varyings = true;
3717 break;
3718
3719 case SpvExecutionModeVecTypeHint:
3720 case SpvExecutionModeContractionOff:
3721 break; /* OpenCL */
3722
3723 case SpvExecutionModeStencilRefReplacingEXT:
3724 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3725 break;
3726
3727 default:
3728 vtn_fail("Unhandled execution mode");
3729 }
3730 }
3731
3732 static bool
3733 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
3734 const uint32_t *w, unsigned count)
3735 {
3736 vtn_set_instruction_result_type(b, opcode, w, count);
3737
3738 switch (opcode) {
3739 case SpvOpSource:
3740 case SpvOpSourceContinued:
3741 case SpvOpSourceExtension:
3742 case SpvOpExtension:
3743 case SpvOpCapability:
3744 case SpvOpExtInstImport:
3745 case SpvOpMemoryModel:
3746 case SpvOpEntryPoint:
3747 case SpvOpExecutionMode:
3748 case SpvOpString:
3749 case SpvOpName:
3750 case SpvOpMemberName:
3751 case SpvOpDecorationGroup:
3752 case SpvOpDecorate:
3753 case SpvOpMemberDecorate:
3754 case SpvOpGroupDecorate:
3755 case SpvOpGroupMemberDecorate:
3756 case SpvOpDecorateStringGOOGLE:
3757 case SpvOpMemberDecorateStringGOOGLE:
3758 vtn_fail("Invalid opcode types and variables section");
3759 break;
3760
3761 case SpvOpTypeVoid:
3762 case SpvOpTypeBool:
3763 case SpvOpTypeInt:
3764 case SpvOpTypeFloat:
3765 case SpvOpTypeVector:
3766 case SpvOpTypeMatrix:
3767 case SpvOpTypeImage:
3768 case SpvOpTypeSampler:
3769 case SpvOpTypeSampledImage:
3770 case SpvOpTypeArray:
3771 case SpvOpTypeRuntimeArray:
3772 case SpvOpTypeStruct:
3773 case SpvOpTypeOpaque:
3774 case SpvOpTypePointer:
3775 case SpvOpTypeFunction:
3776 case SpvOpTypeEvent:
3777 case SpvOpTypeDeviceEvent:
3778 case SpvOpTypeReserveId:
3779 case SpvOpTypeQueue:
3780 case SpvOpTypePipe:
3781 vtn_handle_type(b, opcode, w, count);
3782 break;
3783
3784 case SpvOpConstantTrue:
3785 case SpvOpConstantFalse:
3786 case SpvOpConstant:
3787 case SpvOpConstantComposite:
3788 case SpvOpConstantSampler:
3789 case SpvOpConstantNull:
3790 case SpvOpSpecConstantTrue:
3791 case SpvOpSpecConstantFalse:
3792 case SpvOpSpecConstant:
3793 case SpvOpSpecConstantComposite:
3794 case SpvOpSpecConstantOp:
3795 vtn_handle_constant(b, opcode, w, count);
3796 break;
3797
3798 case SpvOpUndef:
3799 case SpvOpVariable:
3800 vtn_handle_variables(b, opcode, w, count);
3801 break;
3802
3803 default:
3804 return false; /* End of preamble */
3805 }
3806
3807 return true;
3808 }
3809
3810 static bool
3811 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
3812 const uint32_t *w, unsigned count)
3813 {
3814 switch (opcode) {
3815 case SpvOpLabel:
3816 break;
3817
3818 case SpvOpLoopMerge:
3819 case SpvOpSelectionMerge:
3820 /* This is handled by cfg pre-pass and walk_blocks */
3821 break;
3822
3823 case SpvOpUndef: {
3824 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
3825 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
3826 break;
3827 }
3828
3829 case SpvOpExtInst:
3830 vtn_handle_extension(b, opcode, w, count);
3831 break;
3832
3833 case SpvOpVariable:
3834 case SpvOpLoad:
3835 case SpvOpStore:
3836 case SpvOpCopyMemory:
3837 case SpvOpCopyMemorySized:
3838 case SpvOpAccessChain:
3839 case SpvOpPtrAccessChain:
3840 case SpvOpInBoundsAccessChain:
3841 case SpvOpArrayLength:
3842 vtn_handle_variables(b, opcode, w, count);
3843 break;
3844
3845 case SpvOpFunctionCall:
3846 vtn_handle_function_call(b, opcode, w, count);
3847 break;
3848
3849 case SpvOpSampledImage:
3850 case SpvOpImage:
3851 case SpvOpImageSampleImplicitLod:
3852 case SpvOpImageSampleExplicitLod:
3853 case SpvOpImageSampleDrefImplicitLod:
3854 case SpvOpImageSampleDrefExplicitLod:
3855 case SpvOpImageSampleProjImplicitLod:
3856 case SpvOpImageSampleProjExplicitLod:
3857 case SpvOpImageSampleProjDrefImplicitLod:
3858 case SpvOpImageSampleProjDrefExplicitLod:
3859 case SpvOpImageFetch:
3860 case SpvOpImageGather:
3861 case SpvOpImageDrefGather:
3862 case SpvOpImageQuerySizeLod:
3863 case SpvOpImageQueryLod:
3864 case SpvOpImageQueryLevels:
3865 case SpvOpImageQuerySamples:
3866 vtn_handle_texture(b, opcode, w, count);
3867 break;
3868
3869 case SpvOpImageRead:
3870 case SpvOpImageWrite:
3871 case SpvOpImageTexelPointer:
3872 vtn_handle_image(b, opcode, w, count);
3873 break;
3874
3875 case SpvOpImageQuerySize: {
3876 struct vtn_pointer *image =
3877 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3878 if (glsl_type_is_image(image->type->type)) {
3879 vtn_handle_image(b, opcode, w, count);
3880 } else {
3881 vtn_assert(glsl_type_is_sampler(image->type->type));
3882 vtn_handle_texture(b, opcode, w, count);
3883 }
3884 break;
3885 }
3886
3887 case SpvOpAtomicLoad:
3888 case SpvOpAtomicExchange:
3889 case SpvOpAtomicCompareExchange:
3890 case SpvOpAtomicCompareExchangeWeak:
3891 case SpvOpAtomicIIncrement:
3892 case SpvOpAtomicIDecrement:
3893 case SpvOpAtomicIAdd:
3894 case SpvOpAtomicISub:
3895 case SpvOpAtomicSMin:
3896 case SpvOpAtomicUMin:
3897 case SpvOpAtomicSMax:
3898 case SpvOpAtomicUMax:
3899 case SpvOpAtomicAnd:
3900 case SpvOpAtomicOr:
3901 case SpvOpAtomicXor: {
3902 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
3903 if (pointer->value_type == vtn_value_type_image_pointer) {
3904 vtn_handle_image(b, opcode, w, count);
3905 } else {
3906 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3907 vtn_handle_atomics(b, opcode, w, count);
3908 }
3909 break;
3910 }
3911
3912 case SpvOpAtomicStore: {
3913 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
3914 if (pointer->value_type == vtn_value_type_image_pointer) {
3915 vtn_handle_image(b, opcode, w, count);
3916 } else {
3917 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3918 vtn_handle_atomics(b, opcode, w, count);
3919 }
3920 break;
3921 }
3922
3923 case SpvOpSelect: {
3924 /* Handle OpSelect up-front here because it needs to be able to handle
3925 * pointers and not just regular vectors and scalars.
3926 */
3927 struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
3928 struct vtn_value *sel_val = vtn_untyped_value(b, w[3]);
3929 struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
3930 struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
3931
3932 const struct glsl_type *sel_type;
3933 switch (res_val->type->base_type) {
3934 case vtn_base_type_scalar:
3935 sel_type = glsl_bool_type();
3936 break;
3937 case vtn_base_type_vector:
3938 sel_type = glsl_vector_type(GLSL_TYPE_BOOL, res_val->type->length);
3939 break;
3940 case vtn_base_type_pointer:
3941 /* We need to have actual storage for pointer types */
3942 vtn_fail_if(res_val->type->type == NULL,
3943 "Invalid pointer result type for OpSelect");
3944 sel_type = glsl_bool_type();
3945 break;
3946 default:
3947 vtn_fail("Result type of OpSelect must be a scalar, vector, or pointer");
3948 }
3949
3950 if (unlikely(sel_val->type->type != sel_type)) {
3951 if (sel_val->type->type == glsl_bool_type()) {
3952 /* This case is illegal but some older versions of GLSLang produce
3953 * it. The GLSLang issue was fixed on March 30, 2017:
3954 *
3955 * https://github.com/KhronosGroup/glslang/issues/809
3956 *
3957 * Unfortunately, there are applications in the wild which are
3958 * shipping with this bug so it isn't nice to fail on them so we
3959 * throw a warning instead. It's not actually a problem for us as
3960 * nir_builder will just splat the condition out which is most
3961 * likely what the client wanted anyway.
3962 */
3963 vtn_warn("Condition type of OpSelect must have the same number "
3964 "of components as Result Type");
3965 } else {
3966 vtn_fail("Condition type of OpSelect must be a scalar or vector "
3967 "of Boolean type. It must have the same number of "
3968 "components as Result Type");
3969 }
3970 }
3971
3972 vtn_fail_if(obj1_val->type != res_val->type ||
3973 obj2_val->type != res_val->type,
3974 "Object types must match the result type in OpSelect");
3975
3976 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
3977 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, res_type->type);
3978 ssa->def = nir_bcsel(&b->nb, vtn_ssa_value(b, w[3])->def,
3979 vtn_ssa_value(b, w[4])->def,
3980 vtn_ssa_value(b, w[5])->def);
3981 vtn_push_ssa(b, w[2], res_type, ssa);
3982 break;
3983 }
3984
3985 case SpvOpSNegate:
3986 case SpvOpFNegate:
3987 case SpvOpNot:
3988 case SpvOpAny:
3989 case SpvOpAll:
3990 case SpvOpConvertFToU:
3991 case SpvOpConvertFToS:
3992 case SpvOpConvertSToF:
3993 case SpvOpConvertUToF:
3994 case SpvOpUConvert:
3995 case SpvOpSConvert:
3996 case SpvOpFConvert:
3997 case SpvOpQuantizeToF16:
3998 case SpvOpConvertPtrToU:
3999 case SpvOpConvertUToPtr:
4000 case SpvOpPtrCastToGeneric:
4001 case SpvOpGenericCastToPtr:
4002 case SpvOpBitcast:
4003 case SpvOpIsNan:
4004 case SpvOpIsInf:
4005 case SpvOpIsFinite:
4006 case SpvOpIsNormal:
4007 case SpvOpSignBitSet:
4008 case SpvOpLessOrGreater:
4009 case SpvOpOrdered:
4010 case SpvOpUnordered:
4011 case SpvOpIAdd:
4012 case SpvOpFAdd:
4013 case SpvOpISub:
4014 case SpvOpFSub:
4015 case SpvOpIMul:
4016 case SpvOpFMul:
4017 case SpvOpUDiv:
4018 case SpvOpSDiv:
4019 case SpvOpFDiv:
4020 case SpvOpUMod:
4021 case SpvOpSRem:
4022 case SpvOpSMod:
4023 case SpvOpFRem:
4024 case SpvOpFMod:
4025 case SpvOpVectorTimesScalar:
4026 case SpvOpDot:
4027 case SpvOpIAddCarry:
4028 case SpvOpISubBorrow:
4029 case SpvOpUMulExtended:
4030 case SpvOpSMulExtended:
4031 case SpvOpShiftRightLogical:
4032 case SpvOpShiftRightArithmetic:
4033 case SpvOpShiftLeftLogical:
4034 case SpvOpLogicalEqual:
4035 case SpvOpLogicalNotEqual:
4036 case SpvOpLogicalOr:
4037 case SpvOpLogicalAnd:
4038 case SpvOpLogicalNot:
4039 case SpvOpBitwiseOr:
4040 case SpvOpBitwiseXor:
4041 case SpvOpBitwiseAnd:
4042 case SpvOpIEqual:
4043 case SpvOpFOrdEqual:
4044 case SpvOpFUnordEqual:
4045 case SpvOpINotEqual:
4046 case SpvOpFOrdNotEqual:
4047 case SpvOpFUnordNotEqual:
4048 case SpvOpULessThan:
4049 case SpvOpSLessThan:
4050 case SpvOpFOrdLessThan:
4051 case SpvOpFUnordLessThan:
4052 case SpvOpUGreaterThan:
4053 case SpvOpSGreaterThan:
4054 case SpvOpFOrdGreaterThan:
4055 case SpvOpFUnordGreaterThan:
4056 case SpvOpULessThanEqual:
4057 case SpvOpSLessThanEqual:
4058 case SpvOpFOrdLessThanEqual:
4059 case SpvOpFUnordLessThanEqual:
4060 case SpvOpUGreaterThanEqual:
4061 case SpvOpSGreaterThanEqual:
4062 case SpvOpFOrdGreaterThanEqual:
4063 case SpvOpFUnordGreaterThanEqual:
4064 case SpvOpDPdx:
4065 case SpvOpDPdy:
4066 case SpvOpFwidth:
4067 case SpvOpDPdxFine:
4068 case SpvOpDPdyFine:
4069 case SpvOpFwidthFine:
4070 case SpvOpDPdxCoarse:
4071 case SpvOpDPdyCoarse:
4072 case SpvOpFwidthCoarse:
4073 case SpvOpBitFieldInsert:
4074 case SpvOpBitFieldSExtract:
4075 case SpvOpBitFieldUExtract:
4076 case SpvOpBitReverse:
4077 case SpvOpBitCount:
4078 case SpvOpTranspose:
4079 case SpvOpOuterProduct:
4080 case SpvOpMatrixTimesScalar:
4081 case SpvOpVectorTimesMatrix:
4082 case SpvOpMatrixTimesVector:
4083 case SpvOpMatrixTimesMatrix:
4084 vtn_handle_alu(b, opcode, w, count);
4085 break;
4086
4087 case SpvOpVectorExtractDynamic:
4088 case SpvOpVectorInsertDynamic:
4089 case SpvOpVectorShuffle:
4090 case SpvOpCompositeConstruct:
4091 case SpvOpCompositeExtract:
4092 case SpvOpCompositeInsert:
4093 case SpvOpCopyObject:
4094 vtn_handle_composite(b, opcode, w, count);
4095 break;
4096
4097 case SpvOpEmitVertex:
4098 case SpvOpEndPrimitive:
4099 case SpvOpEmitStreamVertex:
4100 case SpvOpEndStreamPrimitive:
4101 case SpvOpControlBarrier:
4102 case SpvOpMemoryBarrier:
4103 vtn_handle_barrier(b, opcode, w, count);
4104 break;
4105
4106 case SpvOpGroupNonUniformElect:
4107 case SpvOpGroupNonUniformAll:
4108 case SpvOpGroupNonUniformAny:
4109 case SpvOpGroupNonUniformAllEqual:
4110 case SpvOpGroupNonUniformBroadcast:
4111 case SpvOpGroupNonUniformBroadcastFirst:
4112 case SpvOpGroupNonUniformBallot:
4113 case SpvOpGroupNonUniformInverseBallot:
4114 case SpvOpGroupNonUniformBallotBitExtract:
4115 case SpvOpGroupNonUniformBallotBitCount:
4116 case SpvOpGroupNonUniformBallotFindLSB:
4117 case SpvOpGroupNonUniformBallotFindMSB:
4118 case SpvOpGroupNonUniformShuffle:
4119 case SpvOpGroupNonUniformShuffleXor:
4120 case SpvOpGroupNonUniformShuffleUp:
4121 case SpvOpGroupNonUniformShuffleDown:
4122 case SpvOpGroupNonUniformIAdd:
4123 case SpvOpGroupNonUniformFAdd:
4124 case SpvOpGroupNonUniformIMul:
4125 case SpvOpGroupNonUniformFMul:
4126 case SpvOpGroupNonUniformSMin:
4127 case SpvOpGroupNonUniformUMin:
4128 case SpvOpGroupNonUniformFMin:
4129 case SpvOpGroupNonUniformSMax:
4130 case SpvOpGroupNonUniformUMax:
4131 case SpvOpGroupNonUniformFMax:
4132 case SpvOpGroupNonUniformBitwiseAnd:
4133 case SpvOpGroupNonUniformBitwiseOr:
4134 case SpvOpGroupNonUniformBitwiseXor:
4135 case SpvOpGroupNonUniformLogicalAnd:
4136 case SpvOpGroupNonUniformLogicalOr:
4137 case SpvOpGroupNonUniformLogicalXor:
4138 case SpvOpGroupNonUniformQuadBroadcast:
4139 case SpvOpGroupNonUniformQuadSwap:
4140 vtn_handle_subgroup(b, opcode, w, count);
4141 break;
4142
4143 default:
4144 vtn_fail("Unhandled opcode");
4145 }
4146
4147 return true;
4148 }
4149
4150 struct vtn_builder*
4151 vtn_create_builder(const uint32_t *words, size_t word_count,
4152 gl_shader_stage stage, const char *entry_point_name,
4153 const struct spirv_to_nir_options *options)
4154 {
4155 /* Initialize the vtn_builder object */
4156 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
4157 b->spirv = words;
4158 b->spirv_word_count = word_count;
4159 b->file = NULL;
4160 b->line = -1;
4161 b->col = -1;
4162 exec_list_make_empty(&b->functions);
4163 b->entry_point_stage = stage;
4164 b->entry_point_name = entry_point_name;
4165 b->options = options;
4166
4167 /*
4168 * Handle the SPIR-V header (first 5 dwords).
4169 * Can't use vtx_assert() as the setjmp(3) target isn't initialized yet.
4170 */
4171 if (word_count <= 5)
4172 goto fail;
4173
4174 if (words[0] != SpvMagicNumber) {
4175 vtn_err("words[0] was 0x%x, want 0x%x", words[0], SpvMagicNumber);
4176 goto fail;
4177 }
4178 if (words[1] < 0x10000) {
4179 vtn_err("words[1] was 0x%x, want >= 0x10000", words[1]);
4180 goto fail;
4181 }
4182
4183 /* words[2] == generator magic */
4184 unsigned value_id_bound = words[3];
4185 if (words[4] != 0) {
4186 vtn_err("words[4] was %u, want 0", words[4]);
4187 goto fail;
4188 }
4189
4190 b->value_id_bound = value_id_bound;
4191 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
4192
4193 return b;
4194 fail:
4195 ralloc_free(b);
4196 return NULL;
4197 }
4198
4199 nir_function *
4200 spirv_to_nir(const uint32_t *words, size_t word_count,
4201 struct nir_spirv_specialization *spec, unsigned num_spec,
4202 gl_shader_stage stage, const char *entry_point_name,
4203 const struct spirv_to_nir_options *options,
4204 const nir_shader_compiler_options *nir_options)
4205
4206 {
4207 const uint32_t *word_end = words + word_count;
4208
4209 struct vtn_builder *b = vtn_create_builder(words, word_count,
4210 stage, entry_point_name,
4211 options);
4212
4213 if (b == NULL)
4214 return NULL;
4215
4216 /* See also _vtn_fail() */
4217 if (setjmp(b->fail_jump)) {
4218 ralloc_free(b);
4219 return NULL;
4220 }
4221
4222 /* Skip the SPIR-V header, handled at vtn_create_builder */
4223 words+= 5;
4224
4225 /* Handle all the preamble instructions */
4226 words = vtn_foreach_instruction(b, words, word_end,
4227 vtn_handle_preamble_instruction);
4228
4229 if (b->entry_point == NULL) {
4230 vtn_fail("Entry point not found");
4231 ralloc_free(b);
4232 return NULL;
4233 }
4234
4235 b->shader = nir_shader_create(b, stage, nir_options, NULL);
4236
4237 /* Set shader info defaults */
4238 b->shader->info.gs.invocations = 1;
4239
4240 /* Parse execution modes */
4241 vtn_foreach_execution_mode(b, b->entry_point,
4242 vtn_handle_execution_mode, NULL);
4243
4244 b->specializations = spec;
4245 b->num_specializations = num_spec;
4246
4247 /* Handle all variable, type, and constant instructions */
4248 words = vtn_foreach_instruction(b, words, word_end,
4249 vtn_handle_variable_or_type_instruction);
4250
4251 /* Set types on all vtn_values */
4252 vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
4253
4254 vtn_build_cfg(b, words, word_end);
4255
4256 assert(b->entry_point->value_type == vtn_value_type_function);
4257 b->entry_point->func->referenced = true;
4258
4259 bool progress;
4260 do {
4261 progress = false;
4262 foreach_list_typed(struct vtn_function, func, node, &b->functions) {
4263 if (func->referenced && !func->emitted) {
4264 b->const_table = _mesa_hash_table_create(b, _mesa_hash_pointer,
4265 _mesa_key_pointer_equal);
4266
4267 vtn_function_emit(b, func, vtn_handle_body_instruction);
4268 progress = true;
4269 }
4270 }
4271 } while (progress);
4272
4273 /* We sometimes generate bogus derefs that, while never used, give the
4274 * validator a bit of heartburn. Run dead code to get rid of them.
4275 */
4276 nir_opt_dce(b->shader);
4277
4278 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
4279 nir_function *entry_point = b->entry_point->func->impl->function;
4280 vtn_assert(entry_point);
4281
4282 /* Unparent the shader from the vtn_builder before we delete the builder */
4283 ralloc_steal(NULL, b->shader);
4284
4285 ralloc_free(b);
4286
4287 return entry_point;
4288 }