nir/spirv: handle ContractionOff execution mode
[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_get_bit_size(type->type) / 8;
1048 *size_out = comp_size;
1049 *align_out = comp_size;
1050 return type;
1051 }
1052
1053 case vtn_base_type_vector: {
1054 uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
1055 unsigned align_comps = type->length == 3 ? 4 : type->length;
1056 *size_out = comp_size * type->length,
1057 *align_out = comp_size * align_comps;
1058 return type;
1059 }
1060
1061 case vtn_base_type_matrix:
1062 case vtn_base_type_array: {
1063 /* We're going to add an array stride */
1064 type = vtn_type_copy(b, type);
1065 uint32_t elem_size, elem_align;
1066 type->array_element = vtn_type_layout_std430(b, type->array_element,
1067 &elem_size, &elem_align);
1068 type->stride = vtn_align_u32(elem_size, elem_align);
1069 *size_out = type->stride * type->length;
1070 *align_out = elem_align;
1071 return type;
1072 }
1073
1074 case vtn_base_type_struct: {
1075 /* We're going to add member offsets */
1076 type = vtn_type_copy(b, type);
1077 uint32_t offset = 0;
1078 uint32_t align = 0;
1079 for (unsigned i = 0; i < type->length; i++) {
1080 uint32_t mem_size, mem_align;
1081 type->members[i] = vtn_type_layout_std430(b, type->members[i],
1082 &mem_size, &mem_align);
1083 offset = vtn_align_u32(offset, mem_align);
1084 type->offsets[i] = offset;
1085 offset += mem_size;
1086 align = MAX2(align, mem_align);
1087 }
1088 *size_out = offset;
1089 *align_out = align;
1090 return type;
1091 }
1092
1093 default:
1094 unreachable("Invalid SPIR-V type for std430");
1095 }
1096 }
1097
1098 static void
1099 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
1100 const uint32_t *w, unsigned count)
1101 {
1102 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_type);
1103
1104 val->type = rzalloc(b, struct vtn_type);
1105 val->type->id = w[1];
1106
1107 switch (opcode) {
1108 case SpvOpTypeVoid:
1109 val->type->base_type = vtn_base_type_void;
1110 val->type->type = glsl_void_type();
1111 break;
1112 case SpvOpTypeBool:
1113 val->type->base_type = vtn_base_type_scalar;
1114 val->type->type = glsl_bool_type();
1115 val->type->length = 1;
1116 break;
1117 case SpvOpTypeInt: {
1118 int bit_size = w[2];
1119 const bool signedness = w[3];
1120 val->type->base_type = vtn_base_type_scalar;
1121 switch (bit_size) {
1122 case 64:
1123 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1124 break;
1125 case 32:
1126 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1127 break;
1128 case 16:
1129 val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1130 break;
1131 case 8:
1132 val->type->type = (signedness ? glsl_int8_t_type() : glsl_uint8_t_type());
1133 break;
1134 default:
1135 vtn_fail("Invalid int bit size");
1136 }
1137 val->type->length = 1;
1138 break;
1139 }
1140
1141 case SpvOpTypeFloat: {
1142 int bit_size = w[2];
1143 val->type->base_type = vtn_base_type_scalar;
1144 switch (bit_size) {
1145 case 16:
1146 val->type->type = glsl_float16_t_type();
1147 break;
1148 case 32:
1149 val->type->type = glsl_float_type();
1150 break;
1151 case 64:
1152 val->type->type = glsl_double_type();
1153 break;
1154 default:
1155 vtn_fail("Invalid float bit size");
1156 }
1157 val->type->length = 1;
1158 break;
1159 }
1160
1161 case SpvOpTypeVector: {
1162 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1163 unsigned elems = w[3];
1164
1165 vtn_fail_if(base->base_type != vtn_base_type_scalar,
1166 "Base type for OpTypeVector must be a scalar");
1167 vtn_fail_if((elems < 2 || elems > 4) && (elems != 8) && (elems != 16),
1168 "Invalid component count for OpTypeVector");
1169
1170 val->type->base_type = vtn_base_type_vector;
1171 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1172 val->type->length = elems;
1173 val->type->stride = glsl_get_bit_size(base->type) / 8;
1174 val->type->array_element = base;
1175 break;
1176 }
1177
1178 case SpvOpTypeMatrix: {
1179 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1180 unsigned columns = w[3];
1181
1182 vtn_fail_if(base->base_type != vtn_base_type_vector,
1183 "Base type for OpTypeMatrix must be a vector");
1184 vtn_fail_if(columns < 2 || columns > 4,
1185 "Invalid column count for OpTypeMatrix");
1186
1187 val->type->base_type = vtn_base_type_matrix;
1188 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1189 glsl_get_vector_elements(base->type),
1190 columns);
1191 vtn_fail_if(glsl_type_is_error(val->type->type),
1192 "Unsupported base type for OpTypeMatrix");
1193 assert(!glsl_type_is_error(val->type->type));
1194 val->type->length = columns;
1195 val->type->array_element = base;
1196 val->type->row_major = false;
1197 val->type->stride = 0;
1198 break;
1199 }
1200
1201 case SpvOpTypeRuntimeArray:
1202 case SpvOpTypeArray: {
1203 struct vtn_type *array_element =
1204 vtn_value(b, w[2], vtn_value_type_type)->type;
1205
1206 if (opcode == SpvOpTypeRuntimeArray) {
1207 /* A length of 0 is used to denote unsized arrays */
1208 val->type->length = 0;
1209 } else {
1210 val->type->length =
1211 vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
1212 }
1213
1214 val->type->base_type = vtn_base_type_array;
1215 val->type->array_element = array_element;
1216 val->type->stride = 0;
1217
1218 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1219 val->type->type = glsl_array_type(array_element->type, val->type->length,
1220 val->type->stride);
1221 break;
1222 }
1223
1224 case SpvOpTypeStruct: {
1225 unsigned num_fields = count - 2;
1226 val->type->base_type = vtn_base_type_struct;
1227 val->type->length = num_fields;
1228 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1229 val->type->offsets = ralloc_array(b, unsigned, num_fields);
1230
1231 NIR_VLA(struct glsl_struct_field, fields, count);
1232 for (unsigned i = 0; i < num_fields; i++) {
1233 val->type->members[i] =
1234 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
1235 fields[i] = (struct glsl_struct_field) {
1236 .type = val->type->members[i]->type,
1237 .name = ralloc_asprintf(b, "field%d", i),
1238 .location = -1,
1239 };
1240 }
1241
1242 struct member_decoration_ctx ctx = {
1243 .num_fields = num_fields,
1244 .fields = fields,
1245 .type = val->type
1246 };
1247
1248 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1249 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1250
1251 const char *name = val->name ? val->name : "struct";
1252
1253 val->type->type = glsl_struct_type(fields, num_fields, name);
1254 break;
1255 }
1256
1257 case SpvOpTypeFunction: {
1258 val->type->base_type = vtn_base_type_function;
1259 val->type->type = NULL;
1260
1261 val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
1262
1263 const unsigned num_params = count - 3;
1264 val->type->length = num_params;
1265 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1266 for (unsigned i = 0; i < count - 3; i++) {
1267 val->type->params[i] =
1268 vtn_value(b, w[i + 3], vtn_value_type_type)->type;
1269 }
1270 break;
1271 }
1272
1273 case SpvOpTypePointer: {
1274 SpvStorageClass storage_class = w[2];
1275 struct vtn_type *deref_type =
1276 vtn_value(b, w[3], vtn_value_type_type)->type;
1277
1278 val->type->base_type = vtn_base_type_pointer;
1279 val->type->storage_class = storage_class;
1280 val->type->deref = deref_type;
1281
1282 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1283
1284 /* These can actually be stored to nir_variables and used as SSA
1285 * values so they need a real glsl_type.
1286 */
1287 switch (storage_class) {
1288 case SpvStorageClassUniform:
1289 val->type->type = b->options->ubo_ptr_type;
1290 break;
1291 case SpvStorageClassStorageBuffer:
1292 val->type->type = b->options->ssbo_ptr_type;
1293 break;
1294 case SpvStorageClassPushConstant:
1295 val->type->type = b->options->push_const_ptr_type;
1296 break;
1297 case SpvStorageClassWorkgroup:
1298 val->type->type = b->options->shared_ptr_type;
1299 if (b->options->lower_workgroup_access_to_offsets) {
1300 uint32_t size, align;
1301 val->type->deref = vtn_type_layout_std430(b, val->type->deref,
1302 &size, &align);
1303 val->type->length = size;
1304 val->type->align = align;
1305 }
1306 break;
1307 default:
1308 /* In this case, no variable pointers are allowed so all deref chains
1309 * are complete back to the variable and it doesn't matter what type
1310 * gets used so we leave it NULL.
1311 */
1312 break;
1313 }
1314 break;
1315 }
1316
1317 case SpvOpTypeImage: {
1318 val->type->base_type = vtn_base_type_image;
1319
1320 const struct vtn_type *sampled_type =
1321 vtn_value(b, w[2], vtn_value_type_type)->type;
1322
1323 vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1324 glsl_get_bit_size(sampled_type->type) != 32,
1325 "Sampled type of OpTypeImage must be a 32-bit scalar");
1326
1327 enum glsl_sampler_dim dim;
1328 switch ((SpvDim)w[3]) {
1329 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
1330 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
1331 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
1332 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
1333 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
1334 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
1335 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1336 default:
1337 vtn_fail("Invalid SPIR-V image dimensionality");
1338 }
1339
1340 bool is_shadow = w[4];
1341 bool is_array = w[5];
1342 bool multisampled = w[6];
1343 unsigned sampled = w[7];
1344 SpvImageFormat format = w[8];
1345
1346 if (count > 9)
1347 val->type->access_qualifier = w[9];
1348 else
1349 val->type->access_qualifier = SpvAccessQualifierReadWrite;
1350
1351 if (multisampled) {
1352 if (dim == GLSL_SAMPLER_DIM_2D)
1353 dim = GLSL_SAMPLER_DIM_MS;
1354 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1355 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1356 else
1357 vtn_fail("Unsupported multisampled image type");
1358 }
1359
1360 val->type->image_format = translate_image_format(b, format);
1361
1362 enum glsl_base_type sampled_base_type =
1363 glsl_get_base_type(sampled_type->type);
1364 if (sampled == 1) {
1365 val->type->sampled = true;
1366 val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
1367 sampled_base_type);
1368 } else if (sampled == 2) {
1369 vtn_assert(!is_shadow);
1370 val->type->sampled = false;
1371 val->type->type = glsl_image_type(dim, is_array, sampled_base_type);
1372 } else {
1373 vtn_fail("We need to know if the image will be sampled");
1374 }
1375 break;
1376 }
1377
1378 case SpvOpTypeSampledImage:
1379 val->type->base_type = vtn_base_type_sampled_image;
1380 val->type->image = vtn_value(b, w[2], vtn_value_type_type)->type;
1381 val->type->type = val->type->image->type;
1382 break;
1383
1384 case SpvOpTypeSampler:
1385 /* The actual sampler type here doesn't really matter. It gets
1386 * thrown away the moment you combine it with an image. What really
1387 * matters is that it's a sampler type as opposed to an integer type
1388 * so the backend knows what to do.
1389 */
1390 val->type->base_type = vtn_base_type_sampler;
1391 val->type->type = glsl_bare_sampler_type();
1392 break;
1393
1394 case SpvOpTypeOpaque:
1395 case SpvOpTypeEvent:
1396 case SpvOpTypeDeviceEvent:
1397 case SpvOpTypeReserveId:
1398 case SpvOpTypeQueue:
1399 case SpvOpTypePipe:
1400 default:
1401 vtn_fail("Unhandled opcode");
1402 }
1403
1404 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1405
1406 if (val->type->base_type == vtn_base_type_struct &&
1407 (val->type->block || val->type->buffer_block)) {
1408 for (unsigned i = 0; i < val->type->length; i++) {
1409 vtn_fail_if(vtn_type_contains_block(b, val->type->members[i]),
1410 "Block and BufferBlock decorations cannot decorate a "
1411 "structure type that is nested at any level inside "
1412 "another structure type decorated with Block or "
1413 "BufferBlock.");
1414 }
1415 }
1416 }
1417
1418 static nir_constant *
1419 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
1420 {
1421 nir_constant *c = rzalloc(b, nir_constant);
1422
1423 /* For pointers and other typeless things, we have to return something but
1424 * it doesn't matter what.
1425 */
1426 if (!type)
1427 return c;
1428
1429 switch (glsl_get_base_type(type)) {
1430 case GLSL_TYPE_INT:
1431 case GLSL_TYPE_UINT:
1432 case GLSL_TYPE_INT16:
1433 case GLSL_TYPE_UINT16:
1434 case GLSL_TYPE_UINT8:
1435 case GLSL_TYPE_INT8:
1436 case GLSL_TYPE_INT64:
1437 case GLSL_TYPE_UINT64:
1438 case GLSL_TYPE_BOOL:
1439 case GLSL_TYPE_FLOAT:
1440 case GLSL_TYPE_FLOAT16:
1441 case GLSL_TYPE_DOUBLE:
1442 /* Nothing to do here. It's already initialized to zero */
1443 break;
1444
1445 case GLSL_TYPE_ARRAY:
1446 vtn_assert(glsl_get_length(type) > 0);
1447 c->num_elements = glsl_get_length(type);
1448 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1449
1450 c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
1451 for (unsigned i = 1; i < c->num_elements; i++)
1452 c->elements[i] = c->elements[0];
1453 break;
1454
1455 case GLSL_TYPE_STRUCT:
1456 c->num_elements = glsl_get_length(type);
1457 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1458
1459 for (unsigned i = 0; i < c->num_elements; i++) {
1460 c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
1461 }
1462 break;
1463
1464 default:
1465 vtn_fail("Invalid type for null constant");
1466 }
1467
1468 return c;
1469 }
1470
1471 static void
1472 spec_constant_decoration_cb(struct vtn_builder *b, struct vtn_value *v,
1473 int member, const struct vtn_decoration *dec,
1474 void *data)
1475 {
1476 vtn_assert(member == -1);
1477 if (dec->decoration != SpvDecorationSpecId)
1478 return;
1479
1480 struct spec_constant_value *const_value = data;
1481
1482 for (unsigned i = 0; i < b->num_specializations; i++) {
1483 if (b->specializations[i].id == dec->literals[0]) {
1484 if (const_value->is_double)
1485 const_value->data64 = b->specializations[i].data64;
1486 else
1487 const_value->data32 = b->specializations[i].data32;
1488 return;
1489 }
1490 }
1491 }
1492
1493 static uint32_t
1494 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1495 uint32_t const_value)
1496 {
1497 struct spec_constant_value data;
1498 data.is_double = false;
1499 data.data32 = const_value;
1500 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1501 return data.data32;
1502 }
1503
1504 static uint64_t
1505 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1506 uint64_t const_value)
1507 {
1508 struct spec_constant_value data;
1509 data.is_double = true;
1510 data.data64 = const_value;
1511 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1512 return data.data64;
1513 }
1514
1515 static void
1516 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1517 struct vtn_value *val,
1518 int member,
1519 const struct vtn_decoration *dec,
1520 void *data)
1521 {
1522 vtn_assert(member == -1);
1523 if (dec->decoration != SpvDecorationBuiltIn ||
1524 dec->literals[0] != SpvBuiltInWorkgroupSize)
1525 return;
1526
1527 vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1528
1529 b->shader->info.cs.local_size[0] = val->constant->values[0].u32[0];
1530 b->shader->info.cs.local_size[1] = val->constant->values[0].u32[1];
1531 b->shader->info.cs.local_size[2] = val->constant->values[0].u32[2];
1532 }
1533
1534 static void
1535 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1536 const uint32_t *w, unsigned count)
1537 {
1538 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1539 val->constant = rzalloc(b, nir_constant);
1540 switch (opcode) {
1541 case SpvOpConstantTrue:
1542 case SpvOpConstantFalse:
1543 case SpvOpSpecConstantTrue:
1544 case SpvOpSpecConstantFalse: {
1545 vtn_fail_if(val->type->type != glsl_bool_type(),
1546 "Result type of %s must be OpTypeBool",
1547 spirv_op_to_string(opcode));
1548
1549 uint32_t int_val = (opcode == SpvOpConstantTrue ||
1550 opcode == SpvOpSpecConstantTrue);
1551
1552 if (opcode == SpvOpSpecConstantTrue ||
1553 opcode == SpvOpSpecConstantFalse)
1554 int_val = get_specialization(b, val, int_val);
1555
1556 val->constant->values[0].b[0] = int_val != 0;
1557 break;
1558 }
1559
1560 case SpvOpConstant: {
1561 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1562 "Result type of %s must be a scalar",
1563 spirv_op_to_string(opcode));
1564 int bit_size = glsl_get_bit_size(val->type->type);
1565 switch (bit_size) {
1566 case 64:
1567 val->constant->values->u64[0] = vtn_u64_literal(&w[3]);
1568 break;
1569 case 32:
1570 val->constant->values->u32[0] = w[3];
1571 break;
1572 case 16:
1573 val->constant->values->u16[0] = w[3];
1574 break;
1575 case 8:
1576 val->constant->values->u8[0] = w[3];
1577 break;
1578 default:
1579 vtn_fail("Unsupported SpvOpConstant bit size");
1580 }
1581 break;
1582 }
1583
1584 case SpvOpSpecConstant: {
1585 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1586 "Result type of %s must be a scalar",
1587 spirv_op_to_string(opcode));
1588 int bit_size = glsl_get_bit_size(val->type->type);
1589 switch (bit_size) {
1590 case 64:
1591 val->constant->values[0].u64[0] =
1592 get_specialization64(b, val, vtn_u64_literal(&w[3]));
1593 break;
1594 case 32:
1595 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1596 break;
1597 case 16:
1598 val->constant->values[0].u16[0] = get_specialization(b, val, w[3]);
1599 break;
1600 case 8:
1601 val->constant->values[0].u8[0] = get_specialization(b, val, w[3]);
1602 break;
1603 default:
1604 vtn_fail("Unsupported SpvOpSpecConstant bit size");
1605 }
1606 break;
1607 }
1608
1609 case SpvOpSpecConstantComposite:
1610 case SpvOpConstantComposite: {
1611 unsigned elem_count = count - 3;
1612 vtn_fail_if(elem_count != val->type->length,
1613 "%s has %u constituents, expected %u",
1614 spirv_op_to_string(opcode), elem_count, val->type->length);
1615
1616 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1617 for (unsigned i = 0; i < elem_count; i++) {
1618 struct vtn_value *val = vtn_untyped_value(b, w[i + 3]);
1619
1620 if (val->value_type == vtn_value_type_constant) {
1621 elems[i] = val->constant;
1622 } else {
1623 vtn_fail_if(val->value_type != vtn_value_type_undef,
1624 "only constants or undefs allowed for "
1625 "SpvOpConstantComposite");
1626 /* to make it easier, just insert a NULL constant for now */
1627 elems[i] = vtn_null_constant(b, val->type->type);
1628 }
1629 }
1630
1631 switch (val->type->base_type) {
1632 case vtn_base_type_vector: {
1633 assert(glsl_type_is_vector(val->type->type));
1634 int bit_size = glsl_get_bit_size(val->type->type);
1635 for (unsigned i = 0; i < elem_count; i++) {
1636 switch (bit_size) {
1637 case 64:
1638 val->constant->values[0].u64[i] = elems[i]->values[0].u64[0];
1639 break;
1640 case 32:
1641 val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1642 break;
1643 case 16:
1644 val->constant->values[0].u16[i] = elems[i]->values[0].u16[0];
1645 break;
1646 case 8:
1647 val->constant->values[0].u8[i] = elems[i]->values[0].u8[0];
1648 break;
1649 case 1:
1650 val->constant->values[0].b[i] = elems[i]->values[0].b[0];
1651 break;
1652 default:
1653 vtn_fail("Invalid SpvOpConstantComposite bit size");
1654 }
1655 }
1656 break;
1657 }
1658
1659 case vtn_base_type_matrix:
1660 assert(glsl_type_is_matrix(val->type->type));
1661 for (unsigned i = 0; i < elem_count; i++)
1662 val->constant->values[i] = elems[i]->values[0];
1663 break;
1664
1665 case vtn_base_type_struct:
1666 case vtn_base_type_array:
1667 ralloc_steal(val->constant, elems);
1668 val->constant->num_elements = elem_count;
1669 val->constant->elements = elems;
1670 break;
1671
1672 default:
1673 vtn_fail("Result type of %s must be a composite type",
1674 spirv_op_to_string(opcode));
1675 }
1676 break;
1677 }
1678
1679 case SpvOpSpecConstantOp: {
1680 SpvOp opcode = get_specialization(b, val, w[3]);
1681 switch (opcode) {
1682 case SpvOpVectorShuffle: {
1683 struct vtn_value *v0 = &b->values[w[4]];
1684 struct vtn_value *v1 = &b->values[w[5]];
1685
1686 vtn_assert(v0->value_type == vtn_value_type_constant ||
1687 v0->value_type == vtn_value_type_undef);
1688 vtn_assert(v1->value_type == vtn_value_type_constant ||
1689 v1->value_type == vtn_value_type_undef);
1690
1691 unsigned len0 = glsl_get_vector_elements(v0->type->type);
1692 unsigned len1 = glsl_get_vector_elements(v1->type->type);
1693
1694 vtn_assert(len0 + len1 < 16);
1695
1696 unsigned bit_size = glsl_get_bit_size(val->type->type);
1697 unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1698 unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1699
1700 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1701 (void)bit_size0; (void)bit_size1;
1702
1703 if (bit_size == 64) {
1704 uint64_t u64[8];
1705 if (v0->value_type == vtn_value_type_constant) {
1706 for (unsigned i = 0; i < len0; i++)
1707 u64[i] = v0->constant->values[0].u64[i];
1708 }
1709 if (v1->value_type == vtn_value_type_constant) {
1710 for (unsigned i = 0; i < len1; i++)
1711 u64[len0 + i] = v1->constant->values[0].u64[i];
1712 }
1713
1714 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1715 uint32_t comp = w[i + 6];
1716 /* If component is not used, set the value to a known constant
1717 * to detect if it is wrongly used.
1718 */
1719 if (comp == (uint32_t)-1)
1720 val->constant->values[0].u64[j] = 0xdeadbeefdeadbeef;
1721 else
1722 val->constant->values[0].u64[j] = u64[comp];
1723 }
1724 } else {
1725 /* This is for both 32-bit and 16-bit values */
1726 uint32_t u32[8];
1727 if (v0->value_type == vtn_value_type_constant) {
1728 for (unsigned i = 0; i < len0; i++)
1729 u32[i] = v0->constant->values[0].u32[i];
1730 }
1731 if (v1->value_type == vtn_value_type_constant) {
1732 for (unsigned i = 0; i < len1; i++)
1733 u32[len0 + i] = v1->constant->values[0].u32[i];
1734 }
1735
1736 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1737 uint32_t comp = w[i + 6];
1738 /* If component is not used, set the value to a known constant
1739 * to detect if it is wrongly used.
1740 */
1741 if (comp == (uint32_t)-1)
1742 val->constant->values[0].u32[j] = 0xdeadbeef;
1743 else
1744 val->constant->values[0].u32[j] = u32[comp];
1745 }
1746 }
1747 break;
1748 }
1749
1750 case SpvOpCompositeExtract:
1751 case SpvOpCompositeInsert: {
1752 struct vtn_value *comp;
1753 unsigned deref_start;
1754 struct nir_constant **c;
1755 if (opcode == SpvOpCompositeExtract) {
1756 comp = vtn_value(b, w[4], vtn_value_type_constant);
1757 deref_start = 5;
1758 c = &comp->constant;
1759 } else {
1760 comp = vtn_value(b, w[5], vtn_value_type_constant);
1761 deref_start = 6;
1762 val->constant = nir_constant_clone(comp->constant,
1763 (nir_variable *)b);
1764 c = &val->constant;
1765 }
1766
1767 int elem = -1;
1768 int col = 0;
1769 const struct vtn_type *type = comp->type;
1770 for (unsigned i = deref_start; i < count; i++) {
1771 vtn_fail_if(w[i] > type->length,
1772 "%uth index of %s is %u but the type has only "
1773 "%u elements", i - deref_start,
1774 spirv_op_to_string(opcode), w[i], type->length);
1775
1776 switch (type->base_type) {
1777 case vtn_base_type_vector:
1778 elem = w[i];
1779 type = type->array_element;
1780 break;
1781
1782 case vtn_base_type_matrix:
1783 assert(col == 0 && elem == -1);
1784 col = w[i];
1785 elem = 0;
1786 type = type->array_element;
1787 break;
1788
1789 case vtn_base_type_array:
1790 c = &(*c)->elements[w[i]];
1791 type = type->array_element;
1792 break;
1793
1794 case vtn_base_type_struct:
1795 c = &(*c)->elements[w[i]];
1796 type = type->members[w[i]];
1797 break;
1798
1799 default:
1800 vtn_fail("%s must only index into composite types",
1801 spirv_op_to_string(opcode));
1802 }
1803 }
1804
1805 if (opcode == SpvOpCompositeExtract) {
1806 if (elem == -1) {
1807 val->constant = *c;
1808 } else {
1809 unsigned num_components = type->length;
1810 unsigned bit_size = glsl_get_bit_size(type->type);
1811 for (unsigned i = 0; i < num_components; i++)
1812 switch(bit_size) {
1813 case 64:
1814 val->constant->values[0].u64[i] = (*c)->values[col].u64[elem + i];
1815 break;
1816 case 32:
1817 val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1818 break;
1819 case 16:
1820 val->constant->values[0].u16[i] = (*c)->values[col].u16[elem + i];
1821 break;
1822 case 8:
1823 val->constant->values[0].u8[i] = (*c)->values[col].u8[elem + i];
1824 break;
1825 case 1:
1826 val->constant->values[0].b[i] = (*c)->values[col].b[elem + i];
1827 break;
1828 default:
1829 vtn_fail("Invalid SpvOpCompositeExtract bit size");
1830 }
1831 }
1832 } else {
1833 struct vtn_value *insert =
1834 vtn_value(b, w[4], vtn_value_type_constant);
1835 vtn_assert(insert->type == type);
1836 if (elem == -1) {
1837 *c = insert->constant;
1838 } else {
1839 unsigned num_components = type->length;
1840 unsigned bit_size = glsl_get_bit_size(type->type);
1841 for (unsigned i = 0; i < num_components; i++)
1842 switch (bit_size) {
1843 case 64:
1844 (*c)->values[col].u64[elem + i] = insert->constant->values[0].u64[i];
1845 break;
1846 case 32:
1847 (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1848 break;
1849 case 16:
1850 (*c)->values[col].u16[elem + i] = insert->constant->values[0].u16[i];
1851 break;
1852 case 8:
1853 (*c)->values[col].u8[elem + i] = insert->constant->values[0].u8[i];
1854 break;
1855 case 1:
1856 (*c)->values[col].b[elem + i] = insert->constant->values[0].b[i];
1857 break;
1858 default:
1859 vtn_fail("Invalid SpvOpCompositeInsert bit size");
1860 }
1861 }
1862 }
1863 break;
1864 }
1865
1866 default: {
1867 bool swap;
1868 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
1869 nir_alu_type src_alu_type = dst_alu_type;
1870 unsigned num_components = glsl_get_vector_elements(val->type->type);
1871 unsigned bit_size;
1872
1873 vtn_assert(count <= 7);
1874
1875 switch (opcode) {
1876 case SpvOpSConvert:
1877 case SpvOpFConvert:
1878 /* We have a source in a conversion */
1879 src_alu_type =
1880 nir_get_nir_type_for_glsl_type(
1881 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1882 /* We use the bitsize of the conversion source to evaluate the opcode later */
1883 bit_size = glsl_get_bit_size(
1884 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1885 break;
1886 default:
1887 bit_size = glsl_get_bit_size(val->type->type);
1888 };
1889
1890 nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
1891 nir_alu_type_get_type_size(src_alu_type),
1892 nir_alu_type_get_type_size(dst_alu_type));
1893 nir_const_value src[4];
1894
1895 for (unsigned i = 0; i < count - 4; i++) {
1896 struct vtn_value *src_val =
1897 vtn_value(b, w[4 + i], vtn_value_type_constant);
1898
1899 /* If this is an unsized source, pull the bit size from the
1900 * source; otherwise, we'll use the bit size from the destination.
1901 */
1902 if (!nir_alu_type_get_type_size(nir_op_infos[op].input_types[i]))
1903 bit_size = glsl_get_bit_size(src_val->type->type);
1904
1905 unsigned j = swap ? 1 - i : i;
1906 src[j] = src_val->constant->values[0];
1907 }
1908
1909 /* fix up fixed size sources */
1910 switch (op) {
1911 case nir_op_ishl:
1912 case nir_op_ishr:
1913 case nir_op_ushr: {
1914 if (bit_size == 32)
1915 break;
1916 for (unsigned i = 0; i < num_components; ++i) {
1917 switch (bit_size) {
1918 case 64: src[1].u32[i] = src[1].u64[i]; break;
1919 case 16: src[1].u32[i] = src[1].u16[i]; break;
1920 case 8: src[1].u32[i] = src[1].u8[i]; break;
1921 }
1922 }
1923 break;
1924 }
1925 default:
1926 break;
1927 }
1928
1929 val->constant->values[0] =
1930 nir_eval_const_opcode(op, num_components, bit_size, src);
1931 break;
1932 } /* default */
1933 }
1934 break;
1935 }
1936
1937 case SpvOpConstantNull:
1938 val->constant = vtn_null_constant(b, val->type->type);
1939 break;
1940
1941 case SpvOpConstantSampler:
1942 vtn_fail("OpConstantSampler requires Kernel Capability");
1943 break;
1944
1945 default:
1946 vtn_fail("Unhandled opcode");
1947 }
1948
1949 /* Now that we have the value, update the workgroup size if needed */
1950 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1951 }
1952
1953 struct vtn_ssa_value *
1954 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1955 {
1956 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1957 val->type = type;
1958
1959 if (!glsl_type_is_vector_or_scalar(type)) {
1960 unsigned elems = glsl_get_length(type);
1961 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1962 for (unsigned i = 0; i < elems; i++) {
1963 const struct glsl_type *child_type;
1964
1965 switch (glsl_get_base_type(type)) {
1966 case GLSL_TYPE_INT:
1967 case GLSL_TYPE_UINT:
1968 case GLSL_TYPE_INT16:
1969 case GLSL_TYPE_UINT16:
1970 case GLSL_TYPE_UINT8:
1971 case GLSL_TYPE_INT8:
1972 case GLSL_TYPE_INT64:
1973 case GLSL_TYPE_UINT64:
1974 case GLSL_TYPE_BOOL:
1975 case GLSL_TYPE_FLOAT:
1976 case GLSL_TYPE_FLOAT16:
1977 case GLSL_TYPE_DOUBLE:
1978 child_type = glsl_get_column_type(type);
1979 break;
1980 case GLSL_TYPE_ARRAY:
1981 child_type = glsl_get_array_element(type);
1982 break;
1983 case GLSL_TYPE_STRUCT:
1984 child_type = glsl_get_struct_field(type, i);
1985 break;
1986 default:
1987 vtn_fail("unkown base type");
1988 }
1989
1990 val->elems[i] = vtn_create_ssa_value(b, child_type);
1991 }
1992 }
1993
1994 return val;
1995 }
1996
1997 static nir_tex_src
1998 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1999 {
2000 nir_tex_src src;
2001 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
2002 src.src_type = type;
2003 return src;
2004 }
2005
2006 static void
2007 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
2008 const uint32_t *w, unsigned count)
2009 {
2010 if (opcode == SpvOpSampledImage) {
2011 struct vtn_value *val =
2012 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
2013 val->sampled_image = ralloc(b, struct vtn_sampled_image);
2014 val->sampled_image->type =
2015 vtn_value(b, w[1], vtn_value_type_type)->type;
2016 val->sampled_image->image =
2017 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2018 val->sampled_image->sampler =
2019 vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
2020 return;
2021 } else if (opcode == SpvOpImage) {
2022 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
2023 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
2024 if (src_val->value_type == vtn_value_type_sampled_image) {
2025 val->pointer = src_val->sampled_image->image;
2026 } else {
2027 vtn_assert(src_val->value_type == vtn_value_type_pointer);
2028 val->pointer = src_val->pointer;
2029 }
2030 return;
2031 }
2032
2033 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
2034 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2035
2036 struct vtn_sampled_image sampled;
2037 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
2038 if (sampled_val->value_type == vtn_value_type_sampled_image) {
2039 sampled = *sampled_val->sampled_image;
2040 } else {
2041 vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
2042 sampled.type = sampled_val->pointer->type;
2043 sampled.image = NULL;
2044 sampled.sampler = sampled_val->pointer;
2045 }
2046
2047 const struct glsl_type *image_type = sampled.type->type;
2048 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
2049 const bool is_array = glsl_sampler_type_is_array(image_type);
2050
2051 /* Figure out the base texture operation */
2052 nir_texop texop;
2053 switch (opcode) {
2054 case SpvOpImageSampleImplicitLod:
2055 case SpvOpImageSampleDrefImplicitLod:
2056 case SpvOpImageSampleProjImplicitLod:
2057 case SpvOpImageSampleProjDrefImplicitLod:
2058 texop = nir_texop_tex;
2059 break;
2060
2061 case SpvOpImageSampleExplicitLod:
2062 case SpvOpImageSampleDrefExplicitLod:
2063 case SpvOpImageSampleProjExplicitLod:
2064 case SpvOpImageSampleProjDrefExplicitLod:
2065 texop = nir_texop_txl;
2066 break;
2067
2068 case SpvOpImageFetch:
2069 if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
2070 texop = nir_texop_txf_ms;
2071 } else {
2072 texop = nir_texop_txf;
2073 }
2074 break;
2075
2076 case SpvOpImageGather:
2077 case SpvOpImageDrefGather:
2078 texop = nir_texop_tg4;
2079 break;
2080
2081 case SpvOpImageQuerySizeLod:
2082 case SpvOpImageQuerySize:
2083 texop = nir_texop_txs;
2084 break;
2085
2086 case SpvOpImageQueryLod:
2087 texop = nir_texop_lod;
2088 break;
2089
2090 case SpvOpImageQueryLevels:
2091 texop = nir_texop_query_levels;
2092 break;
2093
2094 case SpvOpImageQuerySamples:
2095 texop = nir_texop_texture_samples;
2096 break;
2097
2098 default:
2099 vtn_fail("Unhandled opcode");
2100 }
2101
2102 nir_tex_src srcs[10]; /* 10 should be enough */
2103 nir_tex_src *p = srcs;
2104
2105 nir_deref_instr *sampler = vtn_pointer_to_deref(b, sampled.sampler);
2106 nir_deref_instr *texture =
2107 sampled.image ? vtn_pointer_to_deref(b, sampled.image) : sampler;
2108
2109 p->src = nir_src_for_ssa(&texture->dest.ssa);
2110 p->src_type = nir_tex_src_texture_deref;
2111 p++;
2112
2113 switch (texop) {
2114 case nir_texop_tex:
2115 case nir_texop_txb:
2116 case nir_texop_txl:
2117 case nir_texop_txd:
2118 case nir_texop_tg4:
2119 /* These operations require a sampler */
2120 p->src = nir_src_for_ssa(&sampler->dest.ssa);
2121 p->src_type = nir_tex_src_sampler_deref;
2122 p++;
2123 break;
2124 case nir_texop_txf:
2125 case nir_texop_txf_ms:
2126 case nir_texop_txs:
2127 case nir_texop_lod:
2128 case nir_texop_query_levels:
2129 case nir_texop_texture_samples:
2130 case nir_texop_samples_identical:
2131 /* These don't */
2132 break;
2133 case nir_texop_txf_ms_mcs:
2134 vtn_fail("unexpected nir_texop_txf_ms_mcs");
2135 }
2136
2137 unsigned idx = 4;
2138
2139 struct nir_ssa_def *coord;
2140 unsigned coord_components;
2141 switch (opcode) {
2142 case SpvOpImageSampleImplicitLod:
2143 case SpvOpImageSampleExplicitLod:
2144 case SpvOpImageSampleDrefImplicitLod:
2145 case SpvOpImageSampleDrefExplicitLod:
2146 case SpvOpImageSampleProjImplicitLod:
2147 case SpvOpImageSampleProjExplicitLod:
2148 case SpvOpImageSampleProjDrefImplicitLod:
2149 case SpvOpImageSampleProjDrefExplicitLod:
2150 case SpvOpImageFetch:
2151 case SpvOpImageGather:
2152 case SpvOpImageDrefGather:
2153 case SpvOpImageQueryLod: {
2154 /* All these types have the coordinate as their first real argument */
2155 switch (sampler_dim) {
2156 case GLSL_SAMPLER_DIM_1D:
2157 case GLSL_SAMPLER_DIM_BUF:
2158 coord_components = 1;
2159 break;
2160 case GLSL_SAMPLER_DIM_2D:
2161 case GLSL_SAMPLER_DIM_RECT:
2162 case GLSL_SAMPLER_DIM_MS:
2163 coord_components = 2;
2164 break;
2165 case GLSL_SAMPLER_DIM_3D:
2166 case GLSL_SAMPLER_DIM_CUBE:
2167 coord_components = 3;
2168 break;
2169 default:
2170 vtn_fail("Invalid sampler type");
2171 }
2172
2173 if (is_array && texop != nir_texop_lod)
2174 coord_components++;
2175
2176 coord = vtn_ssa_value(b, w[idx++])->def;
2177 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
2178 (1 << coord_components) - 1));
2179 p->src_type = nir_tex_src_coord;
2180 p++;
2181 break;
2182 }
2183
2184 default:
2185 coord = NULL;
2186 coord_components = 0;
2187 break;
2188 }
2189
2190 switch (opcode) {
2191 case SpvOpImageSampleProjImplicitLod:
2192 case SpvOpImageSampleProjExplicitLod:
2193 case SpvOpImageSampleProjDrefImplicitLod:
2194 case SpvOpImageSampleProjDrefExplicitLod:
2195 /* These have the projector as the last coordinate component */
2196 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
2197 p->src_type = nir_tex_src_projector;
2198 p++;
2199 break;
2200
2201 default:
2202 break;
2203 }
2204
2205 bool is_shadow = false;
2206 unsigned gather_component = 0;
2207 switch (opcode) {
2208 case SpvOpImageSampleDrefImplicitLod:
2209 case SpvOpImageSampleDrefExplicitLod:
2210 case SpvOpImageSampleProjDrefImplicitLod:
2211 case SpvOpImageSampleProjDrefExplicitLod:
2212 case SpvOpImageDrefGather:
2213 /* These all have an explicit depth value as their next source */
2214 is_shadow = true;
2215 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2216 break;
2217
2218 case SpvOpImageGather:
2219 /* This has a component as its next source */
2220 gather_component =
2221 vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
2222 break;
2223
2224 default:
2225 break;
2226 }
2227
2228 /* For OpImageQuerySizeLod, we always have an LOD */
2229 if (opcode == SpvOpImageQuerySizeLod)
2230 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2231
2232 /* Now we need to handle some number of optional arguments */
2233 const struct vtn_ssa_value *gather_offsets = NULL;
2234 if (idx < count) {
2235 uint32_t operands = w[idx++];
2236
2237 if (operands & SpvImageOperandsBiasMask) {
2238 vtn_assert(texop == nir_texop_tex);
2239 texop = nir_texop_txb;
2240 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
2241 }
2242
2243 if (operands & SpvImageOperandsLodMask) {
2244 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2245 texop == nir_texop_txs);
2246 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2247 }
2248
2249 if (operands & SpvImageOperandsGradMask) {
2250 vtn_assert(texop == nir_texop_txl);
2251 texop = nir_texop_txd;
2252 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
2253 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
2254 }
2255
2256 if (operands & SpvImageOperandsOffsetMask ||
2257 operands & SpvImageOperandsConstOffsetMask)
2258 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
2259
2260 if (operands & SpvImageOperandsConstOffsetsMask) {
2261 nir_tex_src none = {0};
2262 gather_offsets = vtn_ssa_value(b, w[idx++]);
2263 (*p++) = none;
2264 }
2265
2266 if (operands & SpvImageOperandsSampleMask) {
2267 vtn_assert(texop == nir_texop_txf_ms);
2268 texop = nir_texop_txf_ms;
2269 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2270 }
2271
2272 if (operands & SpvImageOperandsMinLodMask) {
2273 vtn_assert(texop == nir_texop_tex ||
2274 texop == nir_texop_txb ||
2275 texop == nir_texop_txd);
2276 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_min_lod);
2277 }
2278 }
2279 /* We should have now consumed exactly all of the arguments */
2280 vtn_assert(idx == count);
2281
2282 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2283 instr->op = texop;
2284
2285 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2286
2287 instr->coord_components = coord_components;
2288 instr->sampler_dim = sampler_dim;
2289 instr->is_array = is_array;
2290 instr->is_shadow = is_shadow;
2291 instr->is_new_style_shadow =
2292 is_shadow && glsl_get_components(ret_type->type) == 1;
2293 instr->component = gather_component;
2294
2295 switch (glsl_get_sampler_result_type(image_type)) {
2296 case GLSL_TYPE_FLOAT: instr->dest_type = nir_type_float; break;
2297 case GLSL_TYPE_INT: instr->dest_type = nir_type_int; break;
2298 case GLSL_TYPE_UINT: instr->dest_type = nir_type_uint; break;
2299 case GLSL_TYPE_BOOL: instr->dest_type = nir_type_bool; break;
2300 default:
2301 vtn_fail("Invalid base type for sampler result");
2302 }
2303
2304 nir_ssa_dest_init(&instr->instr, &instr->dest,
2305 nir_tex_instr_dest_size(instr), 32, NULL);
2306
2307 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2308 nir_tex_instr_dest_size(instr));
2309
2310 nir_ssa_def *def;
2311 nir_instr *instruction;
2312 if (gather_offsets) {
2313 vtn_assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
2314 vtn_assert(glsl_get_length(gather_offsets->type) == 4);
2315 nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
2316
2317 /* Copy the current instruction 4x */
2318 for (uint32_t i = 1; i < 4; i++) {
2319 instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
2320 instrs[i]->op = instr->op;
2321 instrs[i]->coord_components = instr->coord_components;
2322 instrs[i]->sampler_dim = instr->sampler_dim;
2323 instrs[i]->is_array = instr->is_array;
2324 instrs[i]->is_shadow = instr->is_shadow;
2325 instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
2326 instrs[i]->component = instr->component;
2327 instrs[i]->dest_type = instr->dest_type;
2328
2329 memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
2330
2331 nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
2332 nir_tex_instr_dest_size(instr), 32, NULL);
2333 }
2334
2335 /* Fill in the last argument with the offset from the passed in offsets
2336 * and insert the instruction into the stream.
2337 */
2338 for (uint32_t i = 0; i < 4; i++) {
2339 nir_tex_src src;
2340 src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
2341 src.src_type = nir_tex_src_offset;
2342 instrs[i]->src[instrs[i]->num_srcs - 1] = src;
2343 nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
2344 }
2345
2346 /* Combine the results of the 4 instructions by taking their .w
2347 * components
2348 */
2349 nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
2350 nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
2351 vec4->dest.write_mask = 0xf;
2352 for (uint32_t i = 0; i < 4; i++) {
2353 vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
2354 vec4->src[i].swizzle[0] = 3;
2355 }
2356 def = &vec4->dest.dest.ssa;
2357 instruction = &vec4->instr;
2358 } else {
2359 def = &instr->dest.ssa;
2360 instruction = &instr->instr;
2361 }
2362
2363 val->ssa = vtn_create_ssa_value(b, ret_type->type);
2364 val->ssa->def = def;
2365
2366 nir_builder_instr_insert(&b->nb, instruction);
2367 }
2368
2369 static void
2370 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2371 const uint32_t *w, nir_src *src)
2372 {
2373 switch (opcode) {
2374 case SpvOpAtomicIIncrement:
2375 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2376 break;
2377
2378 case SpvOpAtomicIDecrement:
2379 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2380 break;
2381
2382 case SpvOpAtomicISub:
2383 src[0] =
2384 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
2385 break;
2386
2387 case SpvOpAtomicCompareExchange:
2388 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
2389 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
2390 break;
2391
2392 case SpvOpAtomicExchange:
2393 case SpvOpAtomicIAdd:
2394 case SpvOpAtomicSMin:
2395 case SpvOpAtomicUMin:
2396 case SpvOpAtomicSMax:
2397 case SpvOpAtomicUMax:
2398 case SpvOpAtomicAnd:
2399 case SpvOpAtomicOr:
2400 case SpvOpAtomicXor:
2401 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
2402 break;
2403
2404 default:
2405 vtn_fail("Invalid SPIR-V atomic");
2406 }
2407 }
2408
2409 static nir_ssa_def *
2410 get_image_coord(struct vtn_builder *b, uint32_t value)
2411 {
2412 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
2413
2414 /* The image_load_store intrinsics assume a 4-dim coordinate */
2415 unsigned dim = glsl_get_vector_elements(coord->type);
2416 unsigned swizzle[4];
2417 for (unsigned i = 0; i < 4; i++)
2418 swizzle[i] = MIN2(i, dim - 1);
2419
2420 return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
2421 }
2422
2423 static nir_ssa_def *
2424 expand_to_vec4(nir_builder *b, nir_ssa_def *value)
2425 {
2426 if (value->num_components == 4)
2427 return value;
2428
2429 unsigned swiz[4];
2430 for (unsigned i = 0; i < 4; i++)
2431 swiz[i] = i < value->num_components ? i : 0;
2432 return nir_swizzle(b, value, swiz, 4, false);
2433 }
2434
2435 static void
2436 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2437 const uint32_t *w, unsigned count)
2438 {
2439 /* Just get this one out of the way */
2440 if (opcode == SpvOpImageTexelPointer) {
2441 struct vtn_value *val =
2442 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2443 val->image = ralloc(b, struct vtn_image_pointer);
2444
2445 val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2446 val->image->coord = get_image_coord(b, w[4]);
2447 val->image->sample = vtn_ssa_value(b, w[5])->def;
2448 return;
2449 }
2450
2451 struct vtn_image_pointer image;
2452
2453 switch (opcode) {
2454 case SpvOpAtomicExchange:
2455 case SpvOpAtomicCompareExchange:
2456 case SpvOpAtomicCompareExchangeWeak:
2457 case SpvOpAtomicIIncrement:
2458 case SpvOpAtomicIDecrement:
2459 case SpvOpAtomicIAdd:
2460 case SpvOpAtomicISub:
2461 case SpvOpAtomicLoad:
2462 case SpvOpAtomicSMin:
2463 case SpvOpAtomicUMin:
2464 case SpvOpAtomicSMax:
2465 case SpvOpAtomicUMax:
2466 case SpvOpAtomicAnd:
2467 case SpvOpAtomicOr:
2468 case SpvOpAtomicXor:
2469 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2470 break;
2471
2472 case SpvOpAtomicStore:
2473 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2474 break;
2475
2476 case SpvOpImageQuerySize:
2477 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2478 image.coord = NULL;
2479 image.sample = NULL;
2480 break;
2481
2482 case SpvOpImageRead:
2483 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2484 image.coord = get_image_coord(b, w[4]);
2485
2486 if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
2487 vtn_assert(w[5] == SpvImageOperandsSampleMask);
2488 image.sample = vtn_ssa_value(b, w[6])->def;
2489 } else {
2490 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2491 }
2492 break;
2493
2494 case SpvOpImageWrite:
2495 image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2496 image.coord = get_image_coord(b, w[2]);
2497
2498 /* texel = w[3] */
2499
2500 if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
2501 vtn_assert(w[4] == SpvImageOperandsSampleMask);
2502 image.sample = vtn_ssa_value(b, w[5])->def;
2503 } else {
2504 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2505 }
2506 break;
2507
2508 default:
2509 vtn_fail("Invalid image opcode");
2510 }
2511
2512 nir_intrinsic_op op;
2513 switch (opcode) {
2514 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_deref_##N; break;
2515 OP(ImageQuerySize, size)
2516 OP(ImageRead, load)
2517 OP(ImageWrite, store)
2518 OP(AtomicLoad, load)
2519 OP(AtomicStore, store)
2520 OP(AtomicExchange, atomic_exchange)
2521 OP(AtomicCompareExchange, atomic_comp_swap)
2522 OP(AtomicIIncrement, atomic_add)
2523 OP(AtomicIDecrement, atomic_add)
2524 OP(AtomicIAdd, atomic_add)
2525 OP(AtomicISub, atomic_add)
2526 OP(AtomicSMin, atomic_min)
2527 OP(AtomicUMin, atomic_min)
2528 OP(AtomicSMax, atomic_max)
2529 OP(AtomicUMax, atomic_max)
2530 OP(AtomicAnd, atomic_and)
2531 OP(AtomicOr, atomic_or)
2532 OP(AtomicXor, atomic_xor)
2533 #undef OP
2534 default:
2535 vtn_fail("Invalid image opcode");
2536 }
2537
2538 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2539
2540 nir_deref_instr *image_deref = vtn_pointer_to_deref(b, image.image);
2541 intrin->src[0] = nir_src_for_ssa(&image_deref->dest.ssa);
2542
2543 /* ImageQuerySize doesn't take any extra parameters */
2544 if (opcode != SpvOpImageQuerySize) {
2545 /* The image coordinate is always 4 components but we may not have that
2546 * many. Swizzle to compensate.
2547 */
2548 intrin->src[1] = nir_src_for_ssa(expand_to_vec4(&b->nb, image.coord));
2549 intrin->src[2] = nir_src_for_ssa(image.sample);
2550 }
2551
2552 switch (opcode) {
2553 case SpvOpAtomicLoad:
2554 case SpvOpImageQuerySize:
2555 case SpvOpImageRead:
2556 break;
2557 case SpvOpAtomicStore:
2558 case SpvOpImageWrite: {
2559 const uint32_t value_id = opcode == SpvOpAtomicStore ? w[4] : w[3];
2560 nir_ssa_def *value = vtn_ssa_value(b, value_id)->def;
2561 /* nir_intrinsic_image_deref_store always takes a vec4 value */
2562 assert(op == nir_intrinsic_image_deref_store);
2563 intrin->num_components = 4;
2564 intrin->src[3] = nir_src_for_ssa(expand_to_vec4(&b->nb, value));
2565 break;
2566 }
2567
2568 case SpvOpAtomicCompareExchange:
2569 case SpvOpAtomicIIncrement:
2570 case SpvOpAtomicIDecrement:
2571 case SpvOpAtomicExchange:
2572 case SpvOpAtomicIAdd:
2573 case SpvOpAtomicISub:
2574 case SpvOpAtomicSMin:
2575 case SpvOpAtomicUMin:
2576 case SpvOpAtomicSMax:
2577 case SpvOpAtomicUMax:
2578 case SpvOpAtomicAnd:
2579 case SpvOpAtomicOr:
2580 case SpvOpAtomicXor:
2581 fill_common_atomic_sources(b, opcode, w, &intrin->src[3]);
2582 break;
2583
2584 default:
2585 vtn_fail("Invalid image opcode");
2586 }
2587
2588 if (opcode != SpvOpImageWrite && opcode != SpvOpAtomicStore) {
2589 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2590 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2591
2592 unsigned dest_components = glsl_get_vector_elements(type->type);
2593 intrin->num_components = nir_intrinsic_infos[op].dest_components;
2594 if (intrin->num_components == 0)
2595 intrin->num_components = dest_components;
2596
2597 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2598 intrin->num_components, 32, NULL);
2599
2600 nir_builder_instr_insert(&b->nb, &intrin->instr);
2601
2602 nir_ssa_def *result = &intrin->dest.ssa;
2603 if (intrin->num_components != dest_components)
2604 result = nir_channels(&b->nb, result, (1 << dest_components) - 1);
2605
2606 val->ssa = vtn_create_ssa_value(b, type->type);
2607 val->ssa->def = result;
2608 } else {
2609 nir_builder_instr_insert(&b->nb, &intrin->instr);
2610 }
2611 }
2612
2613 static nir_intrinsic_op
2614 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2615 {
2616 switch (opcode) {
2617 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
2618 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
2619 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2620 OP(AtomicExchange, atomic_exchange)
2621 OP(AtomicCompareExchange, atomic_comp_swap)
2622 OP(AtomicIIncrement, atomic_add)
2623 OP(AtomicIDecrement, atomic_add)
2624 OP(AtomicIAdd, atomic_add)
2625 OP(AtomicISub, atomic_add)
2626 OP(AtomicSMin, atomic_imin)
2627 OP(AtomicUMin, atomic_umin)
2628 OP(AtomicSMax, atomic_imax)
2629 OP(AtomicUMax, atomic_umax)
2630 OP(AtomicAnd, atomic_and)
2631 OP(AtomicOr, atomic_or)
2632 OP(AtomicXor, atomic_xor)
2633 #undef OP
2634 default:
2635 vtn_fail("Invalid SSBO atomic");
2636 }
2637 }
2638
2639 static nir_intrinsic_op
2640 get_uniform_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2641 {
2642 switch (opcode) {
2643 #define OP(S, N) case SpvOp##S: return nir_intrinsic_atomic_counter_ ##N;
2644 OP(AtomicLoad, read_deref)
2645 OP(AtomicExchange, exchange)
2646 OP(AtomicCompareExchange, comp_swap)
2647 OP(AtomicIIncrement, inc_deref)
2648 OP(AtomicIDecrement, post_dec_deref)
2649 OP(AtomicIAdd, add_deref)
2650 OP(AtomicISub, add_deref)
2651 OP(AtomicUMin, min_deref)
2652 OP(AtomicUMax, max_deref)
2653 OP(AtomicAnd, and_deref)
2654 OP(AtomicOr, or_deref)
2655 OP(AtomicXor, xor_deref)
2656 #undef OP
2657 default:
2658 /* We left the following out: AtomicStore, AtomicSMin and
2659 * AtomicSmax. Right now there are not nir intrinsics for them. At this
2660 * moment Atomic Counter support is needed for ARB_spirv support, so is
2661 * only need to support GLSL Atomic Counters that are uints and don't
2662 * allow direct storage.
2663 */
2664 unreachable("Invalid uniform atomic");
2665 }
2666 }
2667
2668 static nir_intrinsic_op
2669 get_shared_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2670 {
2671 switch (opcode) {
2672 case SpvOpAtomicLoad: return nir_intrinsic_load_shared;
2673 case SpvOpAtomicStore: return nir_intrinsic_store_shared;
2674 #define OP(S, N) case SpvOp##S: return nir_intrinsic_shared_##N;
2675 OP(AtomicExchange, atomic_exchange)
2676 OP(AtomicCompareExchange, atomic_comp_swap)
2677 OP(AtomicIIncrement, atomic_add)
2678 OP(AtomicIDecrement, atomic_add)
2679 OP(AtomicIAdd, atomic_add)
2680 OP(AtomicISub, atomic_add)
2681 OP(AtomicSMin, atomic_imin)
2682 OP(AtomicUMin, atomic_umin)
2683 OP(AtomicSMax, atomic_imax)
2684 OP(AtomicUMax, atomic_umax)
2685 OP(AtomicAnd, atomic_and)
2686 OP(AtomicOr, atomic_or)
2687 OP(AtomicXor, atomic_xor)
2688 #undef OP
2689 default:
2690 vtn_fail("Invalid shared atomic");
2691 }
2692 }
2693
2694 static nir_intrinsic_op
2695 get_deref_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2696 {
2697 switch (opcode) {
2698 case SpvOpAtomicLoad: return nir_intrinsic_load_deref;
2699 case SpvOpAtomicStore: return nir_intrinsic_store_deref;
2700 #define OP(S, N) case SpvOp##S: return nir_intrinsic_deref_##N;
2701 OP(AtomicExchange, atomic_exchange)
2702 OP(AtomicCompareExchange, atomic_comp_swap)
2703 OP(AtomicIIncrement, atomic_add)
2704 OP(AtomicIDecrement, atomic_add)
2705 OP(AtomicIAdd, atomic_add)
2706 OP(AtomicISub, atomic_add)
2707 OP(AtomicSMin, atomic_imin)
2708 OP(AtomicUMin, atomic_umin)
2709 OP(AtomicSMax, atomic_imax)
2710 OP(AtomicUMax, atomic_umax)
2711 OP(AtomicAnd, atomic_and)
2712 OP(AtomicOr, atomic_or)
2713 OP(AtomicXor, atomic_xor)
2714 #undef OP
2715 default:
2716 vtn_fail("Invalid shared atomic");
2717 }
2718 }
2719
2720 /*
2721 * Handles shared atomics, ssbo atomics and atomic counters.
2722 */
2723 static void
2724 vtn_handle_atomics(struct vtn_builder *b, SpvOp opcode,
2725 const uint32_t *w, unsigned count)
2726 {
2727 struct vtn_pointer *ptr;
2728 nir_intrinsic_instr *atomic;
2729
2730 switch (opcode) {
2731 case SpvOpAtomicLoad:
2732 case SpvOpAtomicExchange:
2733 case SpvOpAtomicCompareExchange:
2734 case SpvOpAtomicCompareExchangeWeak:
2735 case SpvOpAtomicIIncrement:
2736 case SpvOpAtomicIDecrement:
2737 case SpvOpAtomicIAdd:
2738 case SpvOpAtomicISub:
2739 case SpvOpAtomicSMin:
2740 case SpvOpAtomicUMin:
2741 case SpvOpAtomicSMax:
2742 case SpvOpAtomicUMax:
2743 case SpvOpAtomicAnd:
2744 case SpvOpAtomicOr:
2745 case SpvOpAtomicXor:
2746 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2747 break;
2748
2749 case SpvOpAtomicStore:
2750 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2751 break;
2752
2753 default:
2754 vtn_fail("Invalid SPIR-V atomic");
2755 }
2756
2757 /*
2758 SpvScope scope = w[4];
2759 SpvMemorySemanticsMask semantics = w[5];
2760 */
2761
2762 /* uniform as "atomic counter uniform" */
2763 if (ptr->mode == vtn_variable_mode_uniform) {
2764 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
2765 const struct glsl_type *deref_type = deref->type;
2766 nir_intrinsic_op op = get_uniform_nir_atomic_op(b, opcode);
2767 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2768 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
2769
2770 /* SSBO needs to initialize index/offset. In this case we don't need to,
2771 * as that info is already stored on the ptr->var->var nir_variable (see
2772 * vtn_create_variable)
2773 */
2774
2775 switch (opcode) {
2776 case SpvOpAtomicLoad:
2777 atomic->num_components = glsl_get_vector_elements(deref_type);
2778 break;
2779
2780 case SpvOpAtomicStore:
2781 atomic->num_components = glsl_get_vector_elements(deref_type);
2782 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2783 break;
2784
2785 case SpvOpAtomicExchange:
2786 case SpvOpAtomicCompareExchange:
2787 case SpvOpAtomicCompareExchangeWeak:
2788 case SpvOpAtomicIIncrement:
2789 case SpvOpAtomicIDecrement:
2790 case SpvOpAtomicIAdd:
2791 case SpvOpAtomicISub:
2792 case SpvOpAtomicSMin:
2793 case SpvOpAtomicUMin:
2794 case SpvOpAtomicSMax:
2795 case SpvOpAtomicUMax:
2796 case SpvOpAtomicAnd:
2797 case SpvOpAtomicOr:
2798 case SpvOpAtomicXor:
2799 /* Nothing: we don't need to call fill_common_atomic_sources here, as
2800 * atomic counter uniforms doesn't have sources
2801 */
2802 break;
2803
2804 default:
2805 unreachable("Invalid SPIR-V atomic");
2806
2807 }
2808 } else if (vtn_pointer_uses_ssa_offset(b, ptr)) {
2809 nir_ssa_def *offset, *index;
2810 offset = vtn_pointer_to_offset(b, ptr, &index);
2811
2812 nir_intrinsic_op op;
2813 if (ptr->mode == vtn_variable_mode_ssbo) {
2814 op = get_ssbo_nir_atomic_op(b, opcode);
2815 } else {
2816 vtn_assert(ptr->mode == vtn_variable_mode_workgroup &&
2817 b->options->lower_workgroup_access_to_offsets);
2818 op = get_shared_nir_atomic_op(b, opcode);
2819 }
2820
2821 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2822
2823 int src = 0;
2824 switch (opcode) {
2825 case SpvOpAtomicLoad:
2826 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2827 nir_intrinsic_set_align(atomic, 4, 0);
2828 if (ptr->mode == vtn_variable_mode_ssbo)
2829 atomic->src[src++] = nir_src_for_ssa(index);
2830 atomic->src[src++] = nir_src_for_ssa(offset);
2831 break;
2832
2833 case SpvOpAtomicStore:
2834 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2835 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2836 nir_intrinsic_set_align(atomic, 4, 0);
2837 atomic->src[src++] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2838 if (ptr->mode == vtn_variable_mode_ssbo)
2839 atomic->src[src++] = nir_src_for_ssa(index);
2840 atomic->src[src++] = nir_src_for_ssa(offset);
2841 break;
2842
2843 case SpvOpAtomicExchange:
2844 case SpvOpAtomicCompareExchange:
2845 case SpvOpAtomicCompareExchangeWeak:
2846 case SpvOpAtomicIIncrement:
2847 case SpvOpAtomicIDecrement:
2848 case SpvOpAtomicIAdd:
2849 case SpvOpAtomicISub:
2850 case SpvOpAtomicSMin:
2851 case SpvOpAtomicUMin:
2852 case SpvOpAtomicSMax:
2853 case SpvOpAtomicUMax:
2854 case SpvOpAtomicAnd:
2855 case SpvOpAtomicOr:
2856 case SpvOpAtomicXor:
2857 if (ptr->mode == vtn_variable_mode_ssbo)
2858 atomic->src[src++] = nir_src_for_ssa(index);
2859 atomic->src[src++] = nir_src_for_ssa(offset);
2860 fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
2861 break;
2862
2863 default:
2864 vtn_fail("Invalid SPIR-V atomic");
2865 }
2866 } else {
2867 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
2868 const struct glsl_type *deref_type = deref->type;
2869 nir_intrinsic_op op = get_deref_nir_atomic_op(b, opcode);
2870 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2871 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
2872
2873 switch (opcode) {
2874 case SpvOpAtomicLoad:
2875 atomic->num_components = glsl_get_vector_elements(deref_type);
2876 break;
2877
2878 case SpvOpAtomicStore:
2879 atomic->num_components = glsl_get_vector_elements(deref_type);
2880 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2881 atomic->src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2882 break;
2883
2884 case SpvOpAtomicExchange:
2885 case SpvOpAtomicCompareExchange:
2886 case SpvOpAtomicCompareExchangeWeak:
2887 case SpvOpAtomicIIncrement:
2888 case SpvOpAtomicIDecrement:
2889 case SpvOpAtomicIAdd:
2890 case SpvOpAtomicISub:
2891 case SpvOpAtomicSMin:
2892 case SpvOpAtomicUMin:
2893 case SpvOpAtomicSMax:
2894 case SpvOpAtomicUMax:
2895 case SpvOpAtomicAnd:
2896 case SpvOpAtomicOr:
2897 case SpvOpAtomicXor:
2898 fill_common_atomic_sources(b, opcode, w, &atomic->src[1]);
2899 break;
2900
2901 default:
2902 vtn_fail("Invalid SPIR-V atomic");
2903 }
2904 }
2905
2906 if (opcode != SpvOpAtomicStore) {
2907 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2908
2909 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2910 glsl_get_vector_elements(type->type),
2911 glsl_get_bit_size(type->type), NULL);
2912
2913 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2914 val->ssa = rzalloc(b, struct vtn_ssa_value);
2915 val->ssa->def = &atomic->dest.ssa;
2916 val->ssa->type = type->type;
2917 }
2918
2919 nir_builder_instr_insert(&b->nb, &atomic->instr);
2920 }
2921
2922 static nir_alu_instr *
2923 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
2924 {
2925 nir_op op;
2926 switch (num_components) {
2927 case 1: op = nir_op_imov; break;
2928 case 2: op = nir_op_vec2; break;
2929 case 3: op = nir_op_vec3; break;
2930 case 4: op = nir_op_vec4; break;
2931 default: vtn_fail("bad vector size");
2932 }
2933
2934 nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
2935 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2936 bit_size, NULL);
2937 vec->dest.write_mask = (1 << num_components) - 1;
2938
2939 return vec;
2940 }
2941
2942 struct vtn_ssa_value *
2943 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2944 {
2945 if (src->transposed)
2946 return src->transposed;
2947
2948 struct vtn_ssa_value *dest =
2949 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2950
2951 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2952 nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
2953 glsl_get_bit_size(src->type));
2954 if (glsl_type_is_vector_or_scalar(src->type)) {
2955 vec->src[0].src = nir_src_for_ssa(src->def);
2956 vec->src[0].swizzle[0] = i;
2957 } else {
2958 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2959 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2960 vec->src[j].swizzle[0] = i;
2961 }
2962 }
2963 nir_builder_instr_insert(&b->nb, &vec->instr);
2964 dest->elems[i]->def = &vec->dest.dest.ssa;
2965 }
2966
2967 dest->transposed = src;
2968
2969 return dest;
2970 }
2971
2972 nir_ssa_def *
2973 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2974 {
2975 return nir_channel(&b->nb, src, index);
2976 }
2977
2978 nir_ssa_def *
2979 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2980 unsigned index)
2981 {
2982 nir_alu_instr *vec = create_vec(b, src->num_components,
2983 src->bit_size);
2984
2985 for (unsigned i = 0; i < src->num_components; i++) {
2986 if (i == index) {
2987 vec->src[i].src = nir_src_for_ssa(insert);
2988 } else {
2989 vec->src[i].src = nir_src_for_ssa(src);
2990 vec->src[i].swizzle[0] = i;
2991 }
2992 }
2993
2994 nir_builder_instr_insert(&b->nb, &vec->instr);
2995
2996 return &vec->dest.dest.ssa;
2997 }
2998
2999 static nir_ssa_def *
3000 nir_ieq_imm(nir_builder *b, nir_ssa_def *x, uint64_t i)
3001 {
3002 return nir_ieq(b, x, nir_imm_intN_t(b, i, x->bit_size));
3003 }
3004
3005 nir_ssa_def *
3006 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
3007 nir_ssa_def *index)
3008 {
3009 nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
3010 for (unsigned i = 1; i < src->num_components; i++)
3011 dest = nir_bcsel(&b->nb, nir_ieq_imm(&b->nb, index, i),
3012 vtn_vector_extract(b, src, i), dest);
3013
3014 return dest;
3015 }
3016
3017 nir_ssa_def *
3018 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
3019 nir_ssa_def *insert, nir_ssa_def *index)
3020 {
3021 nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
3022 for (unsigned i = 1; i < src->num_components; i++)
3023 dest = nir_bcsel(&b->nb, nir_ieq_imm(&b->nb, index, i),
3024 vtn_vector_insert(b, src, insert, i), dest);
3025
3026 return dest;
3027 }
3028
3029 static nir_ssa_def *
3030 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
3031 nir_ssa_def *src0, nir_ssa_def *src1,
3032 const uint32_t *indices)
3033 {
3034 nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
3035
3036 for (unsigned i = 0; i < num_components; i++) {
3037 uint32_t index = indices[i];
3038 if (index == 0xffffffff) {
3039 vec->src[i].src =
3040 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
3041 } else if (index < src0->num_components) {
3042 vec->src[i].src = nir_src_for_ssa(src0);
3043 vec->src[i].swizzle[0] = index;
3044 } else {
3045 vec->src[i].src = nir_src_for_ssa(src1);
3046 vec->src[i].swizzle[0] = index - src0->num_components;
3047 }
3048 }
3049
3050 nir_builder_instr_insert(&b->nb, &vec->instr);
3051
3052 return &vec->dest.dest.ssa;
3053 }
3054
3055 /*
3056 * Concatentates a number of vectors/scalars together to produce a vector
3057 */
3058 static nir_ssa_def *
3059 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
3060 unsigned num_srcs, nir_ssa_def **srcs)
3061 {
3062 nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
3063
3064 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3065 *
3066 * "When constructing a vector, there must be at least two Constituent
3067 * operands."
3068 */
3069 vtn_assert(num_srcs >= 2);
3070
3071 unsigned dest_idx = 0;
3072 for (unsigned i = 0; i < num_srcs; i++) {
3073 nir_ssa_def *src = srcs[i];
3074 vtn_assert(dest_idx + src->num_components <= num_components);
3075 for (unsigned j = 0; j < src->num_components; j++) {
3076 vec->src[dest_idx].src = nir_src_for_ssa(src);
3077 vec->src[dest_idx].swizzle[0] = j;
3078 dest_idx++;
3079 }
3080 }
3081
3082 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3083 *
3084 * "When constructing a vector, the total number of components in all
3085 * the operands must equal the number of components in Result Type."
3086 */
3087 vtn_assert(dest_idx == num_components);
3088
3089 nir_builder_instr_insert(&b->nb, &vec->instr);
3090
3091 return &vec->dest.dest.ssa;
3092 }
3093
3094 static struct vtn_ssa_value *
3095 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
3096 {
3097 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
3098 dest->type = src->type;
3099
3100 if (glsl_type_is_vector_or_scalar(src->type)) {
3101 dest->def = src->def;
3102 } else {
3103 unsigned elems = glsl_get_length(src->type);
3104
3105 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
3106 for (unsigned i = 0; i < elems; i++)
3107 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
3108 }
3109
3110 return dest;
3111 }
3112
3113 static struct vtn_ssa_value *
3114 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
3115 struct vtn_ssa_value *insert, const uint32_t *indices,
3116 unsigned num_indices)
3117 {
3118 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
3119
3120 struct vtn_ssa_value *cur = dest;
3121 unsigned i;
3122 for (i = 0; i < num_indices - 1; i++) {
3123 cur = cur->elems[indices[i]];
3124 }
3125
3126 if (glsl_type_is_vector_or_scalar(cur->type)) {
3127 /* According to the SPIR-V spec, OpCompositeInsert may work down to
3128 * the component granularity. In that case, the last index will be
3129 * the index to insert the scalar into the vector.
3130 */
3131
3132 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
3133 } else {
3134 cur->elems[indices[i]] = insert;
3135 }
3136
3137 return dest;
3138 }
3139
3140 static struct vtn_ssa_value *
3141 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
3142 const uint32_t *indices, unsigned num_indices)
3143 {
3144 struct vtn_ssa_value *cur = src;
3145 for (unsigned i = 0; i < num_indices; i++) {
3146 if (glsl_type_is_vector_or_scalar(cur->type)) {
3147 vtn_assert(i == num_indices - 1);
3148 /* According to the SPIR-V spec, OpCompositeExtract may work down to
3149 * the component granularity. The last index will be the index of the
3150 * vector to extract.
3151 */
3152
3153 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
3154 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
3155 ret->def = vtn_vector_extract(b, cur->def, indices[i]);
3156 return ret;
3157 } else {
3158 cur = cur->elems[indices[i]];
3159 }
3160 }
3161
3162 return cur;
3163 }
3164
3165 static void
3166 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
3167 const uint32_t *w, unsigned count)
3168 {
3169 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
3170 const struct glsl_type *type =
3171 vtn_value(b, w[1], vtn_value_type_type)->type->type;
3172 val->ssa = vtn_create_ssa_value(b, type);
3173
3174 switch (opcode) {
3175 case SpvOpVectorExtractDynamic:
3176 val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
3177 vtn_ssa_value(b, w[4])->def);
3178 break;
3179
3180 case SpvOpVectorInsertDynamic:
3181 val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
3182 vtn_ssa_value(b, w[4])->def,
3183 vtn_ssa_value(b, w[5])->def);
3184 break;
3185
3186 case SpvOpVectorShuffle:
3187 val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
3188 vtn_ssa_value(b, w[3])->def,
3189 vtn_ssa_value(b, w[4])->def,
3190 w + 5);
3191 break;
3192
3193 case SpvOpCompositeConstruct: {
3194 unsigned elems = count - 3;
3195 assume(elems >= 1);
3196 if (glsl_type_is_vector_or_scalar(type)) {
3197 nir_ssa_def *srcs[NIR_MAX_VEC_COMPONENTS];
3198 for (unsigned i = 0; i < elems; i++)
3199 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
3200 val->ssa->def =
3201 vtn_vector_construct(b, glsl_get_vector_elements(type),
3202 elems, srcs);
3203 } else {
3204 val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
3205 for (unsigned i = 0; i < elems; i++)
3206 val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
3207 }
3208 break;
3209 }
3210 case SpvOpCompositeExtract:
3211 val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
3212 w + 4, count - 4);
3213 break;
3214
3215 case SpvOpCompositeInsert:
3216 val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
3217 vtn_ssa_value(b, w[3]),
3218 w + 5, count - 5);
3219 break;
3220
3221 case SpvOpCopyObject:
3222 val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
3223 break;
3224
3225 default:
3226 vtn_fail("unknown composite operation");
3227 }
3228 }
3229
3230 static void
3231 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
3232 {
3233 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
3234 nir_builder_instr_insert(&b->nb, &intrin->instr);
3235 }
3236
3237 static void
3238 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
3239 SpvMemorySemanticsMask semantics)
3240 {
3241 static const SpvMemorySemanticsMask all_memory_semantics =
3242 SpvMemorySemanticsUniformMemoryMask |
3243 SpvMemorySemanticsWorkgroupMemoryMask |
3244 SpvMemorySemanticsAtomicCounterMemoryMask |
3245 SpvMemorySemanticsImageMemoryMask;
3246
3247 /* If we're not actually doing a memory barrier, bail */
3248 if (!(semantics & all_memory_semantics))
3249 return;
3250
3251 /* GL and Vulkan don't have these */
3252 vtn_assert(scope != SpvScopeCrossDevice);
3253
3254 if (scope == SpvScopeSubgroup)
3255 return; /* Nothing to do here */
3256
3257 if (scope == SpvScopeWorkgroup) {
3258 vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
3259 return;
3260 }
3261
3262 /* There's only two scopes thing left */
3263 vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
3264
3265 if ((semantics & all_memory_semantics) == all_memory_semantics) {
3266 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3267 return;
3268 }
3269
3270 /* Issue a bunch of more specific barriers */
3271 uint32_t bits = semantics;
3272 while (bits) {
3273 SpvMemorySemanticsMask semantic = 1 << u_bit_scan(&bits);
3274 switch (semantic) {
3275 case SpvMemorySemanticsUniformMemoryMask:
3276 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3277 break;
3278 case SpvMemorySemanticsWorkgroupMemoryMask:
3279 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3280 break;
3281 case SpvMemorySemanticsAtomicCounterMemoryMask:
3282 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3283 break;
3284 case SpvMemorySemanticsImageMemoryMask:
3285 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3286 break;
3287 default:
3288 break;;
3289 }
3290 }
3291 }
3292
3293 static void
3294 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3295 const uint32_t *w, unsigned count)
3296 {
3297 switch (opcode) {
3298 case SpvOpEmitVertex:
3299 case SpvOpEmitStreamVertex:
3300 case SpvOpEndPrimitive:
3301 case SpvOpEndStreamPrimitive: {
3302 nir_intrinsic_op intrinsic_op;
3303 switch (opcode) {
3304 case SpvOpEmitVertex:
3305 case SpvOpEmitStreamVertex:
3306 intrinsic_op = nir_intrinsic_emit_vertex;
3307 break;
3308 case SpvOpEndPrimitive:
3309 case SpvOpEndStreamPrimitive:
3310 intrinsic_op = nir_intrinsic_end_primitive;
3311 break;
3312 default:
3313 unreachable("Invalid opcode");
3314 }
3315
3316 nir_intrinsic_instr *intrin =
3317 nir_intrinsic_instr_create(b->shader, intrinsic_op);
3318
3319 switch (opcode) {
3320 case SpvOpEmitStreamVertex:
3321 case SpvOpEndStreamPrimitive: {
3322 unsigned stream = vtn_constant_value(b, w[1])->values[0].u32[0];
3323 nir_intrinsic_set_stream_id(intrin, stream);
3324 break;
3325 }
3326
3327 default:
3328 break;
3329 }
3330
3331 nir_builder_instr_insert(&b->nb, &intrin->instr);
3332 break;
3333 }
3334
3335 case SpvOpMemoryBarrier: {
3336 SpvScope scope = vtn_constant_value(b, w[1])->values[0].u32[0];
3337 SpvMemorySemanticsMask semantics =
3338 vtn_constant_value(b, w[2])->values[0].u32[0];
3339 vtn_emit_memory_barrier(b, scope, semantics);
3340 return;
3341 }
3342
3343 case SpvOpControlBarrier: {
3344 SpvScope execution_scope =
3345 vtn_constant_value(b, w[1])->values[0].u32[0];
3346 if (execution_scope == SpvScopeWorkgroup)
3347 vtn_emit_barrier(b, nir_intrinsic_barrier);
3348
3349 SpvScope memory_scope =
3350 vtn_constant_value(b, w[2])->values[0].u32[0];
3351 SpvMemorySemanticsMask memory_semantics =
3352 vtn_constant_value(b, w[3])->values[0].u32[0];
3353 vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3354 break;
3355 }
3356
3357 default:
3358 unreachable("unknown barrier instruction");
3359 }
3360 }
3361
3362 static unsigned
3363 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
3364 SpvExecutionMode mode)
3365 {
3366 switch (mode) {
3367 case SpvExecutionModeInputPoints:
3368 case SpvExecutionModeOutputPoints:
3369 return 0; /* GL_POINTS */
3370 case SpvExecutionModeInputLines:
3371 return 1; /* GL_LINES */
3372 case SpvExecutionModeInputLinesAdjacency:
3373 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
3374 case SpvExecutionModeTriangles:
3375 return 4; /* GL_TRIANGLES */
3376 case SpvExecutionModeInputTrianglesAdjacency:
3377 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
3378 case SpvExecutionModeQuads:
3379 return 7; /* GL_QUADS */
3380 case SpvExecutionModeIsolines:
3381 return 0x8E7A; /* GL_ISOLINES */
3382 case SpvExecutionModeOutputLineStrip:
3383 return 3; /* GL_LINE_STRIP */
3384 case SpvExecutionModeOutputTriangleStrip:
3385 return 5; /* GL_TRIANGLE_STRIP */
3386 default:
3387 vtn_fail("Invalid primitive type");
3388 }
3389 }
3390
3391 static unsigned
3392 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
3393 SpvExecutionMode mode)
3394 {
3395 switch (mode) {
3396 case SpvExecutionModeInputPoints:
3397 return 1;
3398 case SpvExecutionModeInputLines:
3399 return 2;
3400 case SpvExecutionModeInputLinesAdjacency:
3401 return 4;
3402 case SpvExecutionModeTriangles:
3403 return 3;
3404 case SpvExecutionModeInputTrianglesAdjacency:
3405 return 6;
3406 default:
3407 vtn_fail("Invalid GS input mode");
3408 }
3409 }
3410
3411 static gl_shader_stage
3412 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
3413 {
3414 switch (model) {
3415 case SpvExecutionModelVertex:
3416 return MESA_SHADER_VERTEX;
3417 case SpvExecutionModelTessellationControl:
3418 return MESA_SHADER_TESS_CTRL;
3419 case SpvExecutionModelTessellationEvaluation:
3420 return MESA_SHADER_TESS_EVAL;
3421 case SpvExecutionModelGeometry:
3422 return MESA_SHADER_GEOMETRY;
3423 case SpvExecutionModelFragment:
3424 return MESA_SHADER_FRAGMENT;
3425 case SpvExecutionModelGLCompute:
3426 return MESA_SHADER_COMPUTE;
3427 case SpvExecutionModelKernel:
3428 return MESA_SHADER_KERNEL;
3429 default:
3430 vtn_fail("Unsupported execution model");
3431 }
3432 }
3433
3434 #define spv_check_supported(name, cap) do { \
3435 if (!(b->options && b->options->caps.name)) \
3436 vtn_warn("Unsupported SPIR-V capability: %s", \
3437 spirv_capability_to_string(cap)); \
3438 } while(0)
3439
3440
3441 void
3442 vtn_handle_entry_point(struct vtn_builder *b, const uint32_t *w,
3443 unsigned count)
3444 {
3445 struct vtn_value *entry_point = &b->values[w[2]];
3446 /* Let this be a name label regardless */
3447 unsigned name_words;
3448 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
3449
3450 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
3451 stage_for_execution_model(b, w[1]) != b->entry_point_stage)
3452 return;
3453
3454 vtn_assert(b->entry_point == NULL);
3455 b->entry_point = entry_point;
3456 }
3457
3458 static bool
3459 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
3460 const uint32_t *w, unsigned count)
3461 {
3462 switch (opcode) {
3463 case SpvOpSource: {
3464 const char *lang;
3465 switch (w[1]) {
3466 default:
3467 case SpvSourceLanguageUnknown: lang = "unknown"; break;
3468 case SpvSourceLanguageESSL: lang = "ESSL"; break;
3469 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
3470 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
3471 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
3472 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
3473 }
3474
3475 uint32_t version = w[2];
3476
3477 const char *file =
3478 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
3479
3480 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
3481 break;
3482 }
3483
3484 case SpvOpSourceExtension:
3485 case SpvOpSourceContinued:
3486 case SpvOpExtension:
3487 case SpvOpModuleProcessed:
3488 /* Unhandled, but these are for debug so that's ok. */
3489 break;
3490
3491 case SpvOpCapability: {
3492 SpvCapability cap = w[1];
3493 switch (cap) {
3494 case SpvCapabilityMatrix:
3495 case SpvCapabilityShader:
3496 case SpvCapabilityGeometry:
3497 case SpvCapabilityGeometryPointSize:
3498 case SpvCapabilityUniformBufferArrayDynamicIndexing:
3499 case SpvCapabilitySampledImageArrayDynamicIndexing:
3500 case SpvCapabilityStorageBufferArrayDynamicIndexing:
3501 case SpvCapabilityStorageImageArrayDynamicIndexing:
3502 case SpvCapabilityImageRect:
3503 case SpvCapabilitySampledRect:
3504 case SpvCapabilitySampled1D:
3505 case SpvCapabilityImage1D:
3506 case SpvCapabilitySampledCubeArray:
3507 case SpvCapabilityImageCubeArray:
3508 case SpvCapabilitySampledBuffer:
3509 case SpvCapabilityImageBuffer:
3510 case SpvCapabilityImageQuery:
3511 case SpvCapabilityDerivativeControl:
3512 case SpvCapabilityInterpolationFunction:
3513 case SpvCapabilityMultiViewport:
3514 case SpvCapabilitySampleRateShading:
3515 case SpvCapabilityClipDistance:
3516 case SpvCapabilityCullDistance:
3517 case SpvCapabilityInputAttachment:
3518 case SpvCapabilityImageGatherExtended:
3519 case SpvCapabilityStorageImageExtendedFormats:
3520 break;
3521
3522 case SpvCapabilityLinkage:
3523 case SpvCapabilityVector16:
3524 case SpvCapabilityFloat16Buffer:
3525 case SpvCapabilityFloat16:
3526 case SpvCapabilitySparseResidency:
3527 vtn_warn("Unsupported SPIR-V capability: %s",
3528 spirv_capability_to_string(cap));
3529 break;
3530
3531 case SpvCapabilityMinLod:
3532 spv_check_supported(min_lod, cap);
3533 break;
3534
3535 case SpvCapabilityAtomicStorage:
3536 spv_check_supported(atomic_storage, cap);
3537 break;
3538
3539 case SpvCapabilityFloat64:
3540 spv_check_supported(float64, cap);
3541 break;
3542 case SpvCapabilityInt64:
3543 spv_check_supported(int64, cap);
3544 break;
3545 case SpvCapabilityInt16:
3546 spv_check_supported(int16, cap);
3547 break;
3548
3549 case SpvCapabilityTransformFeedback:
3550 spv_check_supported(transform_feedback, cap);
3551 break;
3552
3553 case SpvCapabilityGeometryStreams:
3554 spv_check_supported(geometry_streams, cap);
3555 break;
3556
3557 case SpvCapabilityInt64Atomics:
3558 spv_check_supported(int64_atomics, cap);
3559
3560 case SpvCapabilityInt8:
3561 spv_check_supported(int8, cap);
3562 break;
3563
3564 case SpvCapabilityStorageImageMultisample:
3565 spv_check_supported(storage_image_ms, cap);
3566 break;
3567
3568 case SpvCapabilityAddresses:
3569 spv_check_supported(address, cap);
3570 break;
3571
3572 case SpvCapabilityKernel:
3573 spv_check_supported(kernel, cap);
3574 break;
3575
3576 case SpvCapabilityImageBasic:
3577 case SpvCapabilityImageReadWrite:
3578 case SpvCapabilityImageMipmap:
3579 case SpvCapabilityPipes:
3580 case SpvCapabilityGroups:
3581 case SpvCapabilityDeviceEnqueue:
3582 case SpvCapabilityLiteralSampler:
3583 case SpvCapabilityGenericPointer:
3584 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
3585 spirv_capability_to_string(cap));
3586 break;
3587
3588 case SpvCapabilityImageMSArray:
3589 spv_check_supported(image_ms_array, cap);
3590 break;
3591
3592 case SpvCapabilityTessellation:
3593 case SpvCapabilityTessellationPointSize:
3594 spv_check_supported(tessellation, cap);
3595 break;
3596
3597 case SpvCapabilityDrawParameters:
3598 spv_check_supported(draw_parameters, cap);
3599 break;
3600
3601 case SpvCapabilityStorageImageReadWithoutFormat:
3602 spv_check_supported(image_read_without_format, cap);
3603 break;
3604
3605 case SpvCapabilityStorageImageWriteWithoutFormat:
3606 spv_check_supported(image_write_without_format, cap);
3607 break;
3608
3609 case SpvCapabilityDeviceGroup:
3610 spv_check_supported(device_group, cap);
3611 break;
3612
3613 case SpvCapabilityMultiView:
3614 spv_check_supported(multiview, cap);
3615 break;
3616
3617 case SpvCapabilityGroupNonUniform:
3618 spv_check_supported(subgroup_basic, cap);
3619 break;
3620
3621 case SpvCapabilityGroupNonUniformVote:
3622 spv_check_supported(subgroup_vote, cap);
3623 break;
3624
3625 case SpvCapabilitySubgroupBallotKHR:
3626 case SpvCapabilityGroupNonUniformBallot:
3627 spv_check_supported(subgroup_ballot, cap);
3628 break;
3629
3630 case SpvCapabilityGroupNonUniformShuffle:
3631 case SpvCapabilityGroupNonUniformShuffleRelative:
3632 spv_check_supported(subgroup_shuffle, cap);
3633 break;
3634
3635 case SpvCapabilityGroupNonUniformQuad:
3636 spv_check_supported(subgroup_quad, cap);
3637 break;
3638
3639 case SpvCapabilityGroupNonUniformArithmetic:
3640 case SpvCapabilityGroupNonUniformClustered:
3641 spv_check_supported(subgroup_arithmetic, cap);
3642 break;
3643
3644 case SpvCapabilityVariablePointersStorageBuffer:
3645 case SpvCapabilityVariablePointers:
3646 spv_check_supported(variable_pointers, cap);
3647 b->variable_pointers = true;
3648 break;
3649
3650 case SpvCapabilityStorageUniformBufferBlock16:
3651 case SpvCapabilityStorageUniform16:
3652 case SpvCapabilityStoragePushConstant16:
3653 case SpvCapabilityStorageInputOutput16:
3654 spv_check_supported(storage_16bit, cap);
3655 break;
3656
3657 case SpvCapabilityShaderViewportIndexLayerEXT:
3658 spv_check_supported(shader_viewport_index_layer, cap);
3659 break;
3660
3661 case SpvCapabilityStorageBuffer8BitAccess:
3662 case SpvCapabilityUniformAndStorageBuffer8BitAccess:
3663 case SpvCapabilityStoragePushConstant8:
3664 spv_check_supported(storage_8bit, cap);
3665 break;
3666
3667 case SpvCapabilityInputAttachmentArrayDynamicIndexingEXT:
3668 case SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT:
3669 case SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT:
3670 spv_check_supported(descriptor_array_dynamic_indexing, cap);
3671 break;
3672
3673 case SpvCapabilityRuntimeDescriptorArrayEXT:
3674 spv_check_supported(runtime_descriptor_array, cap);
3675 break;
3676
3677 case SpvCapabilityStencilExportEXT:
3678 spv_check_supported(stencil_export, cap);
3679 break;
3680
3681 case SpvCapabilitySampleMaskPostDepthCoverage:
3682 spv_check_supported(post_depth_coverage, cap);
3683 break;
3684
3685 default:
3686 vtn_fail("Unhandled capability");
3687 }
3688 break;
3689 }
3690
3691 case SpvOpExtInstImport:
3692 vtn_handle_extension(b, opcode, w, count);
3693 break;
3694
3695 case SpvOpMemoryModel:
3696 vtn_assert(w[1] == SpvAddressingModelLogical);
3697 vtn_assert(w[2] == SpvMemoryModelSimple ||
3698 w[2] == SpvMemoryModelGLSL450);
3699 break;
3700
3701 case SpvOpEntryPoint:
3702 vtn_handle_entry_point(b, w, count);
3703 break;
3704
3705 case SpvOpString:
3706 vtn_push_value(b, w[1], vtn_value_type_string)->str =
3707 vtn_string_literal(b, &w[2], count - 2, NULL);
3708 break;
3709
3710 case SpvOpName:
3711 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
3712 break;
3713
3714 case SpvOpMemberName:
3715 /* TODO */
3716 break;
3717
3718 case SpvOpExecutionMode:
3719 case SpvOpDecorationGroup:
3720 case SpvOpDecorate:
3721 case SpvOpMemberDecorate:
3722 case SpvOpGroupDecorate:
3723 case SpvOpGroupMemberDecorate:
3724 case SpvOpDecorateStringGOOGLE:
3725 case SpvOpMemberDecorateStringGOOGLE:
3726 vtn_handle_decoration(b, opcode, w, count);
3727 break;
3728
3729 default:
3730 return false; /* End of preamble */
3731 }
3732
3733 return true;
3734 }
3735
3736 static void
3737 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
3738 const struct vtn_decoration *mode, void *data)
3739 {
3740 vtn_assert(b->entry_point == entry_point);
3741
3742 switch(mode->exec_mode) {
3743 case SpvExecutionModeOriginUpperLeft:
3744 case SpvExecutionModeOriginLowerLeft:
3745 b->origin_upper_left =
3746 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
3747 break;
3748
3749 case SpvExecutionModeEarlyFragmentTests:
3750 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3751 b->shader->info.fs.early_fragment_tests = true;
3752 break;
3753
3754 case SpvExecutionModePostDepthCoverage:
3755 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3756 b->shader->info.fs.post_depth_coverage = true;
3757 break;
3758
3759 case SpvExecutionModeInvocations:
3760 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3761 b->shader->info.gs.invocations = MAX2(1, mode->literals[0]);
3762 break;
3763
3764 case SpvExecutionModeDepthReplacing:
3765 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3766 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
3767 break;
3768 case SpvExecutionModeDepthGreater:
3769 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3770 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
3771 break;
3772 case SpvExecutionModeDepthLess:
3773 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3774 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
3775 break;
3776 case SpvExecutionModeDepthUnchanged:
3777 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3778 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3779 break;
3780
3781 case SpvExecutionModeLocalSize:
3782 vtn_assert(gl_shader_stage_is_compute(b->shader->info.stage));
3783 b->shader->info.cs.local_size[0] = mode->literals[0];
3784 b->shader->info.cs.local_size[1] = mode->literals[1];
3785 b->shader->info.cs.local_size[2] = mode->literals[2];
3786 break;
3787 case SpvExecutionModeLocalSizeHint:
3788 break; /* Nothing to do with this */
3789
3790 case SpvExecutionModeOutputVertices:
3791 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3792 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3793 b->shader->info.tess.tcs_vertices_out = mode->literals[0];
3794 } else {
3795 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3796 b->shader->info.gs.vertices_out = mode->literals[0];
3797 }
3798 break;
3799
3800 case SpvExecutionModeInputPoints:
3801 case SpvExecutionModeInputLines:
3802 case SpvExecutionModeInputLinesAdjacency:
3803 case SpvExecutionModeTriangles:
3804 case SpvExecutionModeInputTrianglesAdjacency:
3805 case SpvExecutionModeQuads:
3806 case SpvExecutionModeIsolines:
3807 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3808 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3809 b->shader->info.tess.primitive_mode =
3810 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3811 } else {
3812 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3813 b->shader->info.gs.vertices_in =
3814 vertices_in_from_spv_execution_mode(b, mode->exec_mode);
3815 b->shader->info.gs.input_primitive =
3816 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3817 }
3818 break;
3819
3820 case SpvExecutionModeOutputPoints:
3821 case SpvExecutionModeOutputLineStrip:
3822 case SpvExecutionModeOutputTriangleStrip:
3823 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3824 b->shader->info.gs.output_primitive =
3825 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3826 break;
3827
3828 case SpvExecutionModeSpacingEqual:
3829 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3830 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3831 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
3832 break;
3833 case SpvExecutionModeSpacingFractionalEven:
3834 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3835 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3836 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
3837 break;
3838 case SpvExecutionModeSpacingFractionalOdd:
3839 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3840 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3841 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
3842 break;
3843 case SpvExecutionModeVertexOrderCw:
3844 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3845 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3846 b->shader->info.tess.ccw = false;
3847 break;
3848 case SpvExecutionModeVertexOrderCcw:
3849 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3850 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3851 b->shader->info.tess.ccw = true;
3852 break;
3853 case SpvExecutionModePointMode:
3854 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3855 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3856 b->shader->info.tess.point_mode = true;
3857 break;
3858
3859 case SpvExecutionModePixelCenterInteger:
3860 b->pixel_center_integer = true;
3861 break;
3862
3863 case SpvExecutionModeXfb:
3864 b->shader->info.has_transform_feedback_varyings = true;
3865 break;
3866
3867 case SpvExecutionModeVecTypeHint:
3868 break; /* OpenCL */
3869
3870 case SpvExecutionModeContractionOff:
3871 if (b->shader->info.stage != MESA_SHADER_KERNEL)
3872 vtn_warn("ExectionMode only allowed for CL-style kernels: %s",
3873 spirv_executionmode_to_string(mode->exec_mode));
3874 else
3875 b->exact = true;
3876 break;
3877
3878 case SpvExecutionModeStencilRefReplacingEXT:
3879 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3880 break;
3881
3882 default:
3883 vtn_fail("Unhandled execution mode");
3884 }
3885 }
3886
3887 static bool
3888 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
3889 const uint32_t *w, unsigned count)
3890 {
3891 vtn_set_instruction_result_type(b, opcode, w, count);
3892
3893 switch (opcode) {
3894 case SpvOpSource:
3895 case SpvOpSourceContinued:
3896 case SpvOpSourceExtension:
3897 case SpvOpExtension:
3898 case SpvOpCapability:
3899 case SpvOpExtInstImport:
3900 case SpvOpMemoryModel:
3901 case SpvOpEntryPoint:
3902 case SpvOpExecutionMode:
3903 case SpvOpString:
3904 case SpvOpName:
3905 case SpvOpMemberName:
3906 case SpvOpDecorationGroup:
3907 case SpvOpDecorate:
3908 case SpvOpMemberDecorate:
3909 case SpvOpGroupDecorate:
3910 case SpvOpGroupMemberDecorate:
3911 case SpvOpDecorateStringGOOGLE:
3912 case SpvOpMemberDecorateStringGOOGLE:
3913 vtn_fail("Invalid opcode types and variables section");
3914 break;
3915
3916 case SpvOpTypeVoid:
3917 case SpvOpTypeBool:
3918 case SpvOpTypeInt:
3919 case SpvOpTypeFloat:
3920 case SpvOpTypeVector:
3921 case SpvOpTypeMatrix:
3922 case SpvOpTypeImage:
3923 case SpvOpTypeSampler:
3924 case SpvOpTypeSampledImage:
3925 case SpvOpTypeArray:
3926 case SpvOpTypeRuntimeArray:
3927 case SpvOpTypeStruct:
3928 case SpvOpTypeOpaque:
3929 case SpvOpTypePointer:
3930 case SpvOpTypeFunction:
3931 case SpvOpTypeEvent:
3932 case SpvOpTypeDeviceEvent:
3933 case SpvOpTypeReserveId:
3934 case SpvOpTypeQueue:
3935 case SpvOpTypePipe:
3936 vtn_handle_type(b, opcode, w, count);
3937 break;
3938
3939 case SpvOpConstantTrue:
3940 case SpvOpConstantFalse:
3941 case SpvOpConstant:
3942 case SpvOpConstantComposite:
3943 case SpvOpConstantSampler:
3944 case SpvOpConstantNull:
3945 case SpvOpSpecConstantTrue:
3946 case SpvOpSpecConstantFalse:
3947 case SpvOpSpecConstant:
3948 case SpvOpSpecConstantComposite:
3949 case SpvOpSpecConstantOp:
3950 vtn_handle_constant(b, opcode, w, count);
3951 break;
3952
3953 case SpvOpUndef:
3954 case SpvOpVariable:
3955 vtn_handle_variables(b, opcode, w, count);
3956 break;
3957
3958 default:
3959 return false; /* End of preamble */
3960 }
3961
3962 return true;
3963 }
3964
3965 static bool
3966 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
3967 const uint32_t *w, unsigned count)
3968 {
3969 switch (opcode) {
3970 case SpvOpLabel:
3971 break;
3972
3973 case SpvOpLoopMerge:
3974 case SpvOpSelectionMerge:
3975 /* This is handled by cfg pre-pass and walk_blocks */
3976 break;
3977
3978 case SpvOpUndef: {
3979 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
3980 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
3981 break;
3982 }
3983
3984 case SpvOpExtInst:
3985 vtn_handle_extension(b, opcode, w, count);
3986 break;
3987
3988 case SpvOpVariable:
3989 case SpvOpLoad:
3990 case SpvOpStore:
3991 case SpvOpCopyMemory:
3992 case SpvOpCopyMemorySized:
3993 case SpvOpAccessChain:
3994 case SpvOpPtrAccessChain:
3995 case SpvOpInBoundsAccessChain:
3996 case SpvOpArrayLength:
3997 vtn_handle_variables(b, opcode, w, count);
3998 break;
3999
4000 case SpvOpFunctionCall:
4001 vtn_handle_function_call(b, opcode, w, count);
4002 break;
4003
4004 case SpvOpSampledImage:
4005 case SpvOpImage:
4006 case SpvOpImageSampleImplicitLod:
4007 case SpvOpImageSampleExplicitLod:
4008 case SpvOpImageSampleDrefImplicitLod:
4009 case SpvOpImageSampleDrefExplicitLod:
4010 case SpvOpImageSampleProjImplicitLod:
4011 case SpvOpImageSampleProjExplicitLod:
4012 case SpvOpImageSampleProjDrefImplicitLod:
4013 case SpvOpImageSampleProjDrefExplicitLod:
4014 case SpvOpImageFetch:
4015 case SpvOpImageGather:
4016 case SpvOpImageDrefGather:
4017 case SpvOpImageQuerySizeLod:
4018 case SpvOpImageQueryLod:
4019 case SpvOpImageQueryLevels:
4020 case SpvOpImageQuerySamples:
4021 vtn_handle_texture(b, opcode, w, count);
4022 break;
4023
4024 case SpvOpImageRead:
4025 case SpvOpImageWrite:
4026 case SpvOpImageTexelPointer:
4027 vtn_handle_image(b, opcode, w, count);
4028 break;
4029
4030 case SpvOpImageQuerySize: {
4031 struct vtn_pointer *image =
4032 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
4033 if (glsl_type_is_image(image->type->type)) {
4034 vtn_handle_image(b, opcode, w, count);
4035 } else {
4036 vtn_assert(glsl_type_is_sampler(image->type->type));
4037 vtn_handle_texture(b, opcode, w, count);
4038 }
4039 break;
4040 }
4041
4042 case SpvOpAtomicLoad:
4043 case SpvOpAtomicExchange:
4044 case SpvOpAtomicCompareExchange:
4045 case SpvOpAtomicCompareExchangeWeak:
4046 case SpvOpAtomicIIncrement:
4047 case SpvOpAtomicIDecrement:
4048 case SpvOpAtomicIAdd:
4049 case SpvOpAtomicISub:
4050 case SpvOpAtomicSMin:
4051 case SpvOpAtomicUMin:
4052 case SpvOpAtomicSMax:
4053 case SpvOpAtomicUMax:
4054 case SpvOpAtomicAnd:
4055 case SpvOpAtomicOr:
4056 case SpvOpAtomicXor: {
4057 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
4058 if (pointer->value_type == vtn_value_type_image_pointer) {
4059 vtn_handle_image(b, opcode, w, count);
4060 } else {
4061 vtn_assert(pointer->value_type == vtn_value_type_pointer);
4062 vtn_handle_atomics(b, opcode, w, count);
4063 }
4064 break;
4065 }
4066
4067 case SpvOpAtomicStore: {
4068 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
4069 if (pointer->value_type == vtn_value_type_image_pointer) {
4070 vtn_handle_image(b, opcode, w, count);
4071 } else {
4072 vtn_assert(pointer->value_type == vtn_value_type_pointer);
4073 vtn_handle_atomics(b, opcode, w, count);
4074 }
4075 break;
4076 }
4077
4078 case SpvOpSelect: {
4079 /* Handle OpSelect up-front here because it needs to be able to handle
4080 * pointers and not just regular vectors and scalars.
4081 */
4082 struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
4083 struct vtn_value *sel_val = vtn_untyped_value(b, w[3]);
4084 struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
4085 struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
4086
4087 const struct glsl_type *sel_type;
4088 switch (res_val->type->base_type) {
4089 case vtn_base_type_scalar:
4090 sel_type = glsl_bool_type();
4091 break;
4092 case vtn_base_type_vector:
4093 sel_type = glsl_vector_type(GLSL_TYPE_BOOL, res_val->type->length);
4094 break;
4095 case vtn_base_type_pointer:
4096 /* We need to have actual storage for pointer types */
4097 vtn_fail_if(res_val->type->type == NULL,
4098 "Invalid pointer result type for OpSelect");
4099 sel_type = glsl_bool_type();
4100 break;
4101 default:
4102 vtn_fail("Result type of OpSelect must be a scalar, vector, or pointer");
4103 }
4104
4105 if (unlikely(sel_val->type->type != sel_type)) {
4106 if (sel_val->type->type == glsl_bool_type()) {
4107 /* This case is illegal but some older versions of GLSLang produce
4108 * it. The GLSLang issue was fixed on March 30, 2017:
4109 *
4110 * https://github.com/KhronosGroup/glslang/issues/809
4111 *
4112 * Unfortunately, there are applications in the wild which are
4113 * shipping with this bug so it isn't nice to fail on them so we
4114 * throw a warning instead. It's not actually a problem for us as
4115 * nir_builder will just splat the condition out which is most
4116 * likely what the client wanted anyway.
4117 */
4118 vtn_warn("Condition type of OpSelect must have the same number "
4119 "of components as Result Type");
4120 } else {
4121 vtn_fail("Condition type of OpSelect must be a scalar or vector "
4122 "of Boolean type. It must have the same number of "
4123 "components as Result Type");
4124 }
4125 }
4126
4127 vtn_fail_if(obj1_val->type != res_val->type ||
4128 obj2_val->type != res_val->type,
4129 "Object types must match the result type in OpSelect");
4130
4131 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
4132 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, res_type->type);
4133 ssa->def = nir_bcsel(&b->nb, vtn_ssa_value(b, w[3])->def,
4134 vtn_ssa_value(b, w[4])->def,
4135 vtn_ssa_value(b, w[5])->def);
4136 vtn_push_ssa(b, w[2], res_type, ssa);
4137 break;
4138 }
4139
4140 case SpvOpSNegate:
4141 case SpvOpFNegate:
4142 case SpvOpNot:
4143 case SpvOpAny:
4144 case SpvOpAll:
4145 case SpvOpConvertFToU:
4146 case SpvOpConvertFToS:
4147 case SpvOpConvertSToF:
4148 case SpvOpConvertUToF:
4149 case SpvOpUConvert:
4150 case SpvOpSConvert:
4151 case SpvOpFConvert:
4152 case SpvOpQuantizeToF16:
4153 case SpvOpConvertPtrToU:
4154 case SpvOpConvertUToPtr:
4155 case SpvOpPtrCastToGeneric:
4156 case SpvOpGenericCastToPtr:
4157 case SpvOpBitcast:
4158 case SpvOpIsNan:
4159 case SpvOpIsInf:
4160 case SpvOpIsFinite:
4161 case SpvOpIsNormal:
4162 case SpvOpSignBitSet:
4163 case SpvOpLessOrGreater:
4164 case SpvOpOrdered:
4165 case SpvOpUnordered:
4166 case SpvOpIAdd:
4167 case SpvOpFAdd:
4168 case SpvOpISub:
4169 case SpvOpFSub:
4170 case SpvOpIMul:
4171 case SpvOpFMul:
4172 case SpvOpUDiv:
4173 case SpvOpSDiv:
4174 case SpvOpFDiv:
4175 case SpvOpUMod:
4176 case SpvOpSRem:
4177 case SpvOpSMod:
4178 case SpvOpFRem:
4179 case SpvOpFMod:
4180 case SpvOpVectorTimesScalar:
4181 case SpvOpDot:
4182 case SpvOpIAddCarry:
4183 case SpvOpISubBorrow:
4184 case SpvOpUMulExtended:
4185 case SpvOpSMulExtended:
4186 case SpvOpShiftRightLogical:
4187 case SpvOpShiftRightArithmetic:
4188 case SpvOpShiftLeftLogical:
4189 case SpvOpLogicalEqual:
4190 case SpvOpLogicalNotEqual:
4191 case SpvOpLogicalOr:
4192 case SpvOpLogicalAnd:
4193 case SpvOpLogicalNot:
4194 case SpvOpBitwiseOr:
4195 case SpvOpBitwiseXor:
4196 case SpvOpBitwiseAnd:
4197 case SpvOpIEqual:
4198 case SpvOpFOrdEqual:
4199 case SpvOpFUnordEqual:
4200 case SpvOpINotEqual:
4201 case SpvOpFOrdNotEqual:
4202 case SpvOpFUnordNotEqual:
4203 case SpvOpULessThan:
4204 case SpvOpSLessThan:
4205 case SpvOpFOrdLessThan:
4206 case SpvOpFUnordLessThan:
4207 case SpvOpUGreaterThan:
4208 case SpvOpSGreaterThan:
4209 case SpvOpFOrdGreaterThan:
4210 case SpvOpFUnordGreaterThan:
4211 case SpvOpULessThanEqual:
4212 case SpvOpSLessThanEqual:
4213 case SpvOpFOrdLessThanEqual:
4214 case SpvOpFUnordLessThanEqual:
4215 case SpvOpUGreaterThanEqual:
4216 case SpvOpSGreaterThanEqual:
4217 case SpvOpFOrdGreaterThanEqual:
4218 case SpvOpFUnordGreaterThanEqual:
4219 case SpvOpDPdx:
4220 case SpvOpDPdy:
4221 case SpvOpFwidth:
4222 case SpvOpDPdxFine:
4223 case SpvOpDPdyFine:
4224 case SpvOpFwidthFine:
4225 case SpvOpDPdxCoarse:
4226 case SpvOpDPdyCoarse:
4227 case SpvOpFwidthCoarse:
4228 case SpvOpBitFieldInsert:
4229 case SpvOpBitFieldSExtract:
4230 case SpvOpBitFieldUExtract:
4231 case SpvOpBitReverse:
4232 case SpvOpBitCount:
4233 case SpvOpTranspose:
4234 case SpvOpOuterProduct:
4235 case SpvOpMatrixTimesScalar:
4236 case SpvOpVectorTimesMatrix:
4237 case SpvOpMatrixTimesVector:
4238 case SpvOpMatrixTimesMatrix:
4239 vtn_handle_alu(b, opcode, w, count);
4240 break;
4241
4242 case SpvOpVectorExtractDynamic:
4243 case SpvOpVectorInsertDynamic:
4244 case SpvOpVectorShuffle:
4245 case SpvOpCompositeConstruct:
4246 case SpvOpCompositeExtract:
4247 case SpvOpCompositeInsert:
4248 case SpvOpCopyObject:
4249 vtn_handle_composite(b, opcode, w, count);
4250 break;
4251
4252 case SpvOpEmitVertex:
4253 case SpvOpEndPrimitive:
4254 case SpvOpEmitStreamVertex:
4255 case SpvOpEndStreamPrimitive:
4256 case SpvOpControlBarrier:
4257 case SpvOpMemoryBarrier:
4258 vtn_handle_barrier(b, opcode, w, count);
4259 break;
4260
4261 case SpvOpGroupNonUniformElect:
4262 case SpvOpGroupNonUniformAll:
4263 case SpvOpGroupNonUniformAny:
4264 case SpvOpGroupNonUniformAllEqual:
4265 case SpvOpGroupNonUniformBroadcast:
4266 case SpvOpGroupNonUniformBroadcastFirst:
4267 case SpvOpGroupNonUniformBallot:
4268 case SpvOpGroupNonUniformInverseBallot:
4269 case SpvOpGroupNonUniformBallotBitExtract:
4270 case SpvOpGroupNonUniformBallotBitCount:
4271 case SpvOpGroupNonUniformBallotFindLSB:
4272 case SpvOpGroupNonUniformBallotFindMSB:
4273 case SpvOpGroupNonUniformShuffle:
4274 case SpvOpGroupNonUniformShuffleXor:
4275 case SpvOpGroupNonUniformShuffleUp:
4276 case SpvOpGroupNonUniformShuffleDown:
4277 case SpvOpGroupNonUniformIAdd:
4278 case SpvOpGroupNonUniformFAdd:
4279 case SpvOpGroupNonUniformIMul:
4280 case SpvOpGroupNonUniformFMul:
4281 case SpvOpGroupNonUniformSMin:
4282 case SpvOpGroupNonUniformUMin:
4283 case SpvOpGroupNonUniformFMin:
4284 case SpvOpGroupNonUniformSMax:
4285 case SpvOpGroupNonUniformUMax:
4286 case SpvOpGroupNonUniformFMax:
4287 case SpvOpGroupNonUniformBitwiseAnd:
4288 case SpvOpGroupNonUniformBitwiseOr:
4289 case SpvOpGroupNonUniformBitwiseXor:
4290 case SpvOpGroupNonUniformLogicalAnd:
4291 case SpvOpGroupNonUniformLogicalOr:
4292 case SpvOpGroupNonUniformLogicalXor:
4293 case SpvOpGroupNonUniformQuadBroadcast:
4294 case SpvOpGroupNonUniformQuadSwap:
4295 vtn_handle_subgroup(b, opcode, w, count);
4296 break;
4297
4298 default:
4299 vtn_fail("Unhandled opcode");
4300 }
4301
4302 return true;
4303 }
4304
4305 struct vtn_builder*
4306 vtn_create_builder(const uint32_t *words, size_t word_count,
4307 gl_shader_stage stage, const char *entry_point_name,
4308 const struct spirv_to_nir_options *options)
4309 {
4310 /* Initialize the vtn_builder object */
4311 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
4312 b->spirv = words;
4313 b->spirv_word_count = word_count;
4314 b->file = NULL;
4315 b->line = -1;
4316 b->col = -1;
4317 exec_list_make_empty(&b->functions);
4318 b->entry_point_stage = stage;
4319 b->entry_point_name = entry_point_name;
4320 b->options = options;
4321
4322 /*
4323 * Handle the SPIR-V header (first 5 dwords).
4324 * Can't use vtx_assert() as the setjmp(3) target isn't initialized yet.
4325 */
4326 if (word_count <= 5)
4327 goto fail;
4328
4329 if (words[0] != SpvMagicNumber) {
4330 vtn_err("words[0] was 0x%x, want 0x%x", words[0], SpvMagicNumber);
4331 goto fail;
4332 }
4333 if (words[1] < 0x10000) {
4334 vtn_err("words[1] was 0x%x, want >= 0x10000", words[1]);
4335 goto fail;
4336 }
4337
4338 uint16_t generator_id = words[2] >> 16;
4339 uint16_t generator_version = words[2];
4340
4341 /* The first GLSLang version bump actually 1.5 years after #179 was fixed
4342 * but this should at least let us shut the workaround off for modern
4343 * versions of GLSLang.
4344 */
4345 b->wa_glslang_179 = (generator_id == 8 && generator_version == 1);
4346
4347 /* words[2] == generator magic */
4348 unsigned value_id_bound = words[3];
4349 if (words[4] != 0) {
4350 vtn_err("words[4] was %u, want 0", words[4]);
4351 goto fail;
4352 }
4353
4354 b->value_id_bound = value_id_bound;
4355 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
4356
4357 return b;
4358 fail:
4359 ralloc_free(b);
4360 return NULL;
4361 }
4362
4363 nir_function *
4364 spirv_to_nir(const uint32_t *words, size_t word_count,
4365 struct nir_spirv_specialization *spec, unsigned num_spec,
4366 gl_shader_stage stage, const char *entry_point_name,
4367 const struct spirv_to_nir_options *options,
4368 const nir_shader_compiler_options *nir_options)
4369
4370 {
4371 const uint32_t *word_end = words + word_count;
4372
4373 struct vtn_builder *b = vtn_create_builder(words, word_count,
4374 stage, entry_point_name,
4375 options);
4376
4377 if (b == NULL)
4378 return NULL;
4379
4380 /* See also _vtn_fail() */
4381 if (setjmp(b->fail_jump)) {
4382 ralloc_free(b);
4383 return NULL;
4384 }
4385
4386 /* Skip the SPIR-V header, handled at vtn_create_builder */
4387 words+= 5;
4388
4389 /* Handle all the preamble instructions */
4390 words = vtn_foreach_instruction(b, words, word_end,
4391 vtn_handle_preamble_instruction);
4392
4393 if (b->entry_point == NULL) {
4394 vtn_fail("Entry point not found");
4395 ralloc_free(b);
4396 return NULL;
4397 }
4398
4399 b->shader = nir_shader_create(b, stage, nir_options, NULL);
4400
4401 /* Set shader info defaults */
4402 b->shader->info.gs.invocations = 1;
4403
4404 /* Parse execution modes */
4405 vtn_foreach_execution_mode(b, b->entry_point,
4406 vtn_handle_execution_mode, NULL);
4407
4408 b->specializations = spec;
4409 b->num_specializations = num_spec;
4410
4411 /* Handle all variable, type, and constant instructions */
4412 words = vtn_foreach_instruction(b, words, word_end,
4413 vtn_handle_variable_or_type_instruction);
4414
4415 /* Set types on all vtn_values */
4416 vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
4417
4418 vtn_build_cfg(b, words, word_end);
4419
4420 assert(b->entry_point->value_type == vtn_value_type_function);
4421 b->entry_point->func->referenced = true;
4422
4423 bool progress;
4424 do {
4425 progress = false;
4426 foreach_list_typed(struct vtn_function, func, node, &b->functions) {
4427 if (func->referenced && !func->emitted) {
4428 b->const_table = _mesa_pointer_hash_table_create(b);
4429
4430 vtn_function_emit(b, func, vtn_handle_body_instruction);
4431 progress = true;
4432 }
4433 }
4434 } while (progress);
4435
4436 /* We sometimes generate bogus derefs that, while never used, give the
4437 * validator a bit of heartburn. Run dead code to get rid of them.
4438 */
4439 nir_opt_dce(b->shader);
4440
4441 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
4442 nir_function *entry_point = b->entry_point->func->impl->function;
4443 vtn_assert(entry_point);
4444
4445 /* Unparent the shader from the vtn_builder before we delete the builder */
4446 ralloc_steal(NULL, b->shader);
4447
4448 ralloc_free(b);
4449
4450 entry_point->is_entrypoint = true;
4451 return entry_point;
4452 }