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