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