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