spirv: Call nir_builder directly for vector_extract
[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 "util/format/u_format.h"
36 #include "util/u_math.h"
37
38 #include <stdio.h>
39
40 void
41 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
42 size_t spirv_offset, const char *message)
43 {
44 if (b->options->debug.func) {
45 b->options->debug.func(b->options->debug.private_data,
46 level, spirv_offset, message);
47 }
48
49 #ifndef NDEBUG
50 if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
51 fprintf(stderr, "%s\n", message);
52 #endif
53 }
54
55 void
56 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
57 size_t spirv_offset, const char *fmt, ...)
58 {
59 va_list args;
60 char *msg;
61
62 va_start(args, fmt);
63 msg = ralloc_vasprintf(NULL, fmt, args);
64 va_end(args);
65
66 vtn_log(b, level, spirv_offset, msg);
67
68 ralloc_free(msg);
69 }
70
71 static void
72 vtn_log_err(struct vtn_builder *b,
73 enum nir_spirv_debug_level level, const char *prefix,
74 const char *file, unsigned line,
75 const char *fmt, va_list args)
76 {
77 char *msg;
78
79 msg = ralloc_strdup(NULL, prefix);
80
81 #ifndef NDEBUG
82 ralloc_asprintf_append(&msg, " In file %s:%u\n", file, line);
83 #endif
84
85 ralloc_asprintf_append(&msg, " ");
86
87 ralloc_vasprintf_append(&msg, fmt, args);
88
89 ralloc_asprintf_append(&msg, "\n %zu bytes into the SPIR-V binary",
90 b->spirv_offset);
91
92 if (b->file) {
93 ralloc_asprintf_append(&msg,
94 "\n in SPIR-V source file %s, line %d, col %d",
95 b->file, b->line, b->col);
96 }
97
98 vtn_log(b, level, b->spirv_offset, msg);
99
100 ralloc_free(msg);
101 }
102
103 static void
104 vtn_dump_shader(struct vtn_builder *b, const char *path, const char *prefix)
105 {
106 static int idx = 0;
107
108 char filename[1024];
109 int len = snprintf(filename, sizeof(filename), "%s/%s-%d.spirv",
110 path, prefix, idx++);
111 if (len < 0 || len >= sizeof(filename))
112 return;
113
114 FILE *f = fopen(filename, "w");
115 if (f == NULL)
116 return;
117
118 fwrite(b->spirv, sizeof(*b->spirv), b->spirv_word_count, f);
119 fclose(f);
120
121 vtn_info("SPIR-V shader dumped to %s", filename);
122 }
123
124 void
125 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
126 const char *fmt, ...)
127 {
128 va_list args;
129
130 va_start(args, fmt);
131 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
132 file, line, fmt, args);
133 va_end(args);
134 }
135
136 void
137 _vtn_err(struct vtn_builder *b, const char *file, unsigned line,
138 const char *fmt, ...)
139 {
140 va_list args;
141
142 va_start(args, fmt);
143 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V ERROR:\n",
144 file, line, fmt, args);
145 va_end(args);
146 }
147
148 void
149 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
150 const char *fmt, ...)
151 {
152 va_list args;
153
154 va_start(args, fmt);
155 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
156 file, line, fmt, args);
157 va_end(args);
158
159 const char *dump_path = getenv("MESA_SPIRV_FAIL_DUMP_PATH");
160 if (dump_path)
161 vtn_dump_shader(b, dump_path, "fail");
162
163 longjmp(b->fail_jump, 1);
164 }
165
166 struct spec_constant_value {
167 bool is_double;
168 union {
169 uint32_t data32;
170 uint64_t data64;
171 };
172 };
173
174 static struct vtn_ssa_value *
175 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
176 {
177 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
178 val->type = type;
179
180 if (glsl_type_is_vector_or_scalar(type)) {
181 unsigned num_components = glsl_get_vector_elements(val->type);
182 unsigned bit_size = glsl_get_bit_size(val->type);
183 val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
184 } else {
185 unsigned elems = glsl_get_length(val->type);
186 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
187 if (glsl_type_is_matrix(type)) {
188 const struct glsl_type *elem_type =
189 glsl_vector_type(glsl_get_base_type(type),
190 glsl_get_vector_elements(type));
191
192 for (unsigned i = 0; i < elems; i++)
193 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
194 } else if (glsl_type_is_array(type)) {
195 const struct glsl_type *elem_type = glsl_get_array_element(type);
196 for (unsigned i = 0; i < elems; i++)
197 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
198 } else {
199 for (unsigned i = 0; i < elems; i++) {
200 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
201 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
202 }
203 }
204 }
205
206 return val;
207 }
208
209 static struct vtn_ssa_value *
210 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
211 const struct glsl_type *type)
212 {
213 struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
214
215 if (entry)
216 return entry->data;
217
218 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
219 val->type = type;
220
221 switch (glsl_get_base_type(type)) {
222 case GLSL_TYPE_INT:
223 case GLSL_TYPE_UINT:
224 case GLSL_TYPE_INT16:
225 case GLSL_TYPE_UINT16:
226 case GLSL_TYPE_UINT8:
227 case GLSL_TYPE_INT8:
228 case GLSL_TYPE_INT64:
229 case GLSL_TYPE_UINT64:
230 case GLSL_TYPE_BOOL:
231 case GLSL_TYPE_FLOAT:
232 case GLSL_TYPE_FLOAT16:
233 case GLSL_TYPE_DOUBLE: {
234 int bit_size = glsl_get_bit_size(type);
235 if (glsl_type_is_vector_or_scalar(type)) {
236 unsigned num_components = glsl_get_vector_elements(val->type);
237 nir_load_const_instr *load =
238 nir_load_const_instr_create(b->shader, num_components, bit_size);
239
240 memcpy(load->value, constant->values,
241 sizeof(nir_const_value) * load->def.num_components);
242
243 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
244 val->def = &load->def;
245 } else {
246 assert(glsl_type_is_matrix(type));
247 unsigned columns = glsl_get_matrix_columns(val->type);
248 val->elems = ralloc_array(b, struct vtn_ssa_value *, columns);
249 const struct glsl_type *column_type = glsl_get_column_type(val->type);
250 for (unsigned i = 0; i < columns; i++)
251 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
252 column_type);
253 }
254 break;
255 }
256
257 case GLSL_TYPE_ARRAY: {
258 unsigned elems = glsl_get_length(val->type);
259 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
260 const struct glsl_type *elem_type = glsl_get_array_element(val->type);
261 for (unsigned i = 0; i < elems; i++)
262 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
263 elem_type);
264 break;
265 }
266
267 case GLSL_TYPE_STRUCT: {
268 unsigned elems = glsl_get_length(val->type);
269 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
270 for (unsigned i = 0; i < elems; i++) {
271 const struct glsl_type *elem_type =
272 glsl_get_struct_field(val->type, i);
273 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
274 elem_type);
275 }
276 break;
277 }
278
279 default:
280 vtn_fail("bad constant type");
281 }
282
283 return val;
284 }
285
286 struct vtn_ssa_value *
287 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
288 {
289 struct vtn_value *val = vtn_untyped_value(b, value_id);
290 switch (val->value_type) {
291 case vtn_value_type_undef:
292 return vtn_undef_ssa_value(b, val->type->type);
293
294 case vtn_value_type_constant:
295 return vtn_const_ssa_value(b, val->constant, val->type->type);
296
297 case vtn_value_type_ssa:
298 return val->ssa;
299
300 case vtn_value_type_pointer:
301 vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
302 struct vtn_ssa_value *ssa =
303 vtn_create_ssa_value(b, val->pointer->ptr_type->type);
304 ssa->def = vtn_pointer_to_ssa(b, val->pointer);
305 return ssa;
306
307 default:
308 vtn_fail("Invalid type for an SSA value");
309 }
310 }
311
312 static char *
313 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
314 unsigned word_count, unsigned *words_used)
315 {
316 char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
317 if (words_used) {
318 /* Ammount of space taken by the string (including the null) */
319 unsigned len = strlen(dup) + 1;
320 *words_used = DIV_ROUND_UP(len, sizeof(*words));
321 }
322 return dup;
323 }
324
325 const uint32_t *
326 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
327 const uint32_t *end, vtn_instruction_handler handler)
328 {
329 b->file = NULL;
330 b->line = -1;
331 b->col = -1;
332
333 const uint32_t *w = start;
334 while (w < end) {
335 SpvOp opcode = w[0] & SpvOpCodeMask;
336 unsigned count = w[0] >> SpvWordCountShift;
337 vtn_assert(count >= 1 && w + count <= end);
338
339 b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
340
341 switch (opcode) {
342 case SpvOpNop:
343 break; /* Do nothing */
344
345 case SpvOpLine:
346 b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
347 b->line = w[2];
348 b->col = w[3];
349 break;
350
351 case SpvOpNoLine:
352 b->file = NULL;
353 b->line = -1;
354 b->col = -1;
355 break;
356
357 default:
358 if (!handler(b, opcode, w, count))
359 return w;
360 break;
361 }
362
363 w += count;
364 }
365
366 b->spirv_offset = 0;
367 b->file = NULL;
368 b->line = -1;
369 b->col = -1;
370
371 assert(w == end);
372 return w;
373 }
374
375 static bool
376 vtn_handle_non_semantic_instruction(struct vtn_builder *b, SpvOp ext_opcode,
377 const uint32_t *w, unsigned count)
378 {
379 /* Do nothing. */
380 return true;
381 }
382
383 static void
384 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
385 const uint32_t *w, unsigned count)
386 {
387 const char *ext = (const char *)&w[2];
388 switch (opcode) {
389 case SpvOpExtInstImport: {
390 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
391 if (strcmp(ext, "GLSL.std.450") == 0) {
392 val->ext_handler = vtn_handle_glsl450_instruction;
393 } else if ((strcmp(ext, "SPV_AMD_gcn_shader") == 0)
394 && (b->options && b->options->caps.amd_gcn_shader)) {
395 val->ext_handler = vtn_handle_amd_gcn_shader_instruction;
396 } else if ((strcmp(ext, "SPV_AMD_shader_ballot") == 0)
397 && (b->options && b->options->caps.amd_shader_ballot)) {
398 val->ext_handler = vtn_handle_amd_shader_ballot_instruction;
399 } else if ((strcmp(ext, "SPV_AMD_shader_trinary_minmax") == 0)
400 && (b->options && b->options->caps.amd_trinary_minmax)) {
401 val->ext_handler = vtn_handle_amd_shader_trinary_minmax_instruction;
402 } else if ((strcmp(ext, "SPV_AMD_shader_explicit_vertex_parameter") == 0)
403 && (b->options && b->options->caps.amd_shader_explicit_vertex_parameter)) {
404 val->ext_handler = vtn_handle_amd_shader_explicit_vertex_parameter_instruction;
405 } else if (strcmp(ext, "OpenCL.std") == 0) {
406 val->ext_handler = vtn_handle_opencl_instruction;
407 } else if (strstr(ext, "NonSemantic.") == ext) {
408 val->ext_handler = vtn_handle_non_semantic_instruction;
409 } else {
410 vtn_fail("Unsupported extension: %s", ext);
411 }
412 break;
413 }
414
415 case SpvOpExtInst: {
416 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
417 bool handled = val->ext_handler(b, w[4], w, count);
418 vtn_assert(handled);
419 break;
420 }
421
422 default:
423 vtn_fail_with_opcode("Unhandled opcode", opcode);
424 }
425 }
426
427 static void
428 _foreach_decoration_helper(struct vtn_builder *b,
429 struct vtn_value *base_value,
430 int parent_member,
431 struct vtn_value *value,
432 vtn_decoration_foreach_cb cb, void *data)
433 {
434 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
435 int member;
436 if (dec->scope == VTN_DEC_DECORATION) {
437 member = parent_member;
438 } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
439 vtn_fail_if(value->value_type != vtn_value_type_type ||
440 value->type->base_type != vtn_base_type_struct,
441 "OpMemberDecorate and OpGroupMemberDecorate are only "
442 "allowed on OpTypeStruct");
443 /* This means we haven't recursed yet */
444 assert(value == base_value);
445
446 member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
447
448 vtn_fail_if(member >= base_value->type->length,
449 "OpMemberDecorate specifies member %d but the "
450 "OpTypeStruct has only %u members",
451 member, base_value->type->length);
452 } else {
453 /* Not a decoration */
454 assert(dec->scope == VTN_DEC_EXECUTION_MODE);
455 continue;
456 }
457
458 if (dec->group) {
459 assert(dec->group->value_type == vtn_value_type_decoration_group);
460 _foreach_decoration_helper(b, base_value, member, dec->group,
461 cb, data);
462 } else {
463 cb(b, base_value, member, dec, data);
464 }
465 }
466 }
467
468 /** Iterates (recursively if needed) over all of the decorations on a value
469 *
470 * This function iterates over all of the decorations applied to a given
471 * value. If it encounters a decoration group, it recurses into the group
472 * and iterates over all of those decorations as well.
473 */
474 void
475 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
476 vtn_decoration_foreach_cb cb, void *data)
477 {
478 _foreach_decoration_helper(b, value, -1, value, cb, data);
479 }
480
481 void
482 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
483 vtn_execution_mode_foreach_cb cb, void *data)
484 {
485 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
486 if (dec->scope != VTN_DEC_EXECUTION_MODE)
487 continue;
488
489 assert(dec->group == NULL);
490 cb(b, value, dec, data);
491 }
492 }
493
494 void
495 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
496 const uint32_t *w, unsigned count)
497 {
498 const uint32_t *w_end = w + count;
499 const uint32_t target = w[1];
500 w += 2;
501
502 switch (opcode) {
503 case SpvOpDecorationGroup:
504 vtn_push_value(b, target, vtn_value_type_decoration_group);
505 break;
506
507 case SpvOpDecorate:
508 case SpvOpDecorateId:
509 case SpvOpMemberDecorate:
510 case SpvOpDecorateString:
511 case SpvOpMemberDecorateString:
512 case SpvOpExecutionMode:
513 case SpvOpExecutionModeId: {
514 struct vtn_value *val = vtn_untyped_value(b, target);
515
516 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
517 switch (opcode) {
518 case SpvOpDecorate:
519 case SpvOpDecorateId:
520 case SpvOpDecorateString:
521 dec->scope = VTN_DEC_DECORATION;
522 break;
523 case SpvOpMemberDecorate:
524 case SpvOpMemberDecorateString:
525 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(w++);
526 vtn_fail_if(dec->scope < VTN_DEC_STRUCT_MEMBER0, /* overflow */
527 "Member argument of OpMemberDecorate too large");
528 break;
529 case SpvOpExecutionMode:
530 case SpvOpExecutionModeId:
531 dec->scope = VTN_DEC_EXECUTION_MODE;
532 break;
533 default:
534 unreachable("Invalid decoration opcode");
535 }
536 dec->decoration = *(w++);
537 dec->operands = w;
538
539 /* Link into the list */
540 dec->next = val->decoration;
541 val->decoration = dec;
542 break;
543 }
544
545 case SpvOpGroupMemberDecorate:
546 case SpvOpGroupDecorate: {
547 struct vtn_value *group =
548 vtn_value(b, target, vtn_value_type_decoration_group);
549
550 for (; w < w_end; w++) {
551 struct vtn_value *val = vtn_untyped_value(b, *w);
552 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
553
554 dec->group = group;
555 if (opcode == SpvOpGroupDecorate) {
556 dec->scope = VTN_DEC_DECORATION;
557 } else {
558 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
559 vtn_fail_if(dec->scope < 0, /* Check for overflow */
560 "Member argument of OpGroupMemberDecorate too large");
561 }
562
563 /* Link into the list */
564 dec->next = val->decoration;
565 val->decoration = dec;
566 }
567 break;
568 }
569
570 default:
571 unreachable("Unhandled opcode");
572 }
573 }
574
575 struct member_decoration_ctx {
576 unsigned num_fields;
577 struct glsl_struct_field *fields;
578 struct vtn_type *type;
579 };
580
581 /**
582 * Returns true if the given type contains a struct decorated Block or
583 * BufferBlock
584 */
585 bool
586 vtn_type_contains_block(struct vtn_builder *b, struct vtn_type *type)
587 {
588 switch (type->base_type) {
589 case vtn_base_type_array:
590 return vtn_type_contains_block(b, type->array_element);
591 case vtn_base_type_struct:
592 if (type->block || type->buffer_block)
593 return true;
594 for (unsigned i = 0; i < type->length; i++) {
595 if (vtn_type_contains_block(b, type->members[i]))
596 return true;
597 }
598 return false;
599 default:
600 return false;
601 }
602 }
603
604 /** Returns true if two types are "compatible", i.e. you can do an OpLoad,
605 * OpStore, or OpCopyMemory between them without breaking anything.
606 * Technically, the SPIR-V rules require the exact same type ID but this lets
607 * us internally be a bit looser.
608 */
609 bool
610 vtn_types_compatible(struct vtn_builder *b,
611 struct vtn_type *t1, struct vtn_type *t2)
612 {
613 if (t1->id == t2->id)
614 return true;
615
616 if (t1->base_type != t2->base_type)
617 return false;
618
619 switch (t1->base_type) {
620 case vtn_base_type_void:
621 case vtn_base_type_scalar:
622 case vtn_base_type_vector:
623 case vtn_base_type_matrix:
624 case vtn_base_type_image:
625 case vtn_base_type_sampler:
626 case vtn_base_type_sampled_image:
627 return t1->type == t2->type;
628
629 case vtn_base_type_array:
630 return t1->length == t2->length &&
631 vtn_types_compatible(b, t1->array_element, t2->array_element);
632
633 case vtn_base_type_pointer:
634 return vtn_types_compatible(b, t1->deref, t2->deref);
635
636 case vtn_base_type_struct:
637 if (t1->length != t2->length)
638 return false;
639
640 for (unsigned i = 0; i < t1->length; i++) {
641 if (!vtn_types_compatible(b, t1->members[i], t2->members[i]))
642 return false;
643 }
644 return true;
645
646 case vtn_base_type_function:
647 /* This case shouldn't get hit since you can't copy around function
648 * types. Just require them to be identical.
649 */
650 return false;
651 }
652
653 vtn_fail("Invalid base type");
654 }
655
656 struct vtn_type *
657 vtn_type_without_array(struct vtn_type *type)
658 {
659 while (type->base_type == vtn_base_type_array)
660 type = type->array_element;
661 return type;
662 }
663
664 /* does a shallow copy of a vtn_type */
665
666 static struct vtn_type *
667 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
668 {
669 struct vtn_type *dest = ralloc(b, struct vtn_type);
670 *dest = *src;
671
672 switch (src->base_type) {
673 case vtn_base_type_void:
674 case vtn_base_type_scalar:
675 case vtn_base_type_vector:
676 case vtn_base_type_matrix:
677 case vtn_base_type_array:
678 case vtn_base_type_pointer:
679 case vtn_base_type_image:
680 case vtn_base_type_sampler:
681 case vtn_base_type_sampled_image:
682 /* Nothing more to do */
683 break;
684
685 case vtn_base_type_struct:
686 dest->members = ralloc_array(b, struct vtn_type *, src->length);
687 memcpy(dest->members, src->members,
688 src->length * sizeof(src->members[0]));
689
690 dest->offsets = ralloc_array(b, unsigned, src->length);
691 memcpy(dest->offsets, src->offsets,
692 src->length * sizeof(src->offsets[0]));
693 break;
694
695 case vtn_base_type_function:
696 dest->params = ralloc_array(b, struct vtn_type *, src->length);
697 memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
698 break;
699 }
700
701 return dest;
702 }
703
704 static struct vtn_type *
705 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
706 {
707 type->members[member] = vtn_type_copy(b, type->members[member]);
708 type = type->members[member];
709
710 /* We may have an array of matrices.... Oh, joy! */
711 while (glsl_type_is_array(type->type)) {
712 type->array_element = vtn_type_copy(b, type->array_element);
713 type = type->array_element;
714 }
715
716 vtn_assert(glsl_type_is_matrix(type->type));
717
718 return type;
719 }
720
721 static void
722 vtn_handle_access_qualifier(struct vtn_builder *b, struct vtn_type *type,
723 int member, enum gl_access_qualifier access)
724 {
725 type->members[member] = vtn_type_copy(b, type->members[member]);
726 type = type->members[member];
727
728 type->access |= access;
729 }
730
731 static void
732 array_stride_decoration_cb(struct vtn_builder *b,
733 struct vtn_value *val, int member,
734 const struct vtn_decoration *dec, void *void_ctx)
735 {
736 struct vtn_type *type = val->type;
737
738 if (dec->decoration == SpvDecorationArrayStride) {
739 if (vtn_type_contains_block(b, type)) {
740 vtn_warn("The ArrayStride decoration cannot be applied to an array "
741 "type which contains a structure type decorated Block "
742 "or BufferBlock");
743 /* Ignore the decoration */
744 } else {
745 vtn_fail_if(dec->operands[0] == 0, "ArrayStride must be non-zero");
746 type->stride = dec->operands[0];
747 }
748 }
749 }
750
751 static void
752 struct_member_decoration_cb(struct vtn_builder *b,
753 UNUSED struct vtn_value *val, int member,
754 const struct vtn_decoration *dec, void *void_ctx)
755 {
756 struct member_decoration_ctx *ctx = void_ctx;
757
758 if (member < 0)
759 return;
760
761 assert(member < ctx->num_fields);
762
763 switch (dec->decoration) {
764 case SpvDecorationRelaxedPrecision:
765 case SpvDecorationUniform:
766 case SpvDecorationUniformId:
767 break; /* FIXME: Do nothing with this for now. */
768 case SpvDecorationNonWritable:
769 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_WRITEABLE);
770 break;
771 case SpvDecorationNonReadable:
772 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_NON_READABLE);
773 break;
774 case SpvDecorationVolatile:
775 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_VOLATILE);
776 break;
777 case SpvDecorationCoherent:
778 vtn_handle_access_qualifier(b, ctx->type, member, ACCESS_COHERENT);
779 break;
780 case SpvDecorationNoPerspective:
781 ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
782 break;
783 case SpvDecorationFlat:
784 ctx->fields[member].interpolation = INTERP_MODE_FLAT;
785 break;
786 case SpvDecorationExplicitInterpAMD:
787 ctx->fields[member].interpolation = INTERP_MODE_EXPLICIT;
788 break;
789 case SpvDecorationCentroid:
790 ctx->fields[member].centroid = true;
791 break;
792 case SpvDecorationSample:
793 ctx->fields[member].sample = true;
794 break;
795 case SpvDecorationStream:
796 /* This is handled later by var_decoration_cb in vtn_variables.c */
797 break;
798 case SpvDecorationLocation:
799 ctx->fields[member].location = dec->operands[0];
800 break;
801 case SpvDecorationComponent:
802 break; /* FIXME: What should we do with these? */
803 case SpvDecorationBuiltIn:
804 ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
805 ctx->type->members[member]->is_builtin = true;
806 ctx->type->members[member]->builtin = dec->operands[0];
807 ctx->type->builtin_block = true;
808 break;
809 case SpvDecorationOffset:
810 ctx->type->offsets[member] = dec->operands[0];
811 ctx->fields[member].offset = dec->operands[0];
812 break;
813 case SpvDecorationMatrixStride:
814 /* Handled as a second pass */
815 break;
816 case SpvDecorationColMajor:
817 break; /* Nothing to do here. Column-major is the default. */
818 case SpvDecorationRowMajor:
819 mutable_matrix_member(b, ctx->type, member)->row_major = true;
820 break;
821
822 case SpvDecorationPatch:
823 break;
824
825 case SpvDecorationSpecId:
826 case SpvDecorationBlock:
827 case SpvDecorationBufferBlock:
828 case SpvDecorationArrayStride:
829 case SpvDecorationGLSLShared:
830 case SpvDecorationGLSLPacked:
831 case SpvDecorationInvariant:
832 case SpvDecorationRestrict:
833 case SpvDecorationAliased:
834 case SpvDecorationConstant:
835 case SpvDecorationIndex:
836 case SpvDecorationBinding:
837 case SpvDecorationDescriptorSet:
838 case SpvDecorationLinkageAttributes:
839 case SpvDecorationNoContraction:
840 case SpvDecorationInputAttachmentIndex:
841 vtn_warn("Decoration not allowed on struct members: %s",
842 spirv_decoration_to_string(dec->decoration));
843 break;
844
845 case SpvDecorationXfbBuffer:
846 case SpvDecorationXfbStride:
847 /* This is handled later by var_decoration_cb in vtn_variables.c */
848 break;
849
850 case SpvDecorationCPacked:
851 if (b->shader->info.stage != MESA_SHADER_KERNEL)
852 vtn_warn("Decoration only allowed for CL-style kernels: %s",
853 spirv_decoration_to_string(dec->decoration));
854 else
855 ctx->type->packed = true;
856 break;
857
858 case SpvDecorationSaturatedConversion:
859 case SpvDecorationFuncParamAttr:
860 case SpvDecorationFPRoundingMode:
861 case SpvDecorationFPFastMathMode:
862 case SpvDecorationAlignment:
863 if (b->shader->info.stage != MESA_SHADER_KERNEL) {
864 vtn_warn("Decoration only allowed for CL-style kernels: %s",
865 spirv_decoration_to_string(dec->decoration));
866 }
867 break;
868
869 case SpvDecorationUserSemantic:
870 /* User semantic decorations can safely be ignored by the driver. */
871 break;
872
873 default:
874 vtn_fail_with_decoration("Unhandled decoration", dec->decoration);
875 }
876 }
877
878 /** Chases the array type all the way down to the tail and rewrites the
879 * glsl_types to be based off the tail's glsl_type.
880 */
881 static void
882 vtn_array_type_rewrite_glsl_type(struct vtn_type *type)
883 {
884 if (type->base_type != vtn_base_type_array)
885 return;
886
887 vtn_array_type_rewrite_glsl_type(type->array_element);
888
889 type->type = glsl_array_type(type->array_element->type,
890 type->length, type->stride);
891 }
892
893 /* Matrix strides are handled as a separate pass because we need to know
894 * whether the matrix is row-major or not first.
895 */
896 static void
897 struct_member_matrix_stride_cb(struct vtn_builder *b,
898 UNUSED struct vtn_value *val, int member,
899 const struct vtn_decoration *dec,
900 void *void_ctx)
901 {
902 if (dec->decoration != SpvDecorationMatrixStride)
903 return;
904
905 vtn_fail_if(member < 0,
906 "The MatrixStride decoration is only allowed on members "
907 "of OpTypeStruct");
908 vtn_fail_if(dec->operands[0] == 0, "MatrixStride must be non-zero");
909
910 struct member_decoration_ctx *ctx = void_ctx;
911
912 struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
913 if (mat_type->row_major) {
914 mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
915 mat_type->stride = mat_type->array_element->stride;
916 mat_type->array_element->stride = dec->operands[0];
917
918 mat_type->type = glsl_explicit_matrix_type(mat_type->type,
919 dec->operands[0], true);
920 mat_type->array_element->type = glsl_get_column_type(mat_type->type);
921 } else {
922 vtn_assert(mat_type->array_element->stride > 0);
923 mat_type->stride = dec->operands[0];
924
925 mat_type->type = glsl_explicit_matrix_type(mat_type->type,
926 dec->operands[0], false);
927 }
928
929 /* Now that we've replaced the glsl_type with a properly strided matrix
930 * type, rewrite the member type so that it's an array of the proper kind
931 * of glsl_type.
932 */
933 vtn_array_type_rewrite_glsl_type(ctx->type->members[member]);
934 ctx->fields[member].type = ctx->type->members[member]->type;
935 }
936
937 static void
938 struct_block_decoration_cb(struct vtn_builder *b,
939 struct vtn_value *val, int member,
940 const struct vtn_decoration *dec, void *ctx)
941 {
942 if (member != -1)
943 return;
944
945 struct vtn_type *type = val->type;
946 if (dec->decoration == SpvDecorationBlock)
947 type->block = true;
948 else if (dec->decoration == SpvDecorationBufferBlock)
949 type->buffer_block = true;
950 }
951
952 static void
953 type_decoration_cb(struct vtn_builder *b,
954 struct vtn_value *val, int member,
955 const struct vtn_decoration *dec, UNUSED void *ctx)
956 {
957 struct vtn_type *type = val->type;
958
959 if (member != -1) {
960 /* This should have been handled by OpTypeStruct */
961 assert(val->type->base_type == vtn_base_type_struct);
962 assert(member >= 0 && member < val->type->length);
963 return;
964 }
965
966 switch (dec->decoration) {
967 case SpvDecorationArrayStride:
968 vtn_assert(type->base_type == vtn_base_type_array ||
969 type->base_type == vtn_base_type_pointer);
970 break;
971 case SpvDecorationBlock:
972 vtn_assert(type->base_type == vtn_base_type_struct);
973 vtn_assert(type->block);
974 break;
975 case SpvDecorationBufferBlock:
976 vtn_assert(type->base_type == vtn_base_type_struct);
977 vtn_assert(type->buffer_block);
978 break;
979 case SpvDecorationGLSLShared:
980 case SpvDecorationGLSLPacked:
981 /* Ignore these, since we get explicit offsets anyways */
982 break;
983
984 case SpvDecorationRowMajor:
985 case SpvDecorationColMajor:
986 case SpvDecorationMatrixStride:
987 case SpvDecorationBuiltIn:
988 case SpvDecorationNoPerspective:
989 case SpvDecorationFlat:
990 case SpvDecorationPatch:
991 case SpvDecorationCentroid:
992 case SpvDecorationSample:
993 case SpvDecorationExplicitInterpAMD:
994 case SpvDecorationVolatile:
995 case SpvDecorationCoherent:
996 case SpvDecorationNonWritable:
997 case SpvDecorationNonReadable:
998 case SpvDecorationUniform:
999 case SpvDecorationUniformId:
1000 case SpvDecorationLocation:
1001 case SpvDecorationComponent:
1002 case SpvDecorationOffset:
1003 case SpvDecorationXfbBuffer:
1004 case SpvDecorationXfbStride:
1005 case SpvDecorationUserSemantic:
1006 vtn_warn("Decoration only allowed for struct members: %s",
1007 spirv_decoration_to_string(dec->decoration));
1008 break;
1009
1010 case SpvDecorationStream:
1011 /* We don't need to do anything here, as stream is filled up when
1012 * aplying the decoration to a variable, just check that if it is not a
1013 * struct member, it should be a struct.
1014 */
1015 vtn_assert(type->base_type == vtn_base_type_struct);
1016 break;
1017
1018 case SpvDecorationRelaxedPrecision:
1019 case SpvDecorationSpecId:
1020 case SpvDecorationInvariant:
1021 case SpvDecorationRestrict:
1022 case SpvDecorationAliased:
1023 case SpvDecorationConstant:
1024 case SpvDecorationIndex:
1025 case SpvDecorationBinding:
1026 case SpvDecorationDescriptorSet:
1027 case SpvDecorationLinkageAttributes:
1028 case SpvDecorationNoContraction:
1029 case SpvDecorationInputAttachmentIndex:
1030 vtn_warn("Decoration not allowed on types: %s",
1031 spirv_decoration_to_string(dec->decoration));
1032 break;
1033
1034 case SpvDecorationCPacked:
1035 if (b->shader->info.stage != MESA_SHADER_KERNEL)
1036 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1037 spirv_decoration_to_string(dec->decoration));
1038 else
1039 type->packed = true;
1040 break;
1041
1042 case SpvDecorationSaturatedConversion:
1043 case SpvDecorationFuncParamAttr:
1044 case SpvDecorationFPRoundingMode:
1045 case SpvDecorationFPFastMathMode:
1046 case SpvDecorationAlignment:
1047 vtn_warn("Decoration only allowed for CL-style kernels: %s",
1048 spirv_decoration_to_string(dec->decoration));
1049 break;
1050
1051 default:
1052 vtn_fail_with_decoration("Unhandled decoration", dec->decoration);
1053 }
1054 }
1055
1056 static unsigned
1057 translate_image_format(struct vtn_builder *b, SpvImageFormat format)
1058 {
1059 switch (format) {
1060 case SpvImageFormatUnknown: return PIPE_FORMAT_NONE;
1061 case SpvImageFormatRgba32f: return PIPE_FORMAT_R32G32B32A32_FLOAT;
1062 case SpvImageFormatRgba16f: return PIPE_FORMAT_R16G16B16A16_FLOAT;
1063 case SpvImageFormatR32f: return PIPE_FORMAT_R32_FLOAT;
1064 case SpvImageFormatRgba8: return PIPE_FORMAT_R8G8B8A8_UNORM;
1065 case SpvImageFormatRgba8Snorm: return PIPE_FORMAT_R8G8B8A8_SNORM;
1066 case SpvImageFormatRg32f: return PIPE_FORMAT_R32G32_FLOAT;
1067 case SpvImageFormatRg16f: return PIPE_FORMAT_R16G16_FLOAT;
1068 case SpvImageFormatR11fG11fB10f: return PIPE_FORMAT_R11G11B10_FLOAT;
1069 case SpvImageFormatR16f: return PIPE_FORMAT_R16_FLOAT;
1070 case SpvImageFormatRgba16: return PIPE_FORMAT_R16G16B16A16_UNORM;
1071 case SpvImageFormatRgb10A2: return PIPE_FORMAT_R10G10B10A2_UNORM;
1072 case SpvImageFormatRg16: return PIPE_FORMAT_R16G16_UNORM;
1073 case SpvImageFormatRg8: return PIPE_FORMAT_R8G8_UNORM;
1074 case SpvImageFormatR16: return PIPE_FORMAT_R16_UNORM;
1075 case SpvImageFormatR8: return PIPE_FORMAT_R8_UNORM;
1076 case SpvImageFormatRgba16Snorm: return PIPE_FORMAT_R16G16B16A16_SNORM;
1077 case SpvImageFormatRg16Snorm: return PIPE_FORMAT_R16G16_SNORM;
1078 case SpvImageFormatRg8Snorm: return PIPE_FORMAT_R8G8_SNORM;
1079 case SpvImageFormatR16Snorm: return PIPE_FORMAT_R16_SNORM;
1080 case SpvImageFormatR8Snorm: return PIPE_FORMAT_R8_SNORM;
1081 case SpvImageFormatRgba32i: return PIPE_FORMAT_R32G32B32A32_SINT;
1082 case SpvImageFormatRgba16i: return PIPE_FORMAT_R16G16B16A16_SINT;
1083 case SpvImageFormatRgba8i: return PIPE_FORMAT_R8G8B8A8_SINT;
1084 case SpvImageFormatR32i: return PIPE_FORMAT_R32_SINT;
1085 case SpvImageFormatRg32i: return PIPE_FORMAT_R32G32_SINT;
1086 case SpvImageFormatRg16i: return PIPE_FORMAT_R16G16_SINT;
1087 case SpvImageFormatRg8i: return PIPE_FORMAT_R8G8_SINT;
1088 case SpvImageFormatR16i: return PIPE_FORMAT_R16_SINT;
1089 case SpvImageFormatR8i: return PIPE_FORMAT_R8_SINT;
1090 case SpvImageFormatRgba32ui: return PIPE_FORMAT_R32G32B32A32_UINT;
1091 case SpvImageFormatRgba16ui: return PIPE_FORMAT_R16G16B16A16_UINT;
1092 case SpvImageFormatRgba8ui: return PIPE_FORMAT_R8G8B8A8_UINT;
1093 case SpvImageFormatR32ui: return PIPE_FORMAT_R32_UINT;
1094 case SpvImageFormatRgb10a2ui: return PIPE_FORMAT_R10G10B10A2_UINT;
1095 case SpvImageFormatRg32ui: return PIPE_FORMAT_R32G32_UINT;
1096 case SpvImageFormatRg16ui: return PIPE_FORMAT_R16G16_UINT;
1097 case SpvImageFormatRg8ui: return PIPE_FORMAT_R8G8_UINT;
1098 case SpvImageFormatR16ui: return PIPE_FORMAT_R16_UINT;
1099 case SpvImageFormatR8ui: return PIPE_FORMAT_R8_UINT;
1100 default:
1101 vtn_fail("Invalid image format: %s (%u)",
1102 spirv_imageformat_to_string(format), format);
1103 }
1104 }
1105
1106 static void
1107 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
1108 const uint32_t *w, unsigned count)
1109 {
1110 struct vtn_value *val = NULL;
1111
1112 /* In order to properly handle forward declarations, we have to defer
1113 * allocation for pointer types.
1114 */
1115 if (opcode != SpvOpTypePointer && opcode != SpvOpTypeForwardPointer) {
1116 val = vtn_push_value(b, w[1], vtn_value_type_type);
1117 vtn_fail_if(val->type != NULL,
1118 "Only pointers can have forward declarations");
1119 val->type = rzalloc(b, struct vtn_type);
1120 val->type->id = w[1];
1121 }
1122
1123 switch (opcode) {
1124 case SpvOpTypeVoid:
1125 val->type->base_type = vtn_base_type_void;
1126 val->type->type = glsl_void_type();
1127 break;
1128 case SpvOpTypeBool:
1129 val->type->base_type = vtn_base_type_scalar;
1130 val->type->type = glsl_bool_type();
1131 val->type->length = 1;
1132 break;
1133 case SpvOpTypeInt: {
1134 int bit_size = w[2];
1135 const bool signedness = w[3];
1136 val->type->base_type = vtn_base_type_scalar;
1137 switch (bit_size) {
1138 case 64:
1139 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1140 break;
1141 case 32:
1142 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1143 break;
1144 case 16:
1145 val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1146 break;
1147 case 8:
1148 val->type->type = (signedness ? glsl_int8_t_type() : glsl_uint8_t_type());
1149 break;
1150 default:
1151 vtn_fail("Invalid int bit size: %u", bit_size);
1152 }
1153 val->type->length = 1;
1154 break;
1155 }
1156
1157 case SpvOpTypeFloat: {
1158 int bit_size = w[2];
1159 val->type->base_type = vtn_base_type_scalar;
1160 switch (bit_size) {
1161 case 16:
1162 val->type->type = glsl_float16_t_type();
1163 break;
1164 case 32:
1165 val->type->type = glsl_float_type();
1166 break;
1167 case 64:
1168 val->type->type = glsl_double_type();
1169 break;
1170 default:
1171 vtn_fail("Invalid float bit size: %u", bit_size);
1172 }
1173 val->type->length = 1;
1174 break;
1175 }
1176
1177 case SpvOpTypeVector: {
1178 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1179 unsigned elems = w[3];
1180
1181 vtn_fail_if(base->base_type != vtn_base_type_scalar,
1182 "Base type for OpTypeVector must be a scalar");
1183 vtn_fail_if((elems < 2 || elems > 4) && (elems != 8) && (elems != 16),
1184 "Invalid component count for OpTypeVector");
1185
1186 val->type->base_type = vtn_base_type_vector;
1187 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1188 val->type->length = elems;
1189 val->type->stride = glsl_type_is_boolean(val->type->type)
1190 ? 4 : glsl_get_bit_size(base->type) / 8;
1191 val->type->array_element = base;
1192 break;
1193 }
1194
1195 case SpvOpTypeMatrix: {
1196 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1197 unsigned columns = w[3];
1198
1199 vtn_fail_if(base->base_type != vtn_base_type_vector,
1200 "Base type for OpTypeMatrix must be a vector");
1201 vtn_fail_if(columns < 2 || columns > 4,
1202 "Invalid column count for OpTypeMatrix");
1203
1204 val->type->base_type = vtn_base_type_matrix;
1205 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1206 glsl_get_vector_elements(base->type),
1207 columns);
1208 vtn_fail_if(glsl_type_is_error(val->type->type),
1209 "Unsupported base type for OpTypeMatrix");
1210 assert(!glsl_type_is_error(val->type->type));
1211 val->type->length = columns;
1212 val->type->array_element = base;
1213 val->type->row_major = false;
1214 val->type->stride = 0;
1215 break;
1216 }
1217
1218 case SpvOpTypeRuntimeArray:
1219 case SpvOpTypeArray: {
1220 struct vtn_type *array_element =
1221 vtn_value(b, w[2], vtn_value_type_type)->type;
1222
1223 if (opcode == SpvOpTypeRuntimeArray) {
1224 /* A length of 0 is used to denote unsized arrays */
1225 val->type->length = 0;
1226 } else {
1227 val->type->length = vtn_constant_uint(b, w[3]);
1228 }
1229
1230 val->type->base_type = vtn_base_type_array;
1231 val->type->array_element = array_element;
1232 if (b->shader->info.stage == MESA_SHADER_KERNEL)
1233 val->type->stride = glsl_get_cl_size(array_element->type);
1234
1235 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1236 val->type->type = glsl_array_type(array_element->type, val->type->length,
1237 val->type->stride);
1238 break;
1239 }
1240
1241 case SpvOpTypeStruct: {
1242 unsigned num_fields = count - 2;
1243 val->type->base_type = vtn_base_type_struct;
1244 val->type->length = num_fields;
1245 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1246 val->type->offsets = ralloc_array(b, unsigned, num_fields);
1247 val->type->packed = false;
1248
1249 NIR_VLA(struct glsl_struct_field, fields, count);
1250 for (unsigned i = 0; i < num_fields; i++) {
1251 val->type->members[i] =
1252 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
1253 fields[i] = (struct glsl_struct_field) {
1254 .type = val->type->members[i]->type,
1255 .name = ralloc_asprintf(b, "field%d", i),
1256 .location = -1,
1257 .offset = -1,
1258 };
1259 }
1260
1261 if (b->shader->info.stage == MESA_SHADER_KERNEL) {
1262 unsigned offset = 0;
1263 for (unsigned i = 0; i < num_fields; i++) {
1264 offset = align(offset, glsl_get_cl_alignment(fields[i].type));
1265 fields[i].offset = offset;
1266 offset += glsl_get_cl_size(fields[i].type);
1267 }
1268 }
1269
1270 struct member_decoration_ctx ctx = {
1271 .num_fields = num_fields,
1272 .fields = fields,
1273 .type = val->type
1274 };
1275
1276 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1277 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1278
1279 vtn_foreach_decoration(b, val, struct_block_decoration_cb, NULL);
1280
1281 const char *name = val->name;
1282
1283 if (val->type->block || val->type->buffer_block) {
1284 /* Packing will be ignored since types coming from SPIR-V are
1285 * explicitly laid out.
1286 */
1287 val->type->type = glsl_interface_type(fields, num_fields,
1288 /* packing */ 0, false,
1289 name ? name : "block");
1290 } else {
1291 val->type->type = glsl_struct_type(fields, num_fields,
1292 name ? name : "struct", false);
1293 }
1294 break;
1295 }
1296
1297 case SpvOpTypeFunction: {
1298 val->type->base_type = vtn_base_type_function;
1299 val->type->type = NULL;
1300
1301 val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
1302
1303 const unsigned num_params = count - 3;
1304 val->type->length = num_params;
1305 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1306 for (unsigned i = 0; i < count - 3; i++) {
1307 val->type->params[i] =
1308 vtn_value(b, w[i + 3], vtn_value_type_type)->type;
1309 }
1310 break;
1311 }
1312
1313 case SpvOpTypePointer:
1314 case SpvOpTypeForwardPointer: {
1315 /* We can't blindly push the value because it might be a forward
1316 * declaration.
1317 */
1318 val = vtn_untyped_value(b, w[1]);
1319
1320 SpvStorageClass storage_class = w[2];
1321
1322 if (val->value_type == vtn_value_type_invalid) {
1323 val->value_type = vtn_value_type_type;
1324 val->type = rzalloc(b, struct vtn_type);
1325 val->type->id = w[1];
1326 val->type->base_type = vtn_base_type_pointer;
1327 val->type->storage_class = storage_class;
1328
1329 /* These can actually be stored to nir_variables and used as SSA
1330 * values so they need a real glsl_type.
1331 */
1332 enum vtn_variable_mode mode = vtn_storage_class_to_mode(
1333 b, storage_class, NULL, NULL);
1334 val->type->type = nir_address_format_to_glsl_type(
1335 vtn_mode_to_address_format(b, mode));
1336 } else {
1337 vtn_fail_if(val->type->storage_class != storage_class,
1338 "The storage classes of an OpTypePointer and any "
1339 "OpTypeForwardPointers that provide forward "
1340 "declarations of it must match.");
1341 }
1342
1343 if (opcode == SpvOpTypePointer) {
1344 vtn_fail_if(val->type->deref != NULL,
1345 "While OpTypeForwardPointer can be used to provide a "
1346 "forward declaration of a pointer, OpTypePointer can "
1347 "only be used once for a given id.");
1348
1349 val->type->deref = vtn_value(b, w[3], vtn_value_type_type)->type;
1350
1351 /* Only certain storage classes use ArrayStride. The others (in
1352 * particular Workgroup) are expected to be laid out by the driver.
1353 */
1354 switch (storage_class) {
1355 case SpvStorageClassUniform:
1356 case SpvStorageClassPushConstant:
1357 case SpvStorageClassStorageBuffer:
1358 case SpvStorageClassPhysicalStorageBuffer:
1359 vtn_foreach_decoration(b, val, array_stride_decoration_cb, NULL);
1360 break;
1361 default:
1362 /* Nothing to do. */
1363 break;
1364 }
1365
1366 if (b->physical_ptrs) {
1367 switch (storage_class) {
1368 case SpvStorageClassFunction:
1369 case SpvStorageClassWorkgroup:
1370 case SpvStorageClassCrossWorkgroup:
1371 case SpvStorageClassUniformConstant:
1372 val->type->stride = align(glsl_get_cl_size(val->type->deref->type),
1373 glsl_get_cl_alignment(val->type->deref->type));
1374 break;
1375 default:
1376 break;
1377 }
1378 }
1379 }
1380 break;
1381 }
1382
1383 case SpvOpTypeImage: {
1384 val->type->base_type = vtn_base_type_image;
1385
1386 const struct vtn_type *sampled_type =
1387 vtn_value(b, w[2], vtn_value_type_type)->type;
1388
1389 vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1390 glsl_get_bit_size(sampled_type->type) != 32,
1391 "Sampled type of OpTypeImage must be a 32-bit scalar");
1392
1393 enum glsl_sampler_dim dim;
1394 switch ((SpvDim)w[3]) {
1395 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
1396 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
1397 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
1398 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
1399 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
1400 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
1401 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1402 default:
1403 vtn_fail("Invalid SPIR-V image dimensionality: %s (%u)",
1404 spirv_dim_to_string((SpvDim)w[3]), w[3]);
1405 }
1406
1407 /* w[4]: as per Vulkan spec "Validation Rules within a Module",
1408 * The “Depth” operand of OpTypeImage is ignored.
1409 */
1410 bool is_array = w[5];
1411 bool multisampled = w[6];
1412 unsigned sampled = w[7];
1413 SpvImageFormat format = w[8];
1414
1415 if (count > 9)
1416 val->type->access_qualifier = w[9];
1417 else
1418 val->type->access_qualifier = SpvAccessQualifierReadWrite;
1419
1420 if (multisampled) {
1421 if (dim == GLSL_SAMPLER_DIM_2D)
1422 dim = GLSL_SAMPLER_DIM_MS;
1423 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1424 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1425 else
1426 vtn_fail("Unsupported multisampled image type");
1427 }
1428
1429 val->type->image_format = translate_image_format(b, format);
1430
1431 enum glsl_base_type sampled_base_type =
1432 glsl_get_base_type(sampled_type->type);
1433 if (sampled == 1) {
1434 val->type->sampled = true;
1435 val->type->type = glsl_sampler_type(dim, false, is_array,
1436 sampled_base_type);
1437 } else if (sampled == 2) {
1438 val->type->sampled = false;
1439 val->type->type = glsl_image_type(dim, is_array, sampled_base_type);
1440 } else {
1441 vtn_fail("We need to know if the image will be sampled");
1442 }
1443 break;
1444 }
1445
1446 case SpvOpTypeSampledImage:
1447 val->type->base_type = vtn_base_type_sampled_image;
1448 val->type->image = vtn_value(b, w[2], vtn_value_type_type)->type;
1449 val->type->type = val->type->image->type;
1450 break;
1451
1452 case SpvOpTypeSampler:
1453 /* The actual sampler type here doesn't really matter. It gets
1454 * thrown away the moment you combine it with an image. What really
1455 * matters is that it's a sampler type as opposed to an integer type
1456 * so the backend knows what to do.
1457 */
1458 val->type->base_type = vtn_base_type_sampler;
1459 val->type->type = glsl_bare_sampler_type();
1460 break;
1461
1462 case SpvOpTypeOpaque:
1463 case SpvOpTypeEvent:
1464 case SpvOpTypeDeviceEvent:
1465 case SpvOpTypeReserveId:
1466 case SpvOpTypeQueue:
1467 case SpvOpTypePipe:
1468 default:
1469 vtn_fail_with_opcode("Unhandled opcode", opcode);
1470 }
1471
1472 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1473
1474 if (val->type->base_type == vtn_base_type_struct &&
1475 (val->type->block || val->type->buffer_block)) {
1476 for (unsigned i = 0; i < val->type->length; i++) {
1477 vtn_fail_if(vtn_type_contains_block(b, val->type->members[i]),
1478 "Block and BufferBlock decorations cannot decorate a "
1479 "structure type that is nested at any level inside "
1480 "another structure type decorated with Block or "
1481 "BufferBlock.");
1482 }
1483 }
1484 }
1485
1486 static nir_constant *
1487 vtn_null_constant(struct vtn_builder *b, struct vtn_type *type)
1488 {
1489 nir_constant *c = rzalloc(b, nir_constant);
1490
1491 switch (type->base_type) {
1492 case vtn_base_type_scalar:
1493 case vtn_base_type_vector:
1494 /* Nothing to do here. It's already initialized to zero */
1495 break;
1496
1497 case vtn_base_type_pointer: {
1498 enum vtn_variable_mode mode = vtn_storage_class_to_mode(
1499 b, type->storage_class, type->deref, NULL);
1500 nir_address_format addr_format = vtn_mode_to_address_format(b, mode);
1501
1502 const nir_const_value *null_value = nir_address_format_null_value(addr_format);
1503 memcpy(c->values, null_value,
1504 sizeof(nir_const_value) * nir_address_format_num_components(addr_format));
1505 break;
1506 }
1507
1508 case vtn_base_type_void:
1509 case vtn_base_type_image:
1510 case vtn_base_type_sampler:
1511 case vtn_base_type_sampled_image:
1512 case vtn_base_type_function:
1513 /* For those we have to return something but it doesn't matter what. */
1514 break;
1515
1516 case vtn_base_type_matrix:
1517 case vtn_base_type_array:
1518 vtn_assert(type->length > 0);
1519 c->num_elements = type->length;
1520 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1521
1522 c->elements[0] = vtn_null_constant(b, type->array_element);
1523 for (unsigned i = 1; i < c->num_elements; i++)
1524 c->elements[i] = c->elements[0];
1525 break;
1526
1527 case vtn_base_type_struct:
1528 c->num_elements = type->length;
1529 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1530 for (unsigned i = 0; i < c->num_elements; i++)
1531 c->elements[i] = vtn_null_constant(b, type->members[i]);
1532 break;
1533
1534 default:
1535 vtn_fail("Invalid type for null constant");
1536 }
1537
1538 return c;
1539 }
1540
1541 static void
1542 spec_constant_decoration_cb(struct vtn_builder *b, UNUSED struct vtn_value *val,
1543 ASSERTED int member,
1544 const struct vtn_decoration *dec, void *data)
1545 {
1546 vtn_assert(member == -1);
1547 if (dec->decoration != SpvDecorationSpecId)
1548 return;
1549
1550 struct spec_constant_value *const_value = data;
1551
1552 for (unsigned i = 0; i < b->num_specializations; i++) {
1553 if (b->specializations[i].id == dec->operands[0]) {
1554 if (const_value->is_double)
1555 const_value->data64 = b->specializations[i].data64;
1556 else
1557 const_value->data32 = b->specializations[i].data32;
1558 return;
1559 }
1560 }
1561 }
1562
1563 static uint32_t
1564 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1565 uint32_t const_value)
1566 {
1567 struct spec_constant_value data;
1568 data.is_double = false;
1569 data.data32 = const_value;
1570 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1571 return data.data32;
1572 }
1573
1574 static uint64_t
1575 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1576 uint64_t const_value)
1577 {
1578 struct spec_constant_value data;
1579 data.is_double = true;
1580 data.data64 = const_value;
1581 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1582 return data.data64;
1583 }
1584
1585 static void
1586 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1587 struct vtn_value *val,
1588 ASSERTED int member,
1589 const struct vtn_decoration *dec,
1590 UNUSED void *data)
1591 {
1592 vtn_assert(member == -1);
1593 if (dec->decoration != SpvDecorationBuiltIn ||
1594 dec->operands[0] != SpvBuiltInWorkgroupSize)
1595 return;
1596
1597 vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1598 b->workgroup_size_builtin = val;
1599 }
1600
1601 static void
1602 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1603 const uint32_t *w, unsigned count)
1604 {
1605 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1606 val->constant = rzalloc(b, nir_constant);
1607 switch (opcode) {
1608 case SpvOpConstantTrue:
1609 case SpvOpConstantFalse:
1610 case SpvOpSpecConstantTrue:
1611 case SpvOpSpecConstantFalse: {
1612 vtn_fail_if(val->type->type != glsl_bool_type(),
1613 "Result type of %s must be OpTypeBool",
1614 spirv_op_to_string(opcode));
1615
1616 uint32_t int_val = (opcode == SpvOpConstantTrue ||
1617 opcode == SpvOpSpecConstantTrue);
1618
1619 if (opcode == SpvOpSpecConstantTrue ||
1620 opcode == SpvOpSpecConstantFalse)
1621 int_val = get_specialization(b, val, int_val);
1622
1623 val->constant->values[0].b = int_val != 0;
1624 break;
1625 }
1626
1627 case SpvOpConstant: {
1628 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1629 "Result type of %s must be a scalar",
1630 spirv_op_to_string(opcode));
1631 int bit_size = glsl_get_bit_size(val->type->type);
1632 switch (bit_size) {
1633 case 64:
1634 val->constant->values[0].u64 = vtn_u64_literal(&w[3]);
1635 break;
1636 case 32:
1637 val->constant->values[0].u32 = w[3];
1638 break;
1639 case 16:
1640 val->constant->values[0].u16 = w[3];
1641 break;
1642 case 8:
1643 val->constant->values[0].u8 = w[3];
1644 break;
1645 default:
1646 vtn_fail("Unsupported SpvOpConstant bit size: %u", bit_size);
1647 }
1648 break;
1649 }
1650
1651 case SpvOpSpecConstant: {
1652 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1653 "Result type of %s must be a scalar",
1654 spirv_op_to_string(opcode));
1655 int bit_size = glsl_get_bit_size(val->type->type);
1656 switch (bit_size) {
1657 case 64:
1658 val->constant->values[0].u64 =
1659 get_specialization64(b, val, vtn_u64_literal(&w[3]));
1660 break;
1661 case 32:
1662 val->constant->values[0].u32 = get_specialization(b, val, w[3]);
1663 break;
1664 case 16:
1665 val->constant->values[0].u16 = get_specialization(b, val, w[3]);
1666 break;
1667 case 8:
1668 val->constant->values[0].u8 = get_specialization(b, val, w[3]);
1669 break;
1670 default:
1671 vtn_fail("Unsupported SpvOpSpecConstant bit size");
1672 }
1673 break;
1674 }
1675
1676 case SpvOpSpecConstantComposite:
1677 case SpvOpConstantComposite: {
1678 unsigned elem_count = count - 3;
1679 vtn_fail_if(elem_count != val->type->length,
1680 "%s has %u constituents, expected %u",
1681 spirv_op_to_string(opcode), elem_count, val->type->length);
1682
1683 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1684 for (unsigned i = 0; i < elem_count; i++) {
1685 struct vtn_value *val = vtn_untyped_value(b, w[i + 3]);
1686
1687 if (val->value_type == vtn_value_type_constant) {
1688 elems[i] = val->constant;
1689 } else {
1690 vtn_fail_if(val->value_type != vtn_value_type_undef,
1691 "only constants or undefs allowed for "
1692 "SpvOpConstantComposite");
1693 /* to make it easier, just insert a NULL constant for now */
1694 elems[i] = vtn_null_constant(b, val->type);
1695 }
1696 }
1697
1698 switch (val->type->base_type) {
1699 case vtn_base_type_vector: {
1700 assert(glsl_type_is_vector(val->type->type));
1701 for (unsigned i = 0; i < elem_count; i++)
1702 val->constant->values[i] = elems[i]->values[0];
1703 break;
1704 }
1705
1706 case vtn_base_type_matrix:
1707 case vtn_base_type_struct:
1708 case vtn_base_type_array:
1709 ralloc_steal(val->constant, elems);
1710 val->constant->num_elements = elem_count;
1711 val->constant->elements = elems;
1712 break;
1713
1714 default:
1715 vtn_fail("Result type of %s must be a composite type",
1716 spirv_op_to_string(opcode));
1717 }
1718 break;
1719 }
1720
1721 case SpvOpSpecConstantOp: {
1722 SpvOp opcode = get_specialization(b, val, w[3]);
1723 switch (opcode) {
1724 case SpvOpVectorShuffle: {
1725 struct vtn_value *v0 = &b->values[w[4]];
1726 struct vtn_value *v1 = &b->values[w[5]];
1727
1728 vtn_assert(v0->value_type == vtn_value_type_constant ||
1729 v0->value_type == vtn_value_type_undef);
1730 vtn_assert(v1->value_type == vtn_value_type_constant ||
1731 v1->value_type == vtn_value_type_undef);
1732
1733 unsigned len0 = glsl_get_vector_elements(v0->type->type);
1734 unsigned len1 = glsl_get_vector_elements(v1->type->type);
1735
1736 vtn_assert(len0 + len1 < 16);
1737
1738 unsigned bit_size = glsl_get_bit_size(val->type->type);
1739 unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1740 unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1741
1742 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1743 (void)bit_size0; (void)bit_size1;
1744
1745 nir_const_value undef = { .u64 = 0xdeadbeefdeadbeef };
1746 nir_const_value combined[NIR_MAX_VEC_COMPONENTS * 2];
1747
1748 if (v0->value_type == vtn_value_type_constant) {
1749 for (unsigned i = 0; i < len0; i++)
1750 combined[i] = v0->constant->values[i];
1751 }
1752 if (v1->value_type == vtn_value_type_constant) {
1753 for (unsigned i = 0; i < len1; i++)
1754 combined[len0 + i] = v1->constant->values[i];
1755 }
1756
1757 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1758 uint32_t comp = w[i + 6];
1759 if (comp == (uint32_t)-1) {
1760 /* If component is not used, set the value to a known constant
1761 * to detect if it is wrongly used.
1762 */
1763 val->constant->values[j] = undef;
1764 } else {
1765 vtn_fail_if(comp >= len0 + len1,
1766 "All Component literals must either be FFFFFFFF "
1767 "or in [0, N - 1] (inclusive).");
1768 val->constant->values[j] = combined[comp];
1769 }
1770 }
1771 break;
1772 }
1773
1774 case SpvOpCompositeExtract:
1775 case SpvOpCompositeInsert: {
1776 struct vtn_value *comp;
1777 unsigned deref_start;
1778 struct nir_constant **c;
1779 if (opcode == SpvOpCompositeExtract) {
1780 comp = vtn_value(b, w[4], vtn_value_type_constant);
1781 deref_start = 5;
1782 c = &comp->constant;
1783 } else {
1784 comp = vtn_value(b, w[5], vtn_value_type_constant);
1785 deref_start = 6;
1786 val->constant = nir_constant_clone(comp->constant,
1787 (nir_variable *)b);
1788 c = &val->constant;
1789 }
1790
1791 int elem = -1;
1792 const struct vtn_type *type = comp->type;
1793 for (unsigned i = deref_start; i < count; i++) {
1794 vtn_fail_if(w[i] > type->length,
1795 "%uth index of %s is %u but the type has only "
1796 "%u elements", i - deref_start,
1797 spirv_op_to_string(opcode), w[i], type->length);
1798
1799 switch (type->base_type) {
1800 case vtn_base_type_vector:
1801 elem = w[i];
1802 type = type->array_element;
1803 break;
1804
1805 case vtn_base_type_matrix:
1806 case vtn_base_type_array:
1807 c = &(*c)->elements[w[i]];
1808 type = type->array_element;
1809 break;
1810
1811 case vtn_base_type_struct:
1812 c = &(*c)->elements[w[i]];
1813 type = type->members[w[i]];
1814 break;
1815
1816 default:
1817 vtn_fail("%s must only index into composite types",
1818 spirv_op_to_string(opcode));
1819 }
1820 }
1821
1822 if (opcode == SpvOpCompositeExtract) {
1823 if (elem == -1) {
1824 val->constant = *c;
1825 } else {
1826 unsigned num_components = type->length;
1827 for (unsigned i = 0; i < num_components; i++)
1828 val->constant->values[i] = (*c)->values[elem + i];
1829 }
1830 } else {
1831 struct vtn_value *insert =
1832 vtn_value(b, w[4], vtn_value_type_constant);
1833 vtn_assert(insert->type == type);
1834 if (elem == -1) {
1835 *c = insert->constant;
1836 } else {
1837 unsigned num_components = type->length;
1838 for (unsigned i = 0; i < num_components; i++)
1839 (*c)->values[elem + i] = insert->constant->values[i];
1840 }
1841 }
1842 break;
1843 }
1844
1845 default: {
1846 bool swap;
1847 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
1848 nir_alu_type src_alu_type = dst_alu_type;
1849 unsigned num_components = glsl_get_vector_elements(val->type->type);
1850 unsigned bit_size;
1851
1852 vtn_assert(count <= 7);
1853
1854 switch (opcode) {
1855 case SpvOpSConvert:
1856 case SpvOpFConvert:
1857 case SpvOpUConvert:
1858 /* We have a source in a conversion */
1859 src_alu_type =
1860 nir_get_nir_type_for_glsl_type(
1861 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1862 /* We use the bitsize of the conversion source to evaluate the opcode later */
1863 bit_size = glsl_get_bit_size(
1864 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1865 break;
1866 default:
1867 bit_size = glsl_get_bit_size(val->type->type);
1868 };
1869
1870 nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
1871 nir_alu_type_get_type_size(src_alu_type),
1872 nir_alu_type_get_type_size(dst_alu_type));
1873 nir_const_value src[3][NIR_MAX_VEC_COMPONENTS];
1874
1875 for (unsigned i = 0; i < count - 4; i++) {
1876 struct vtn_value *src_val =
1877 vtn_value(b, w[4 + i], vtn_value_type_constant);
1878
1879 /* If this is an unsized source, pull the bit size from the
1880 * source; otherwise, we'll use the bit size from the destination.
1881 */
1882 if (!nir_alu_type_get_type_size(nir_op_infos[op].input_types[i]))
1883 bit_size = glsl_get_bit_size(src_val->type->type);
1884
1885 unsigned src_comps = nir_op_infos[op].input_sizes[i] ?
1886 nir_op_infos[op].input_sizes[i] :
1887 num_components;
1888
1889 unsigned j = swap ? 1 - i : i;
1890 for (unsigned c = 0; c < src_comps; c++)
1891 src[j][c] = src_val->constant->values[c];
1892 }
1893
1894 /* fix up fixed size sources */
1895 switch (op) {
1896 case nir_op_ishl:
1897 case nir_op_ishr:
1898 case nir_op_ushr: {
1899 if (bit_size == 32)
1900 break;
1901 for (unsigned i = 0; i < num_components; ++i) {
1902 switch (bit_size) {
1903 case 64: src[1][i].u32 = src[1][i].u64; break;
1904 case 16: src[1][i].u32 = src[1][i].u16; break;
1905 case 8: src[1][i].u32 = src[1][i].u8; break;
1906 }
1907 }
1908 break;
1909 }
1910 default:
1911 break;
1912 }
1913
1914 nir_const_value *srcs[3] = {
1915 src[0], src[1], src[2],
1916 };
1917 nir_eval_const_opcode(op, val->constant->values,
1918 num_components, bit_size, srcs,
1919 b->shader->info.float_controls_execution_mode);
1920 break;
1921 } /* default */
1922 }
1923 break;
1924 }
1925
1926 case SpvOpConstantNull:
1927 val->constant = vtn_null_constant(b, val->type);
1928 break;
1929
1930 case SpvOpConstantSampler:
1931 vtn_fail("OpConstantSampler requires Kernel Capability");
1932 break;
1933
1934 default:
1935 vtn_fail_with_opcode("Unhandled opcode", opcode);
1936 }
1937
1938 /* Now that we have the value, update the workgroup size if needed */
1939 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1940 }
1941
1942 SpvMemorySemanticsMask
1943 vtn_storage_class_to_memory_semantics(SpvStorageClass sc)
1944 {
1945 switch (sc) {
1946 case SpvStorageClassStorageBuffer:
1947 case SpvStorageClassPhysicalStorageBuffer:
1948 return SpvMemorySemanticsUniformMemoryMask;
1949 case SpvStorageClassWorkgroup:
1950 return SpvMemorySemanticsWorkgroupMemoryMask;
1951 default:
1952 return SpvMemorySemanticsMaskNone;
1953 }
1954 }
1955
1956 static void
1957 vtn_split_barrier_semantics(struct vtn_builder *b,
1958 SpvMemorySemanticsMask semantics,
1959 SpvMemorySemanticsMask *before,
1960 SpvMemorySemanticsMask *after)
1961 {
1962 /* For memory semantics embedded in operations, we split them into up to
1963 * two barriers, to be added before and after the operation. This is less
1964 * strict than if we propagated until the final backend stage, but still
1965 * result in correct execution.
1966 *
1967 * A further improvement could be pipe this information (and use!) into the
1968 * next compiler layers, at the expense of making the handling of barriers
1969 * more complicated.
1970 */
1971
1972 *before = SpvMemorySemanticsMaskNone;
1973 *after = SpvMemorySemanticsMaskNone;
1974
1975 SpvMemorySemanticsMask order_semantics =
1976 semantics & (SpvMemorySemanticsAcquireMask |
1977 SpvMemorySemanticsReleaseMask |
1978 SpvMemorySemanticsAcquireReleaseMask |
1979 SpvMemorySemanticsSequentiallyConsistentMask);
1980
1981 if (util_bitcount(order_semantics) > 1) {
1982 /* Old GLSLang versions incorrectly set all the ordering bits. This was
1983 * fixed in c51287d744fb6e7e9ccc09f6f8451e6c64b1dad6 of glslang repo,
1984 * and it is in GLSLang since revision "SPIRV99.1321" (from Jul-2016).
1985 */
1986 vtn_warn("Multiple memory ordering semantics specified, "
1987 "assuming AcquireRelease.");
1988 order_semantics = SpvMemorySemanticsAcquireReleaseMask;
1989 }
1990
1991 const SpvMemorySemanticsMask av_vis_semantics =
1992 semantics & (SpvMemorySemanticsMakeAvailableMask |
1993 SpvMemorySemanticsMakeVisibleMask);
1994
1995 const SpvMemorySemanticsMask storage_semantics =
1996 semantics & (SpvMemorySemanticsUniformMemoryMask |
1997 SpvMemorySemanticsSubgroupMemoryMask |
1998 SpvMemorySemanticsWorkgroupMemoryMask |
1999 SpvMemorySemanticsCrossWorkgroupMemoryMask |
2000 SpvMemorySemanticsAtomicCounterMemoryMask |
2001 SpvMemorySemanticsImageMemoryMask |
2002 SpvMemorySemanticsOutputMemoryMask);
2003
2004 const SpvMemorySemanticsMask other_semantics =
2005 semantics & ~(order_semantics | av_vis_semantics | storage_semantics);
2006
2007 if (other_semantics)
2008 vtn_warn("Ignoring unhandled memory semantics: %u\n", other_semantics);
2009
2010 /* SequentiallyConsistent is treated as AcquireRelease. */
2011
2012 /* The RELEASE barrier happens BEFORE the operation, and it is usually
2013 * associated with a Store. All the write operations with a matching
2014 * semantics will not be reordered after the Store.
2015 */
2016 if (order_semantics & (SpvMemorySemanticsReleaseMask |
2017 SpvMemorySemanticsAcquireReleaseMask |
2018 SpvMemorySemanticsSequentiallyConsistentMask)) {
2019 *before |= SpvMemorySemanticsReleaseMask | storage_semantics;
2020 }
2021
2022 /* The ACQUIRE barrier happens AFTER the operation, and it is usually
2023 * associated with a Load. All the operations with a matching semantics
2024 * will not be reordered before the Load.
2025 */
2026 if (order_semantics & (SpvMemorySemanticsAcquireMask |
2027 SpvMemorySemanticsAcquireReleaseMask |
2028 SpvMemorySemanticsSequentiallyConsistentMask)) {
2029 *after |= SpvMemorySemanticsAcquireMask | storage_semantics;
2030 }
2031
2032 if (av_vis_semantics & SpvMemorySemanticsMakeVisibleMask)
2033 *before |= SpvMemorySemanticsMakeVisibleMask | storage_semantics;
2034
2035 if (av_vis_semantics & SpvMemorySemanticsMakeAvailableMask)
2036 *after |= SpvMemorySemanticsMakeAvailableMask | storage_semantics;
2037 }
2038
2039 static void
2040 vtn_emit_scoped_memory_barrier(struct vtn_builder *b, SpvScope scope,
2041 SpvMemorySemanticsMask semantics)
2042 {
2043 nir_memory_semantics nir_semantics = 0;
2044
2045 SpvMemorySemanticsMask order_semantics =
2046 semantics & (SpvMemorySemanticsAcquireMask |
2047 SpvMemorySemanticsReleaseMask |
2048 SpvMemorySemanticsAcquireReleaseMask |
2049 SpvMemorySemanticsSequentiallyConsistentMask);
2050
2051 if (util_bitcount(order_semantics) > 1) {
2052 /* Old GLSLang versions incorrectly set all the ordering bits. This was
2053 * fixed in c51287d744fb6e7e9ccc09f6f8451e6c64b1dad6 of glslang repo,
2054 * and it is in GLSLang since revision "SPIRV99.1321" (from Jul-2016).
2055 */
2056 vtn_warn("Multiple memory ordering semantics bits specified, "
2057 "assuming AcquireRelease.");
2058 order_semantics = SpvMemorySemanticsAcquireReleaseMask;
2059 }
2060
2061 switch (order_semantics) {
2062 case 0:
2063 /* Not an ordering barrier. */
2064 break;
2065
2066 case SpvMemorySemanticsAcquireMask:
2067 nir_semantics = NIR_MEMORY_ACQUIRE;
2068 break;
2069
2070 case SpvMemorySemanticsReleaseMask:
2071 nir_semantics = NIR_MEMORY_RELEASE;
2072 break;
2073
2074 case SpvMemorySemanticsSequentiallyConsistentMask:
2075 /* Fall through. Treated as AcquireRelease in Vulkan. */
2076 case SpvMemorySemanticsAcquireReleaseMask:
2077 nir_semantics = NIR_MEMORY_ACQUIRE | NIR_MEMORY_RELEASE;
2078 break;
2079
2080 default:
2081 unreachable("Invalid memory order semantics");
2082 }
2083
2084 if (semantics & SpvMemorySemanticsMakeAvailableMask) {
2085 vtn_fail_if(!b->options->caps.vk_memory_model,
2086 "To use MakeAvailable memory semantics the VulkanMemoryModel "
2087 "capability must be declared.");
2088 nir_semantics |= NIR_MEMORY_MAKE_AVAILABLE;
2089 }
2090
2091 if (semantics & SpvMemorySemanticsMakeVisibleMask) {
2092 vtn_fail_if(!b->options->caps.vk_memory_model,
2093 "To use MakeVisible memory semantics the VulkanMemoryModel "
2094 "capability must be declared.");
2095 nir_semantics |= NIR_MEMORY_MAKE_VISIBLE;
2096 }
2097
2098 /* Vulkan Environment for SPIR-V says "SubgroupMemory, CrossWorkgroupMemory,
2099 * and AtomicCounterMemory are ignored".
2100 */
2101 semantics &= ~(SpvMemorySemanticsSubgroupMemoryMask |
2102 SpvMemorySemanticsCrossWorkgroupMemoryMask |
2103 SpvMemorySemanticsAtomicCounterMemoryMask);
2104
2105 /* TODO: Consider adding nir_var_mem_image mode to NIR so it can be used
2106 * for SpvMemorySemanticsImageMemoryMask.
2107 */
2108
2109 nir_variable_mode modes = 0;
2110 if (semantics & (SpvMemorySemanticsUniformMemoryMask |
2111 SpvMemorySemanticsImageMemoryMask)) {
2112 modes |= nir_var_uniform |
2113 nir_var_mem_ubo |
2114 nir_var_mem_ssbo |
2115 nir_var_mem_global;
2116 }
2117 if (semantics & SpvMemorySemanticsWorkgroupMemoryMask)
2118 modes |= nir_var_mem_shared;
2119 if (semantics & SpvMemorySemanticsOutputMemoryMask) {
2120 modes |= nir_var_shader_out;
2121 }
2122
2123 /* No barrier to add. */
2124 if (nir_semantics == 0 || modes == 0)
2125 return;
2126
2127 nir_scope nir_scope;
2128 switch (scope) {
2129 case SpvScopeDevice:
2130 vtn_fail_if(b->options->caps.vk_memory_model &&
2131 !b->options->caps.vk_memory_model_device_scope,
2132 "If the Vulkan memory model is declared and any instruction "
2133 "uses Device scope, the VulkanMemoryModelDeviceScope "
2134 "capability must be declared.");
2135 nir_scope = NIR_SCOPE_DEVICE;
2136 break;
2137
2138 case SpvScopeQueueFamily:
2139 vtn_fail_if(!b->options->caps.vk_memory_model,
2140 "To use Queue Family scope, the VulkanMemoryModel capability "
2141 "must be declared.");
2142 nir_scope = NIR_SCOPE_QUEUE_FAMILY;
2143 break;
2144
2145 case SpvScopeWorkgroup:
2146 nir_scope = NIR_SCOPE_WORKGROUP;
2147 break;
2148
2149 case SpvScopeSubgroup:
2150 nir_scope = NIR_SCOPE_SUBGROUP;
2151 break;
2152
2153 case SpvScopeInvocation:
2154 nir_scope = NIR_SCOPE_INVOCATION;
2155 break;
2156
2157 default:
2158 vtn_fail("Invalid memory scope");
2159 }
2160
2161 nir_intrinsic_instr *intrin =
2162 nir_intrinsic_instr_create(b->shader, nir_intrinsic_scoped_memory_barrier);
2163 nir_intrinsic_set_memory_semantics(intrin, nir_semantics);
2164
2165 nir_intrinsic_set_memory_modes(intrin, modes);
2166 nir_intrinsic_set_memory_scope(intrin, nir_scope);
2167 nir_builder_instr_insert(&b->nb, &intrin->instr);
2168 }
2169
2170 struct vtn_ssa_value *
2171 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
2172 {
2173 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
2174 val->type = type;
2175
2176 if (!glsl_type_is_vector_or_scalar(type)) {
2177 unsigned elems = glsl_get_length(type);
2178 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2179 for (unsigned i = 0; i < elems; i++) {
2180 const struct glsl_type *child_type;
2181
2182 switch (glsl_get_base_type(type)) {
2183 case GLSL_TYPE_INT:
2184 case GLSL_TYPE_UINT:
2185 case GLSL_TYPE_INT16:
2186 case GLSL_TYPE_UINT16:
2187 case GLSL_TYPE_UINT8:
2188 case GLSL_TYPE_INT8:
2189 case GLSL_TYPE_INT64:
2190 case GLSL_TYPE_UINT64:
2191 case GLSL_TYPE_BOOL:
2192 case GLSL_TYPE_FLOAT:
2193 case GLSL_TYPE_FLOAT16:
2194 case GLSL_TYPE_DOUBLE:
2195 child_type = glsl_get_column_type(type);
2196 break;
2197 case GLSL_TYPE_ARRAY:
2198 child_type = glsl_get_array_element(type);
2199 break;
2200 case GLSL_TYPE_STRUCT:
2201 case GLSL_TYPE_INTERFACE:
2202 child_type = glsl_get_struct_field(type, i);
2203 break;
2204 default:
2205 vtn_fail("unkown base type");
2206 }
2207
2208 val->elems[i] = vtn_create_ssa_value(b, child_type);
2209 }
2210 }
2211
2212 return val;
2213 }
2214
2215 static nir_tex_src
2216 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
2217 {
2218 nir_tex_src src;
2219 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
2220 src.src_type = type;
2221 return src;
2222 }
2223
2224 static uint32_t
2225 image_operand_arg(struct vtn_builder *b, const uint32_t *w, uint32_t count,
2226 uint32_t mask_idx, SpvImageOperandsMask op)
2227 {
2228 static const SpvImageOperandsMask ops_with_arg =
2229 SpvImageOperandsBiasMask |
2230 SpvImageOperandsLodMask |
2231 SpvImageOperandsGradMask |
2232 SpvImageOperandsConstOffsetMask |
2233 SpvImageOperandsOffsetMask |
2234 SpvImageOperandsConstOffsetsMask |
2235 SpvImageOperandsSampleMask |
2236 SpvImageOperandsMinLodMask |
2237 SpvImageOperandsMakeTexelAvailableMask |
2238 SpvImageOperandsMakeTexelVisibleMask;
2239
2240 assert(util_bitcount(op) == 1);
2241 assert(w[mask_idx] & op);
2242 assert(op & ops_with_arg);
2243
2244 uint32_t idx = util_bitcount(w[mask_idx] & (op - 1) & ops_with_arg) + 1;
2245
2246 /* Adjust indices for operands with two arguments. */
2247 static const SpvImageOperandsMask ops_with_two_args =
2248 SpvImageOperandsGradMask;
2249 idx += util_bitcount(w[mask_idx] & (op - 1) & ops_with_two_args);
2250
2251 idx += mask_idx;
2252
2253 vtn_fail_if(idx + (op & ops_with_two_args ? 1 : 0) >= count,
2254 "Image op claims to have %s but does not enough "
2255 "following operands", spirv_imageoperands_to_string(op));
2256
2257 return idx;
2258 }
2259
2260 static void
2261 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
2262 const uint32_t *w, unsigned count)
2263 {
2264 if (opcode == SpvOpSampledImage) {
2265 struct vtn_value *val =
2266 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
2267 val->sampled_image = ralloc(b, struct vtn_sampled_image);
2268 val->sampled_image->image =
2269 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2270 val->sampled_image->sampler =
2271 vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
2272 return;
2273 } else if (opcode == SpvOpImage) {
2274 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
2275 if (src_val->value_type == vtn_value_type_sampled_image) {
2276 vtn_push_value_pointer(b, w[2], src_val->sampled_image->image);
2277 } else {
2278 vtn_assert(src_val->value_type == vtn_value_type_pointer);
2279 vtn_push_value_pointer(b, w[2], src_val->pointer);
2280 }
2281 return;
2282 }
2283
2284 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
2285
2286 struct vtn_pointer *image = NULL, *sampler = NULL;
2287 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
2288 if (sampled_val->value_type == vtn_value_type_sampled_image) {
2289 image = sampled_val->sampled_image->image;
2290 sampler = sampled_val->sampled_image->sampler;
2291 } else {
2292 vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
2293 image = sampled_val->pointer;
2294 }
2295
2296 nir_deref_instr *image_deref = vtn_pointer_to_deref(b, image);
2297 nir_deref_instr *sampler_deref =
2298 sampler ? vtn_pointer_to_deref(b, sampler) : NULL;
2299
2300 const struct glsl_type *image_type = sampled_val->type->type;
2301 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
2302 const bool is_array = glsl_sampler_type_is_array(image_type);
2303 nir_alu_type dest_type = nir_type_invalid;
2304
2305 /* Figure out the base texture operation */
2306 nir_texop texop;
2307 switch (opcode) {
2308 case SpvOpImageSampleImplicitLod:
2309 case SpvOpImageSampleDrefImplicitLod:
2310 case SpvOpImageSampleProjImplicitLod:
2311 case SpvOpImageSampleProjDrefImplicitLod:
2312 texop = nir_texop_tex;
2313 break;
2314
2315 case SpvOpImageSampleExplicitLod:
2316 case SpvOpImageSampleDrefExplicitLod:
2317 case SpvOpImageSampleProjExplicitLod:
2318 case SpvOpImageSampleProjDrefExplicitLod:
2319 texop = nir_texop_txl;
2320 break;
2321
2322 case SpvOpImageFetch:
2323 if (sampler_dim == GLSL_SAMPLER_DIM_MS) {
2324 texop = nir_texop_txf_ms;
2325 } else {
2326 texop = nir_texop_txf;
2327 }
2328 break;
2329
2330 case SpvOpImageGather:
2331 case SpvOpImageDrefGather:
2332 texop = nir_texop_tg4;
2333 break;
2334
2335 case SpvOpImageQuerySizeLod:
2336 case SpvOpImageQuerySize:
2337 texop = nir_texop_txs;
2338 dest_type = nir_type_int;
2339 break;
2340
2341 case SpvOpImageQueryLod:
2342 texop = nir_texop_lod;
2343 dest_type = nir_type_float;
2344 break;
2345
2346 case SpvOpImageQueryLevels:
2347 texop = nir_texop_query_levels;
2348 dest_type = nir_type_int;
2349 break;
2350
2351 case SpvOpImageQuerySamples:
2352 texop = nir_texop_texture_samples;
2353 dest_type = nir_type_int;
2354 break;
2355
2356 case SpvOpFragmentFetchAMD:
2357 texop = nir_texop_fragment_fetch;
2358 break;
2359
2360 case SpvOpFragmentMaskFetchAMD:
2361 texop = nir_texop_fragment_mask_fetch;
2362 break;
2363
2364 default:
2365 vtn_fail_with_opcode("Unhandled opcode", opcode);
2366 }
2367
2368 nir_tex_src srcs[10]; /* 10 should be enough */
2369 nir_tex_src *p = srcs;
2370
2371 p->src = nir_src_for_ssa(&image_deref->dest.ssa);
2372 p->src_type = nir_tex_src_texture_deref;
2373 p++;
2374
2375 switch (texop) {
2376 case nir_texop_tex:
2377 case nir_texop_txb:
2378 case nir_texop_txl:
2379 case nir_texop_txd:
2380 case nir_texop_tg4:
2381 case nir_texop_lod:
2382 vtn_fail_if(sampler == NULL,
2383 "%s requires an image of type OpTypeSampledImage",
2384 spirv_op_to_string(opcode));
2385 p->src = nir_src_for_ssa(&sampler_deref->dest.ssa);
2386 p->src_type = nir_tex_src_sampler_deref;
2387 p++;
2388 break;
2389 case nir_texop_txf:
2390 case nir_texop_txf_ms:
2391 case nir_texop_txs:
2392 case nir_texop_query_levels:
2393 case nir_texop_texture_samples:
2394 case nir_texop_samples_identical:
2395 case nir_texop_fragment_fetch:
2396 case nir_texop_fragment_mask_fetch:
2397 /* These don't */
2398 break;
2399 case nir_texop_txf_ms_fb:
2400 vtn_fail("unexpected nir_texop_txf_ms_fb");
2401 break;
2402 case nir_texop_txf_ms_mcs:
2403 vtn_fail("unexpected nir_texop_txf_ms_mcs");
2404 case nir_texop_tex_prefetch:
2405 vtn_fail("unexpected nir_texop_tex_prefetch");
2406 }
2407
2408 unsigned idx = 4;
2409
2410 struct nir_ssa_def *coord;
2411 unsigned coord_components;
2412 switch (opcode) {
2413 case SpvOpImageSampleImplicitLod:
2414 case SpvOpImageSampleExplicitLod:
2415 case SpvOpImageSampleDrefImplicitLod:
2416 case SpvOpImageSampleDrefExplicitLod:
2417 case SpvOpImageSampleProjImplicitLod:
2418 case SpvOpImageSampleProjExplicitLod:
2419 case SpvOpImageSampleProjDrefImplicitLod:
2420 case SpvOpImageSampleProjDrefExplicitLod:
2421 case SpvOpImageFetch:
2422 case SpvOpImageGather:
2423 case SpvOpImageDrefGather:
2424 case SpvOpImageQueryLod:
2425 case SpvOpFragmentFetchAMD:
2426 case SpvOpFragmentMaskFetchAMD: {
2427 /* All these types have the coordinate as their first real argument */
2428 coord_components = glsl_get_sampler_dim_coordinate_components(sampler_dim);
2429
2430 if (is_array && texop != nir_texop_lod)
2431 coord_components++;
2432
2433 coord = vtn_ssa_value(b, w[idx++])->def;
2434 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
2435 (1 << coord_components) - 1));
2436 p->src_type = nir_tex_src_coord;
2437 p++;
2438 break;
2439 }
2440
2441 default:
2442 coord = NULL;
2443 coord_components = 0;
2444 break;
2445 }
2446
2447 switch (opcode) {
2448 case SpvOpImageSampleProjImplicitLod:
2449 case SpvOpImageSampleProjExplicitLod:
2450 case SpvOpImageSampleProjDrefImplicitLod:
2451 case SpvOpImageSampleProjDrefExplicitLod:
2452 /* These have the projector as the last coordinate component */
2453 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
2454 p->src_type = nir_tex_src_projector;
2455 p++;
2456 break;
2457
2458 default:
2459 break;
2460 }
2461
2462 bool is_shadow = false;
2463 unsigned gather_component = 0;
2464 switch (opcode) {
2465 case SpvOpImageSampleDrefImplicitLod:
2466 case SpvOpImageSampleDrefExplicitLod:
2467 case SpvOpImageSampleProjDrefImplicitLod:
2468 case SpvOpImageSampleProjDrefExplicitLod:
2469 case SpvOpImageDrefGather:
2470 /* These all have an explicit depth value as their next source */
2471 is_shadow = true;
2472 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2473 break;
2474
2475 case SpvOpImageGather:
2476 /* This has a component as its next source */
2477 gather_component = vtn_constant_uint(b, w[idx++]);
2478 break;
2479
2480 default:
2481 break;
2482 }
2483
2484 /* For OpImageQuerySizeLod, we always have an LOD */
2485 if (opcode == SpvOpImageQuerySizeLod)
2486 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2487
2488 /* For OpFragmentFetchAMD, we always have a multisample index */
2489 if (opcode == SpvOpFragmentFetchAMD)
2490 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2491
2492 /* Now we need to handle some number of optional arguments */
2493 struct vtn_value *gather_offsets = NULL;
2494 if (idx < count) {
2495 uint32_t operands = w[idx];
2496
2497 if (operands & SpvImageOperandsBiasMask) {
2498 vtn_assert(texop == nir_texop_tex);
2499 texop = nir_texop_txb;
2500 uint32_t arg = image_operand_arg(b, w, count, idx,
2501 SpvImageOperandsBiasMask);
2502 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_bias);
2503 }
2504
2505 if (operands & SpvImageOperandsLodMask) {
2506 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2507 texop == nir_texop_txs);
2508 uint32_t arg = image_operand_arg(b, w, count, idx,
2509 SpvImageOperandsLodMask);
2510 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_lod);
2511 }
2512
2513 if (operands & SpvImageOperandsGradMask) {
2514 vtn_assert(texop == nir_texop_txl);
2515 texop = nir_texop_txd;
2516 uint32_t arg = image_operand_arg(b, w, count, idx,
2517 SpvImageOperandsGradMask);
2518 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_ddx);
2519 (*p++) = vtn_tex_src(b, w[arg + 1], nir_tex_src_ddy);
2520 }
2521
2522 vtn_fail_if(util_bitcount(operands & (SpvImageOperandsConstOffsetsMask |
2523 SpvImageOperandsOffsetMask |
2524 SpvImageOperandsConstOffsetMask)) > 1,
2525 "At most one of the ConstOffset, Offset, and ConstOffsets "
2526 "image operands can be used on a given instruction.");
2527
2528 if (operands & SpvImageOperandsOffsetMask) {
2529 uint32_t arg = image_operand_arg(b, w, count, idx,
2530 SpvImageOperandsOffsetMask);
2531 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_offset);
2532 }
2533
2534 if (operands & SpvImageOperandsConstOffsetMask) {
2535 uint32_t arg = image_operand_arg(b, w, count, idx,
2536 SpvImageOperandsConstOffsetMask);
2537 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_offset);
2538 }
2539
2540 if (operands & SpvImageOperandsConstOffsetsMask) {
2541 vtn_assert(texop == nir_texop_tg4);
2542 uint32_t arg = image_operand_arg(b, w, count, idx,
2543 SpvImageOperandsConstOffsetsMask);
2544 gather_offsets = vtn_value(b, w[arg], vtn_value_type_constant);
2545 }
2546
2547 if (operands & SpvImageOperandsSampleMask) {
2548 vtn_assert(texop == nir_texop_txf_ms);
2549 uint32_t arg = image_operand_arg(b, w, count, idx,
2550 SpvImageOperandsSampleMask);
2551 texop = nir_texop_txf_ms;
2552 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_ms_index);
2553 }
2554
2555 if (operands & SpvImageOperandsMinLodMask) {
2556 vtn_assert(texop == nir_texop_tex ||
2557 texop == nir_texop_txb ||
2558 texop == nir_texop_txd);
2559 uint32_t arg = image_operand_arg(b, w, count, idx,
2560 SpvImageOperandsMinLodMask);
2561 (*p++) = vtn_tex_src(b, w[arg], nir_tex_src_min_lod);
2562 }
2563 }
2564
2565 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2566 instr->op = texop;
2567
2568 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2569
2570 instr->coord_components = coord_components;
2571 instr->sampler_dim = sampler_dim;
2572 instr->is_array = is_array;
2573 instr->is_shadow = is_shadow;
2574 instr->is_new_style_shadow =
2575 is_shadow && glsl_get_components(ret_type->type) == 1;
2576 instr->component = gather_component;
2577
2578 if (image && (image->access & ACCESS_NON_UNIFORM))
2579 instr->texture_non_uniform = true;
2580
2581 if (sampler && (sampler->access & ACCESS_NON_UNIFORM))
2582 instr->sampler_non_uniform = true;
2583
2584 /* for non-query ops, get dest_type from sampler type */
2585 if (dest_type == nir_type_invalid) {
2586 switch (glsl_get_sampler_result_type(image_type)) {
2587 case GLSL_TYPE_FLOAT: dest_type = nir_type_float; break;
2588 case GLSL_TYPE_INT: dest_type = nir_type_int; break;
2589 case GLSL_TYPE_UINT: dest_type = nir_type_uint; break;
2590 case GLSL_TYPE_BOOL: dest_type = nir_type_bool; break;
2591 default:
2592 vtn_fail("Invalid base type for sampler result");
2593 }
2594 }
2595
2596 instr->dest_type = dest_type;
2597
2598 nir_ssa_dest_init(&instr->instr, &instr->dest,
2599 nir_tex_instr_dest_size(instr), 32, NULL);
2600
2601 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2602 nir_tex_instr_dest_size(instr));
2603
2604 if (gather_offsets) {
2605 vtn_fail_if(gather_offsets->type->base_type != vtn_base_type_array ||
2606 gather_offsets->type->length != 4,
2607 "ConstOffsets must be an array of size four of vectors "
2608 "of two integer components");
2609
2610 struct vtn_type *vec_type = gather_offsets->type->array_element;
2611 vtn_fail_if(vec_type->base_type != vtn_base_type_vector ||
2612 vec_type->length != 2 ||
2613 !glsl_type_is_integer(vec_type->type),
2614 "ConstOffsets must be an array of size four of vectors "
2615 "of two integer components");
2616
2617 unsigned bit_size = glsl_get_bit_size(vec_type->type);
2618 for (uint32_t i = 0; i < 4; i++) {
2619 const nir_const_value *cvec =
2620 gather_offsets->constant->elements[i]->values;
2621 for (uint32_t j = 0; j < 2; j++) {
2622 switch (bit_size) {
2623 case 8: instr->tg4_offsets[i][j] = cvec[j].i8; break;
2624 case 16: instr->tg4_offsets[i][j] = cvec[j].i16; break;
2625 case 32: instr->tg4_offsets[i][j] = cvec[j].i32; break;
2626 case 64: instr->tg4_offsets[i][j] = cvec[j].i64; break;
2627 default:
2628 vtn_fail("Unsupported bit size: %u", bit_size);
2629 }
2630 }
2631 }
2632 }
2633
2634 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, ret_type->type);
2635 ssa->def = &instr->dest.ssa;
2636 vtn_push_ssa(b, w[2], ret_type, ssa);
2637
2638 nir_builder_instr_insert(&b->nb, &instr->instr);
2639 }
2640
2641 static void
2642 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2643 const uint32_t *w, nir_src *src)
2644 {
2645 switch (opcode) {
2646 case SpvOpAtomicIIncrement:
2647 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2648 break;
2649
2650 case SpvOpAtomicIDecrement:
2651 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2652 break;
2653
2654 case SpvOpAtomicISub:
2655 src[0] =
2656 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
2657 break;
2658
2659 case SpvOpAtomicCompareExchange:
2660 case SpvOpAtomicCompareExchangeWeak:
2661 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
2662 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
2663 break;
2664
2665 case SpvOpAtomicExchange:
2666 case SpvOpAtomicIAdd:
2667 case SpvOpAtomicSMin:
2668 case SpvOpAtomicUMin:
2669 case SpvOpAtomicSMax:
2670 case SpvOpAtomicUMax:
2671 case SpvOpAtomicAnd:
2672 case SpvOpAtomicOr:
2673 case SpvOpAtomicXor:
2674 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
2675 break;
2676
2677 default:
2678 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
2679 }
2680 }
2681
2682 static nir_ssa_def *
2683 get_image_coord(struct vtn_builder *b, uint32_t value)
2684 {
2685 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
2686
2687 /* The image_load_store intrinsics assume a 4-dim coordinate */
2688 unsigned dim = glsl_get_vector_elements(coord->type);
2689 unsigned swizzle[4];
2690 for (unsigned i = 0; i < 4; i++)
2691 swizzle[i] = MIN2(i, dim - 1);
2692
2693 return nir_swizzle(&b->nb, coord->def, swizzle, 4);
2694 }
2695
2696 static nir_ssa_def *
2697 expand_to_vec4(nir_builder *b, nir_ssa_def *value)
2698 {
2699 if (value->num_components == 4)
2700 return value;
2701
2702 unsigned swiz[4];
2703 for (unsigned i = 0; i < 4; i++)
2704 swiz[i] = i < value->num_components ? i : 0;
2705 return nir_swizzle(b, value, swiz, 4);
2706 }
2707
2708 static void
2709 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2710 const uint32_t *w, unsigned count)
2711 {
2712 /* Just get this one out of the way */
2713 if (opcode == SpvOpImageTexelPointer) {
2714 struct vtn_value *val =
2715 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2716 val->image = ralloc(b, struct vtn_image_pointer);
2717
2718 val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2719 val->image->coord = get_image_coord(b, w[4]);
2720 val->image->sample = vtn_ssa_value(b, w[5])->def;
2721 val->image->lod = nir_imm_int(&b->nb, 0);
2722 return;
2723 }
2724
2725 struct vtn_image_pointer image;
2726 SpvScope scope = SpvScopeInvocation;
2727 SpvMemorySemanticsMask semantics = 0;
2728
2729 switch (opcode) {
2730 case SpvOpAtomicExchange:
2731 case SpvOpAtomicCompareExchange:
2732 case SpvOpAtomicCompareExchangeWeak:
2733 case SpvOpAtomicIIncrement:
2734 case SpvOpAtomicIDecrement:
2735 case SpvOpAtomicIAdd:
2736 case SpvOpAtomicISub:
2737 case SpvOpAtomicLoad:
2738 case SpvOpAtomicSMin:
2739 case SpvOpAtomicUMin:
2740 case SpvOpAtomicSMax:
2741 case SpvOpAtomicUMax:
2742 case SpvOpAtomicAnd:
2743 case SpvOpAtomicOr:
2744 case SpvOpAtomicXor:
2745 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2746 scope = vtn_constant_uint(b, w[4]);
2747 semantics = vtn_constant_uint(b, w[5]);
2748 break;
2749
2750 case SpvOpAtomicStore:
2751 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2752 scope = vtn_constant_uint(b, w[2]);
2753 semantics = vtn_constant_uint(b, w[3]);
2754 break;
2755
2756 case SpvOpImageQuerySize:
2757 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2758 image.coord = NULL;
2759 image.sample = NULL;
2760 image.lod = NULL;
2761 break;
2762
2763 case SpvOpImageRead: {
2764 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2765 image.coord = get_image_coord(b, w[4]);
2766
2767 const SpvImageOperandsMask operands =
2768 count > 5 ? w[5] : SpvImageOperandsMaskNone;
2769
2770 if (operands & SpvImageOperandsSampleMask) {
2771 uint32_t arg = image_operand_arg(b, w, count, 5,
2772 SpvImageOperandsSampleMask);
2773 image.sample = vtn_ssa_value(b, w[arg])->def;
2774 } else {
2775 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2776 }
2777
2778 if (operands & SpvImageOperandsMakeTexelVisibleMask) {
2779 vtn_fail_if((operands & SpvImageOperandsNonPrivateTexelMask) == 0,
2780 "MakeTexelVisible requires NonPrivateTexel to also be set.");
2781 uint32_t arg = image_operand_arg(b, w, count, 5,
2782 SpvImageOperandsMakeTexelVisibleMask);
2783 semantics = SpvMemorySemanticsMakeVisibleMask;
2784 scope = vtn_constant_uint(b, w[arg]);
2785 }
2786
2787 if (operands & SpvImageOperandsLodMask) {
2788 uint32_t arg = image_operand_arg(b, w, count, 5,
2789 SpvImageOperandsLodMask);
2790 image.lod = vtn_ssa_value(b, w[arg])->def;
2791 } else {
2792 image.lod = nir_imm_int(&b->nb, 0);
2793 }
2794
2795 /* TODO: Volatile. */
2796
2797 break;
2798 }
2799
2800 case SpvOpImageWrite: {
2801 image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2802 image.coord = get_image_coord(b, w[2]);
2803
2804 /* texel = w[3] */
2805
2806 const SpvImageOperandsMask operands =
2807 count > 4 ? w[4] : SpvImageOperandsMaskNone;
2808
2809 if (operands & SpvImageOperandsSampleMask) {
2810 uint32_t arg = image_operand_arg(b, w, count, 4,
2811 SpvImageOperandsSampleMask);
2812 image.sample = vtn_ssa_value(b, w[arg])->def;
2813 } else {
2814 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2815 }
2816
2817 if (operands & SpvImageOperandsMakeTexelAvailableMask) {
2818 vtn_fail_if((operands & SpvImageOperandsNonPrivateTexelMask) == 0,
2819 "MakeTexelAvailable requires NonPrivateTexel to also be set.");
2820 uint32_t arg = image_operand_arg(b, w, count, 4,
2821 SpvImageOperandsMakeTexelAvailableMask);
2822 semantics = SpvMemorySemanticsMakeAvailableMask;
2823 scope = vtn_constant_uint(b, w[arg]);
2824 }
2825
2826 if (operands & SpvImageOperandsLodMask) {
2827 uint32_t arg = image_operand_arg(b, w, count, 4,
2828 SpvImageOperandsLodMask);
2829 image.lod = vtn_ssa_value(b, w[arg])->def;
2830 } else {
2831 image.lod = nir_imm_int(&b->nb, 0);
2832 }
2833
2834 /* TODO: Volatile. */
2835
2836 break;
2837 }
2838
2839 default:
2840 vtn_fail_with_opcode("Invalid image opcode", opcode);
2841 }
2842
2843 nir_intrinsic_op op;
2844 switch (opcode) {
2845 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_deref_##N; break;
2846 OP(ImageQuerySize, size)
2847 OP(ImageRead, load)
2848 OP(ImageWrite, store)
2849 OP(AtomicLoad, load)
2850 OP(AtomicStore, store)
2851 OP(AtomicExchange, atomic_exchange)
2852 OP(AtomicCompareExchange, atomic_comp_swap)
2853 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
2854 OP(AtomicIIncrement, atomic_add)
2855 OP(AtomicIDecrement, atomic_add)
2856 OP(AtomicIAdd, atomic_add)
2857 OP(AtomicISub, atomic_add)
2858 OP(AtomicSMin, atomic_imin)
2859 OP(AtomicUMin, atomic_umin)
2860 OP(AtomicSMax, atomic_imax)
2861 OP(AtomicUMax, atomic_umax)
2862 OP(AtomicAnd, atomic_and)
2863 OP(AtomicOr, atomic_or)
2864 OP(AtomicXor, atomic_xor)
2865 #undef OP
2866 default:
2867 vtn_fail_with_opcode("Invalid image opcode", opcode);
2868 }
2869
2870 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2871
2872 nir_deref_instr *image_deref = vtn_pointer_to_deref(b, image.image);
2873 intrin->src[0] = nir_src_for_ssa(&image_deref->dest.ssa);
2874
2875 /* ImageQuerySize doesn't take any extra parameters */
2876 if (opcode != SpvOpImageQuerySize) {
2877 /* The image coordinate is always 4 components but we may not have that
2878 * many. Swizzle to compensate.
2879 */
2880 intrin->src[1] = nir_src_for_ssa(expand_to_vec4(&b->nb, image.coord));
2881 intrin->src[2] = nir_src_for_ssa(image.sample);
2882 }
2883
2884 nir_intrinsic_set_access(intrin, image.image->access);
2885
2886 switch (opcode) {
2887 case SpvOpAtomicLoad:
2888 case SpvOpImageQuerySize:
2889 case SpvOpImageRead:
2890 if (opcode == SpvOpImageRead || opcode == SpvOpAtomicLoad) {
2891 /* Only OpImageRead can support a lod parameter if
2892 * SPV_AMD_shader_image_load_store_lod is used but the current NIR
2893 * intrinsics definition for atomics requires us to set it for
2894 * OpAtomicLoad.
2895 */
2896 intrin->src[3] = nir_src_for_ssa(image.lod);
2897 }
2898 break;
2899 case SpvOpAtomicStore:
2900 case SpvOpImageWrite: {
2901 const uint32_t value_id = opcode == SpvOpAtomicStore ? w[4] : w[3];
2902 nir_ssa_def *value = vtn_ssa_value(b, value_id)->def;
2903 /* nir_intrinsic_image_deref_store always takes a vec4 value */
2904 assert(op == nir_intrinsic_image_deref_store);
2905 intrin->num_components = 4;
2906 intrin->src[3] = nir_src_for_ssa(expand_to_vec4(&b->nb, value));
2907 /* Only OpImageWrite can support a lod parameter if
2908 * SPV_AMD_shader_image_load_store_lod is used but the current NIR
2909 * intrinsics definition for atomics requires us to set it for
2910 * OpAtomicStore.
2911 */
2912 intrin->src[4] = nir_src_for_ssa(image.lod);
2913 break;
2914 }
2915
2916 case SpvOpAtomicCompareExchange:
2917 case SpvOpAtomicCompareExchangeWeak:
2918 case SpvOpAtomicIIncrement:
2919 case SpvOpAtomicIDecrement:
2920 case SpvOpAtomicExchange:
2921 case SpvOpAtomicIAdd:
2922 case SpvOpAtomicISub:
2923 case SpvOpAtomicSMin:
2924 case SpvOpAtomicUMin:
2925 case SpvOpAtomicSMax:
2926 case SpvOpAtomicUMax:
2927 case SpvOpAtomicAnd:
2928 case SpvOpAtomicOr:
2929 case SpvOpAtomicXor:
2930 fill_common_atomic_sources(b, opcode, w, &intrin->src[3]);
2931 break;
2932
2933 default:
2934 vtn_fail_with_opcode("Invalid image opcode", opcode);
2935 }
2936
2937 /* Image operations implicitly have the Image storage memory semantics. */
2938 semantics |= SpvMemorySemanticsImageMemoryMask;
2939
2940 SpvMemorySemanticsMask before_semantics;
2941 SpvMemorySemanticsMask after_semantics;
2942 vtn_split_barrier_semantics(b, semantics, &before_semantics, &after_semantics);
2943
2944 if (before_semantics)
2945 vtn_emit_memory_barrier(b, scope, before_semantics);
2946
2947 if (opcode != SpvOpImageWrite && opcode != SpvOpAtomicStore) {
2948 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2949
2950 unsigned dest_components = glsl_get_vector_elements(type->type);
2951 intrin->num_components = nir_intrinsic_infos[op].dest_components;
2952 if (intrin->num_components == 0)
2953 intrin->num_components = dest_components;
2954
2955 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2956 intrin->num_components, 32, NULL);
2957
2958 nir_builder_instr_insert(&b->nb, &intrin->instr);
2959
2960 nir_ssa_def *result = &intrin->dest.ssa;
2961 if (intrin->num_components != dest_components)
2962 result = nir_channels(&b->nb, result, (1 << dest_components) - 1);
2963
2964 struct vtn_value *val =
2965 vtn_push_ssa(b, w[2], type, vtn_create_ssa_value(b, type->type));
2966 val->ssa->def = result;
2967 } else {
2968 nir_builder_instr_insert(&b->nb, &intrin->instr);
2969 }
2970
2971 if (after_semantics)
2972 vtn_emit_memory_barrier(b, scope, after_semantics);
2973 }
2974
2975 static nir_intrinsic_op
2976 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2977 {
2978 switch (opcode) {
2979 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
2980 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
2981 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2982 OP(AtomicExchange, atomic_exchange)
2983 OP(AtomicCompareExchange, atomic_comp_swap)
2984 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
2985 OP(AtomicIIncrement, atomic_add)
2986 OP(AtomicIDecrement, atomic_add)
2987 OP(AtomicIAdd, atomic_add)
2988 OP(AtomicISub, atomic_add)
2989 OP(AtomicSMin, atomic_imin)
2990 OP(AtomicUMin, atomic_umin)
2991 OP(AtomicSMax, atomic_imax)
2992 OP(AtomicUMax, atomic_umax)
2993 OP(AtomicAnd, atomic_and)
2994 OP(AtomicOr, atomic_or)
2995 OP(AtomicXor, atomic_xor)
2996 #undef OP
2997 default:
2998 vtn_fail_with_opcode("Invalid SSBO atomic", opcode);
2999 }
3000 }
3001
3002 static nir_intrinsic_op
3003 get_uniform_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
3004 {
3005 switch (opcode) {
3006 #define OP(S, N) case SpvOp##S: return nir_intrinsic_atomic_counter_ ##N;
3007 OP(AtomicLoad, read_deref)
3008 OP(AtomicExchange, exchange)
3009 OP(AtomicCompareExchange, comp_swap)
3010 OP(AtomicCompareExchangeWeak, comp_swap)
3011 OP(AtomicIIncrement, inc_deref)
3012 OP(AtomicIDecrement, post_dec_deref)
3013 OP(AtomicIAdd, add_deref)
3014 OP(AtomicISub, add_deref)
3015 OP(AtomicUMin, min_deref)
3016 OP(AtomicUMax, max_deref)
3017 OP(AtomicAnd, and_deref)
3018 OP(AtomicOr, or_deref)
3019 OP(AtomicXor, xor_deref)
3020 #undef OP
3021 default:
3022 /* We left the following out: AtomicStore, AtomicSMin and
3023 * AtomicSmax. Right now there are not nir intrinsics for them. At this
3024 * moment Atomic Counter support is needed for ARB_spirv support, so is
3025 * only need to support GLSL Atomic Counters that are uints and don't
3026 * allow direct storage.
3027 */
3028 vtn_fail("Invalid uniform atomic");
3029 }
3030 }
3031
3032 static nir_intrinsic_op
3033 get_deref_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
3034 {
3035 switch (opcode) {
3036 case SpvOpAtomicLoad: return nir_intrinsic_load_deref;
3037 case SpvOpAtomicStore: return nir_intrinsic_store_deref;
3038 #define OP(S, N) case SpvOp##S: return nir_intrinsic_deref_##N;
3039 OP(AtomicExchange, atomic_exchange)
3040 OP(AtomicCompareExchange, atomic_comp_swap)
3041 OP(AtomicCompareExchangeWeak, atomic_comp_swap)
3042 OP(AtomicIIncrement, atomic_add)
3043 OP(AtomicIDecrement, atomic_add)
3044 OP(AtomicIAdd, atomic_add)
3045 OP(AtomicISub, atomic_add)
3046 OP(AtomicSMin, atomic_imin)
3047 OP(AtomicUMin, atomic_umin)
3048 OP(AtomicSMax, atomic_imax)
3049 OP(AtomicUMax, atomic_umax)
3050 OP(AtomicAnd, atomic_and)
3051 OP(AtomicOr, atomic_or)
3052 OP(AtomicXor, atomic_xor)
3053 #undef OP
3054 default:
3055 vtn_fail_with_opcode("Invalid shared atomic", opcode);
3056 }
3057 }
3058
3059 /*
3060 * Handles shared atomics, ssbo atomics and atomic counters.
3061 */
3062 static void
3063 vtn_handle_atomics(struct vtn_builder *b, SpvOp opcode,
3064 const uint32_t *w, UNUSED unsigned count)
3065 {
3066 struct vtn_pointer *ptr;
3067 nir_intrinsic_instr *atomic;
3068
3069 SpvScope scope = SpvScopeInvocation;
3070 SpvMemorySemanticsMask semantics = 0;
3071
3072 switch (opcode) {
3073 case SpvOpAtomicLoad:
3074 case SpvOpAtomicExchange:
3075 case SpvOpAtomicCompareExchange:
3076 case SpvOpAtomicCompareExchangeWeak:
3077 case SpvOpAtomicIIncrement:
3078 case SpvOpAtomicIDecrement:
3079 case SpvOpAtomicIAdd:
3080 case SpvOpAtomicISub:
3081 case SpvOpAtomicSMin:
3082 case SpvOpAtomicUMin:
3083 case SpvOpAtomicSMax:
3084 case SpvOpAtomicUMax:
3085 case SpvOpAtomicAnd:
3086 case SpvOpAtomicOr:
3087 case SpvOpAtomicXor:
3088 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3089 scope = vtn_constant_uint(b, w[4]);
3090 semantics = vtn_constant_uint(b, w[5]);
3091 break;
3092
3093 case SpvOpAtomicStore:
3094 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
3095 scope = vtn_constant_uint(b, w[2]);
3096 semantics = vtn_constant_uint(b, w[3]);
3097 break;
3098
3099 default:
3100 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3101 }
3102
3103 /* uniform as "atomic counter uniform" */
3104 if (ptr->mode == vtn_variable_mode_uniform) {
3105 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
3106 const struct glsl_type *deref_type = deref->type;
3107 nir_intrinsic_op op = get_uniform_nir_atomic_op(b, opcode);
3108 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3109 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
3110
3111 /* SSBO needs to initialize index/offset. In this case we don't need to,
3112 * as that info is already stored on the ptr->var->var nir_variable (see
3113 * vtn_create_variable)
3114 */
3115
3116 switch (opcode) {
3117 case SpvOpAtomicLoad:
3118 atomic->num_components = glsl_get_vector_elements(deref_type);
3119 break;
3120
3121 case SpvOpAtomicStore:
3122 atomic->num_components = glsl_get_vector_elements(deref_type);
3123 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
3124 break;
3125
3126 case SpvOpAtomicExchange:
3127 case SpvOpAtomicCompareExchange:
3128 case SpvOpAtomicCompareExchangeWeak:
3129 case SpvOpAtomicIIncrement:
3130 case SpvOpAtomicIDecrement:
3131 case SpvOpAtomicIAdd:
3132 case SpvOpAtomicISub:
3133 case SpvOpAtomicSMin:
3134 case SpvOpAtomicUMin:
3135 case SpvOpAtomicSMax:
3136 case SpvOpAtomicUMax:
3137 case SpvOpAtomicAnd:
3138 case SpvOpAtomicOr:
3139 case SpvOpAtomicXor:
3140 /* Nothing: we don't need to call fill_common_atomic_sources here, as
3141 * atomic counter uniforms doesn't have sources
3142 */
3143 break;
3144
3145 default:
3146 unreachable("Invalid SPIR-V atomic");
3147
3148 }
3149 } else if (vtn_pointer_uses_ssa_offset(b, ptr)) {
3150 nir_ssa_def *offset, *index;
3151 offset = vtn_pointer_to_offset(b, ptr, &index);
3152
3153 assert(ptr->mode == vtn_variable_mode_ssbo);
3154
3155 nir_intrinsic_op op = get_ssbo_nir_atomic_op(b, opcode);
3156 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3157
3158 int src = 0;
3159 switch (opcode) {
3160 case SpvOpAtomicLoad:
3161 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
3162 nir_intrinsic_set_align(atomic, 4, 0);
3163 if (ptr->mode == vtn_variable_mode_ssbo)
3164 atomic->src[src++] = nir_src_for_ssa(index);
3165 atomic->src[src++] = nir_src_for_ssa(offset);
3166 break;
3167
3168 case SpvOpAtomicStore:
3169 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
3170 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
3171 nir_intrinsic_set_align(atomic, 4, 0);
3172 atomic->src[src++] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
3173 if (ptr->mode == vtn_variable_mode_ssbo)
3174 atomic->src[src++] = nir_src_for_ssa(index);
3175 atomic->src[src++] = nir_src_for_ssa(offset);
3176 break;
3177
3178 case SpvOpAtomicExchange:
3179 case SpvOpAtomicCompareExchange:
3180 case SpvOpAtomicCompareExchangeWeak:
3181 case SpvOpAtomicIIncrement:
3182 case SpvOpAtomicIDecrement:
3183 case SpvOpAtomicIAdd:
3184 case SpvOpAtomicISub:
3185 case SpvOpAtomicSMin:
3186 case SpvOpAtomicUMin:
3187 case SpvOpAtomicSMax:
3188 case SpvOpAtomicUMax:
3189 case SpvOpAtomicAnd:
3190 case SpvOpAtomicOr:
3191 case SpvOpAtomicXor:
3192 if (ptr->mode == vtn_variable_mode_ssbo)
3193 atomic->src[src++] = nir_src_for_ssa(index);
3194 atomic->src[src++] = nir_src_for_ssa(offset);
3195 fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
3196 break;
3197
3198 default:
3199 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3200 }
3201 } else {
3202 nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
3203 const struct glsl_type *deref_type = deref->type;
3204 nir_intrinsic_op op = get_deref_nir_atomic_op(b, opcode);
3205 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
3206 atomic->src[0] = nir_src_for_ssa(&deref->dest.ssa);
3207
3208 switch (opcode) {
3209 case SpvOpAtomicLoad:
3210 atomic->num_components = glsl_get_vector_elements(deref_type);
3211 break;
3212
3213 case SpvOpAtomicStore:
3214 atomic->num_components = glsl_get_vector_elements(deref_type);
3215 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
3216 atomic->src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
3217 break;
3218
3219 case SpvOpAtomicExchange:
3220 case SpvOpAtomicCompareExchange:
3221 case SpvOpAtomicCompareExchangeWeak:
3222 case SpvOpAtomicIIncrement:
3223 case SpvOpAtomicIDecrement:
3224 case SpvOpAtomicIAdd:
3225 case SpvOpAtomicISub:
3226 case SpvOpAtomicSMin:
3227 case SpvOpAtomicUMin:
3228 case SpvOpAtomicSMax:
3229 case SpvOpAtomicUMax:
3230 case SpvOpAtomicAnd:
3231 case SpvOpAtomicOr:
3232 case SpvOpAtomicXor:
3233 fill_common_atomic_sources(b, opcode, w, &atomic->src[1]);
3234 break;
3235
3236 default:
3237 vtn_fail_with_opcode("Invalid SPIR-V atomic", opcode);
3238 }
3239 }
3240
3241 /* Atomic ordering operations will implicitly apply to the atomic operation
3242 * storage class, so include that too.
3243 */
3244 semantics |= vtn_storage_class_to_memory_semantics(ptr->ptr_type->storage_class);
3245
3246 SpvMemorySemanticsMask before_semantics;
3247 SpvMemorySemanticsMask after_semantics;
3248 vtn_split_barrier_semantics(b, semantics, &before_semantics, &after_semantics);
3249
3250 if (before_semantics)
3251 vtn_emit_memory_barrier(b, scope, before_semantics);
3252
3253 if (opcode != SpvOpAtomicStore) {
3254 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
3255
3256 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
3257 glsl_get_vector_elements(type->type),
3258 glsl_get_bit_size(type->type), NULL);
3259
3260 struct vtn_ssa_value *ssa = rzalloc(b, struct vtn_ssa_value);
3261 ssa->def = &atomic->dest.ssa;
3262 ssa->type = type->type;
3263 vtn_push_ssa(b, w[2], type, ssa);
3264 }
3265
3266 nir_builder_instr_insert(&b->nb, &atomic->instr);
3267
3268 if (after_semantics)
3269 vtn_emit_memory_barrier(b, scope, after_semantics);
3270 }
3271
3272 static nir_alu_instr *
3273 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
3274 {
3275 nir_op op = nir_op_vec(num_components);
3276 nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
3277 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
3278 bit_size, NULL);
3279 vec->dest.write_mask = (1 << num_components) - 1;
3280
3281 return vec;
3282 }
3283
3284 struct vtn_ssa_value *
3285 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
3286 {
3287 if (src->transposed)
3288 return src->transposed;
3289
3290 struct vtn_ssa_value *dest =
3291 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
3292
3293 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
3294 nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
3295 glsl_get_bit_size(src->type));
3296 if (glsl_type_is_vector_or_scalar(src->type)) {
3297 vec->src[0].src = nir_src_for_ssa(src->def);
3298 vec->src[0].swizzle[0] = i;
3299 } else {
3300 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
3301 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
3302 vec->src[j].swizzle[0] = i;
3303 }
3304 }
3305 nir_builder_instr_insert(&b->nb, &vec->instr);
3306 dest->elems[i]->def = &vec->dest.dest.ssa;
3307 }
3308
3309 dest->transposed = src;
3310
3311 return dest;
3312 }
3313
3314 nir_ssa_def *
3315 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
3316 unsigned index)
3317 {
3318 nir_alu_instr *vec = create_vec(b, src->num_components,
3319 src->bit_size);
3320
3321 for (unsigned i = 0; i < src->num_components; i++) {
3322 if (i == index) {
3323 vec->src[i].src = nir_src_for_ssa(insert);
3324 } else {
3325 vec->src[i].src = nir_src_for_ssa(src);
3326 vec->src[i].swizzle[0] = i;
3327 }
3328 }
3329
3330 nir_builder_instr_insert(&b->nb, &vec->instr);
3331
3332 return &vec->dest.dest.ssa;
3333 }
3334
3335 nir_ssa_def *
3336 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
3337 nir_ssa_def *insert, nir_ssa_def *index)
3338 {
3339 nir_const_value per_comp_idx_const[NIR_MAX_VEC_COMPONENTS];
3340 for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; i++)
3341 per_comp_idx_const[i] = nir_const_value_for_int(i, index->bit_size);
3342 nir_ssa_def *per_comp_idx =
3343 nir_build_imm(&b->nb, src->num_components,
3344 index->bit_size, per_comp_idx_const);
3345
3346 /* nir_builder will automatically splat out scalars to vectors so an insert
3347 * is as simple as "if I'm the channel, replace me with the scalar."
3348 */
3349 return nir_bcsel(&b->nb, nir_ieq(&b->nb, index, per_comp_idx), insert, src);
3350 }
3351
3352 static nir_ssa_def *
3353 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
3354 nir_ssa_def *src0, nir_ssa_def *src1,
3355 const uint32_t *indices)
3356 {
3357 nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
3358
3359 for (unsigned i = 0; i < num_components; i++) {
3360 uint32_t index = indices[i];
3361 if (index == 0xffffffff) {
3362 vec->src[i].src =
3363 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
3364 } else if (index < src0->num_components) {
3365 vec->src[i].src = nir_src_for_ssa(src0);
3366 vec->src[i].swizzle[0] = index;
3367 } else {
3368 vec->src[i].src = nir_src_for_ssa(src1);
3369 vec->src[i].swizzle[0] = index - src0->num_components;
3370 }
3371 }
3372
3373 nir_builder_instr_insert(&b->nb, &vec->instr);
3374
3375 return &vec->dest.dest.ssa;
3376 }
3377
3378 /*
3379 * Concatentates a number of vectors/scalars together to produce a vector
3380 */
3381 static nir_ssa_def *
3382 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
3383 unsigned num_srcs, nir_ssa_def **srcs)
3384 {
3385 nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
3386
3387 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3388 *
3389 * "When constructing a vector, there must be at least two Constituent
3390 * operands."
3391 */
3392 vtn_assert(num_srcs >= 2);
3393
3394 unsigned dest_idx = 0;
3395 for (unsigned i = 0; i < num_srcs; i++) {
3396 nir_ssa_def *src = srcs[i];
3397 vtn_assert(dest_idx + src->num_components <= num_components);
3398 for (unsigned j = 0; j < src->num_components; j++) {
3399 vec->src[dest_idx].src = nir_src_for_ssa(src);
3400 vec->src[dest_idx].swizzle[0] = j;
3401 dest_idx++;
3402 }
3403 }
3404
3405 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
3406 *
3407 * "When constructing a vector, the total number of components in all
3408 * the operands must equal the number of components in Result Type."
3409 */
3410 vtn_assert(dest_idx == num_components);
3411
3412 nir_builder_instr_insert(&b->nb, &vec->instr);
3413
3414 return &vec->dest.dest.ssa;
3415 }
3416
3417 static struct vtn_ssa_value *
3418 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
3419 {
3420 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
3421 dest->type = src->type;
3422
3423 if (glsl_type_is_vector_or_scalar(src->type)) {
3424 dest->def = src->def;
3425 } else {
3426 unsigned elems = glsl_get_length(src->type);
3427
3428 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
3429 for (unsigned i = 0; i < elems; i++)
3430 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
3431 }
3432
3433 return dest;
3434 }
3435
3436 static struct vtn_ssa_value *
3437 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
3438 struct vtn_ssa_value *insert, const uint32_t *indices,
3439 unsigned num_indices)
3440 {
3441 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
3442
3443 struct vtn_ssa_value *cur = dest;
3444 unsigned i;
3445 for (i = 0; i < num_indices - 1; i++) {
3446 /* If we got a vector here, that means the next index will be trying to
3447 * dereference a scalar.
3448 */
3449 vtn_fail_if(glsl_type_is_vector_or_scalar(cur->type),
3450 "OpCompositeInsert has too many indices.");
3451 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3452 "All indices in an OpCompositeInsert must be in-bounds");
3453 cur = cur->elems[indices[i]];
3454 }
3455
3456 if (glsl_type_is_vector_or_scalar(cur->type)) {
3457 vtn_fail_if(indices[i] >= glsl_get_vector_elements(cur->type),
3458 "All indices in an OpCompositeInsert must be in-bounds");
3459
3460 /* According to the SPIR-V spec, OpCompositeInsert may work down to
3461 * the component granularity. In that case, the last index will be
3462 * the index to insert the scalar into the vector.
3463 */
3464
3465 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
3466 } else {
3467 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3468 "All indices in an OpCompositeInsert must be in-bounds");
3469 cur->elems[indices[i]] = insert;
3470 }
3471
3472 return dest;
3473 }
3474
3475 static struct vtn_ssa_value *
3476 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
3477 const uint32_t *indices, unsigned num_indices)
3478 {
3479 struct vtn_ssa_value *cur = src;
3480 for (unsigned i = 0; i < num_indices; i++) {
3481 if (glsl_type_is_vector_or_scalar(cur->type)) {
3482 vtn_assert(i == num_indices - 1);
3483 vtn_fail_if(indices[i] >= glsl_get_vector_elements(cur->type),
3484 "All indices in an OpCompositeExtract must be in-bounds");
3485
3486 /* According to the SPIR-V spec, OpCompositeExtract may work down to
3487 * the component granularity. The last index will be the index of the
3488 * vector to extract.
3489 */
3490
3491 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
3492 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
3493 ret->def = nir_channel(&b->nb, cur->def, indices[i]);
3494 return ret;
3495 } else {
3496 vtn_fail_if(indices[i] >= glsl_get_length(cur->type),
3497 "All indices in an OpCompositeExtract must be in-bounds");
3498 cur = cur->elems[indices[i]];
3499 }
3500 }
3501
3502 return cur;
3503 }
3504
3505 static void
3506 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
3507 const uint32_t *w, unsigned count)
3508 {
3509 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
3510 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, type->type);
3511
3512 switch (opcode) {
3513 case SpvOpVectorExtractDynamic:
3514 ssa->def = nir_vector_extract(&b->nb, vtn_ssa_value(b, w[3])->def,
3515 vtn_ssa_value(b, w[4])->def);
3516 break;
3517
3518 case SpvOpVectorInsertDynamic:
3519 ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
3520 vtn_ssa_value(b, w[4])->def,
3521 vtn_ssa_value(b, w[5])->def);
3522 break;
3523
3524 case SpvOpVectorShuffle:
3525 ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type->type),
3526 vtn_ssa_value(b, w[3])->def,
3527 vtn_ssa_value(b, w[4])->def,
3528 w + 5);
3529 break;
3530
3531 case SpvOpCompositeConstruct: {
3532 unsigned elems = count - 3;
3533 assume(elems >= 1);
3534 if (glsl_type_is_vector_or_scalar(type->type)) {
3535 nir_ssa_def *srcs[NIR_MAX_VEC_COMPONENTS];
3536 for (unsigned i = 0; i < elems; i++)
3537 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
3538 ssa->def =
3539 vtn_vector_construct(b, glsl_get_vector_elements(type->type),
3540 elems, srcs);
3541 } else {
3542 ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
3543 for (unsigned i = 0; i < elems; i++)
3544 ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
3545 }
3546 break;
3547 }
3548 case SpvOpCompositeExtract:
3549 ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
3550 w + 4, count - 4);
3551 break;
3552
3553 case SpvOpCompositeInsert:
3554 ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
3555 vtn_ssa_value(b, w[3]),
3556 w + 5, count - 5);
3557 break;
3558
3559 case SpvOpCopyLogical:
3560 case SpvOpCopyObject:
3561 ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
3562 break;
3563
3564 default:
3565 vtn_fail_with_opcode("unknown composite operation", opcode);
3566 }
3567
3568 vtn_push_ssa(b, w[2], type, ssa);
3569 }
3570
3571 static void
3572 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
3573 {
3574 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
3575 nir_builder_instr_insert(&b->nb, &intrin->instr);
3576 }
3577
3578 void
3579 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
3580 SpvMemorySemanticsMask semantics)
3581 {
3582 if (b->shader->options->use_scoped_memory_barrier) {
3583 vtn_emit_scoped_memory_barrier(b, scope, semantics);
3584 return;
3585 }
3586
3587 static const SpvMemorySemanticsMask all_memory_semantics =
3588 SpvMemorySemanticsUniformMemoryMask |
3589 SpvMemorySemanticsWorkgroupMemoryMask |
3590 SpvMemorySemanticsAtomicCounterMemoryMask |
3591 SpvMemorySemanticsImageMemoryMask |
3592 SpvMemorySemanticsOutputMemoryMask;
3593
3594 /* If we're not actually doing a memory barrier, bail */
3595 if (!(semantics & all_memory_semantics))
3596 return;
3597
3598 /* GL and Vulkan don't have these */
3599 vtn_assert(scope != SpvScopeCrossDevice);
3600
3601 if (scope == SpvScopeSubgroup)
3602 return; /* Nothing to do here */
3603
3604 if (scope == SpvScopeWorkgroup) {
3605 vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
3606 return;
3607 }
3608
3609 /* There's only two scopes thing left */
3610 vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
3611
3612 /* Map the GLSL memoryBarrier() construct to the corresponding NIR one. */
3613 static const SpvMemorySemanticsMask glsl_memory_barrier =
3614 SpvMemorySemanticsUniformMemoryMask |
3615 SpvMemorySemanticsWorkgroupMemoryMask |
3616 SpvMemorySemanticsImageMemoryMask;
3617 if ((semantics & glsl_memory_barrier) == glsl_memory_barrier) {
3618 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3619 semantics &= ~(glsl_memory_barrier | SpvMemorySemanticsAtomicCounterMemoryMask);
3620 }
3621
3622 /* Issue a bunch of more specific barriers */
3623 uint32_t bits = semantics;
3624 while (bits) {
3625 SpvMemorySemanticsMask semantic = 1 << u_bit_scan(&bits);
3626 switch (semantic) {
3627 case SpvMemorySemanticsUniformMemoryMask:
3628 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3629 break;
3630 case SpvMemorySemanticsWorkgroupMemoryMask:
3631 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3632 break;
3633 case SpvMemorySemanticsAtomicCounterMemoryMask:
3634 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3635 break;
3636 case SpvMemorySemanticsImageMemoryMask:
3637 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3638 break;
3639 case SpvMemorySemanticsOutputMemoryMask:
3640 if (b->nb.shader->info.stage == MESA_SHADER_TESS_CTRL)
3641 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_tcs_patch);
3642 break;
3643 default:
3644 break;;
3645 }
3646 }
3647 }
3648
3649 static void
3650 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3651 const uint32_t *w, UNUSED unsigned count)
3652 {
3653 switch (opcode) {
3654 case SpvOpEmitVertex:
3655 case SpvOpEmitStreamVertex:
3656 case SpvOpEndPrimitive:
3657 case SpvOpEndStreamPrimitive: {
3658 nir_intrinsic_op intrinsic_op;
3659 switch (opcode) {
3660 case SpvOpEmitVertex:
3661 case SpvOpEmitStreamVertex:
3662 intrinsic_op = nir_intrinsic_emit_vertex;
3663 break;
3664 case SpvOpEndPrimitive:
3665 case SpvOpEndStreamPrimitive:
3666 intrinsic_op = nir_intrinsic_end_primitive;
3667 break;
3668 default:
3669 unreachable("Invalid opcode");
3670 }
3671
3672 nir_intrinsic_instr *intrin =
3673 nir_intrinsic_instr_create(b->shader, intrinsic_op);
3674
3675 switch (opcode) {
3676 case SpvOpEmitStreamVertex:
3677 case SpvOpEndStreamPrimitive: {
3678 unsigned stream = vtn_constant_uint(b, w[1]);
3679 nir_intrinsic_set_stream_id(intrin, stream);
3680 break;
3681 }
3682
3683 default:
3684 break;
3685 }
3686
3687 nir_builder_instr_insert(&b->nb, &intrin->instr);
3688 break;
3689 }
3690
3691 case SpvOpMemoryBarrier: {
3692 SpvScope scope = vtn_constant_uint(b, w[1]);
3693 SpvMemorySemanticsMask semantics = vtn_constant_uint(b, w[2]);
3694 vtn_emit_memory_barrier(b, scope, semantics);
3695 return;
3696 }
3697
3698 case SpvOpControlBarrier: {
3699 SpvScope execution_scope = vtn_constant_uint(b, w[1]);
3700 SpvScope memory_scope = vtn_constant_uint(b, w[2]);
3701 SpvMemorySemanticsMask memory_semantics = vtn_constant_uint(b, w[3]);
3702
3703 /* GLSLang, prior to commit 8297936dd6eb3, emitted OpControlBarrier with
3704 * memory semantics of None for GLSL barrier().
3705 */
3706 if (b->wa_glslang_cs_barrier &&
3707 b->nb.shader->info.stage == MESA_SHADER_COMPUTE &&
3708 execution_scope == SpvScopeWorkgroup &&
3709 memory_semantics == SpvMemorySemanticsMaskNone) {
3710 memory_scope = SpvScopeWorkgroup;
3711 memory_semantics = SpvMemorySemanticsAcquireReleaseMask |
3712 SpvMemorySemanticsWorkgroupMemoryMask;
3713 }
3714
3715 /* From the SPIR-V spec:
3716 *
3717 * "When used with the TessellationControl execution model, it also
3718 * implicitly synchronizes the Output Storage Class: Writes to Output
3719 * variables performed by any invocation executed prior to a
3720 * OpControlBarrier will be visible to any other invocation after
3721 * return from that OpControlBarrier."
3722 */
3723 if (b->nb.shader->info.stage == MESA_SHADER_TESS_CTRL) {
3724 memory_semantics &= ~(SpvMemorySemanticsAcquireMask |
3725 SpvMemorySemanticsReleaseMask |
3726 SpvMemorySemanticsAcquireReleaseMask |
3727 SpvMemorySemanticsSequentiallyConsistentMask);
3728 memory_semantics |= SpvMemorySemanticsAcquireReleaseMask |
3729 SpvMemorySemanticsOutputMemoryMask;
3730 }
3731
3732 vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3733
3734 if (execution_scope == SpvScopeWorkgroup)
3735 vtn_emit_barrier(b, nir_intrinsic_control_barrier);
3736 break;
3737 }
3738
3739 default:
3740 unreachable("unknown barrier instruction");
3741 }
3742 }
3743
3744 static unsigned
3745 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
3746 SpvExecutionMode mode)
3747 {
3748 switch (mode) {
3749 case SpvExecutionModeInputPoints:
3750 case SpvExecutionModeOutputPoints:
3751 return 0; /* GL_POINTS */
3752 case SpvExecutionModeInputLines:
3753 return 1; /* GL_LINES */
3754 case SpvExecutionModeInputLinesAdjacency:
3755 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
3756 case SpvExecutionModeTriangles:
3757 return 4; /* GL_TRIANGLES */
3758 case SpvExecutionModeInputTrianglesAdjacency:
3759 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
3760 case SpvExecutionModeQuads:
3761 return 7; /* GL_QUADS */
3762 case SpvExecutionModeIsolines:
3763 return 0x8E7A; /* GL_ISOLINES */
3764 case SpvExecutionModeOutputLineStrip:
3765 return 3; /* GL_LINE_STRIP */
3766 case SpvExecutionModeOutputTriangleStrip:
3767 return 5; /* GL_TRIANGLE_STRIP */
3768 default:
3769 vtn_fail("Invalid primitive type: %s (%u)",
3770 spirv_executionmode_to_string(mode), mode);
3771 }
3772 }
3773
3774 static unsigned
3775 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
3776 SpvExecutionMode mode)
3777 {
3778 switch (mode) {
3779 case SpvExecutionModeInputPoints:
3780 return 1;
3781 case SpvExecutionModeInputLines:
3782 return 2;
3783 case SpvExecutionModeInputLinesAdjacency:
3784 return 4;
3785 case SpvExecutionModeTriangles:
3786 return 3;
3787 case SpvExecutionModeInputTrianglesAdjacency:
3788 return 6;
3789 default:
3790 vtn_fail("Invalid GS input mode: %s (%u)",
3791 spirv_executionmode_to_string(mode), mode);
3792 }
3793 }
3794
3795 static gl_shader_stage
3796 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
3797 {
3798 switch (model) {
3799 case SpvExecutionModelVertex:
3800 return MESA_SHADER_VERTEX;
3801 case SpvExecutionModelTessellationControl:
3802 return MESA_SHADER_TESS_CTRL;
3803 case SpvExecutionModelTessellationEvaluation:
3804 return MESA_SHADER_TESS_EVAL;
3805 case SpvExecutionModelGeometry:
3806 return MESA_SHADER_GEOMETRY;
3807 case SpvExecutionModelFragment:
3808 return MESA_SHADER_FRAGMENT;
3809 case SpvExecutionModelGLCompute:
3810 return MESA_SHADER_COMPUTE;
3811 case SpvExecutionModelKernel:
3812 return MESA_SHADER_KERNEL;
3813 default:
3814 vtn_fail("Unsupported execution model: %s (%u)",
3815 spirv_executionmodel_to_string(model), model);
3816 }
3817 }
3818
3819 #define spv_check_supported(name, cap) do { \
3820 if (!(b->options && b->options->caps.name)) \
3821 vtn_warn("Unsupported SPIR-V capability: %s (%u)", \
3822 spirv_capability_to_string(cap), cap); \
3823 } while(0)
3824
3825
3826 void
3827 vtn_handle_entry_point(struct vtn_builder *b, const uint32_t *w,
3828 unsigned count)
3829 {
3830 struct vtn_value *entry_point = &b->values[w[2]];
3831 /* Let this be a name label regardless */
3832 unsigned name_words;
3833 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
3834
3835 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
3836 stage_for_execution_model(b, w[1]) != b->entry_point_stage)
3837 return;
3838
3839 vtn_assert(b->entry_point == NULL);
3840 b->entry_point = entry_point;
3841 }
3842
3843 static bool
3844 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
3845 const uint32_t *w, unsigned count)
3846 {
3847 switch (opcode) {
3848 case SpvOpSource: {
3849 const char *lang;
3850 switch (w[1]) {
3851 default:
3852 case SpvSourceLanguageUnknown: lang = "unknown"; break;
3853 case SpvSourceLanguageESSL: lang = "ESSL"; break;
3854 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
3855 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
3856 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
3857 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
3858 }
3859
3860 uint32_t version = w[2];
3861
3862 const char *file =
3863 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
3864
3865 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
3866 break;
3867 }
3868
3869 case SpvOpSourceExtension:
3870 case SpvOpSourceContinued:
3871 case SpvOpExtension:
3872 case SpvOpModuleProcessed:
3873 /* Unhandled, but these are for debug so that's ok. */
3874 break;
3875
3876 case SpvOpCapability: {
3877 SpvCapability cap = w[1];
3878 switch (cap) {
3879 case SpvCapabilityMatrix:
3880 case SpvCapabilityShader:
3881 case SpvCapabilityGeometry:
3882 case SpvCapabilityGeometryPointSize:
3883 case SpvCapabilityUniformBufferArrayDynamicIndexing:
3884 case SpvCapabilitySampledImageArrayDynamicIndexing:
3885 case SpvCapabilityStorageBufferArrayDynamicIndexing:
3886 case SpvCapabilityStorageImageArrayDynamicIndexing:
3887 case SpvCapabilityImageRect:
3888 case SpvCapabilitySampledRect:
3889 case SpvCapabilitySampled1D:
3890 case SpvCapabilityImage1D:
3891 case SpvCapabilitySampledCubeArray:
3892 case SpvCapabilityImageCubeArray:
3893 case SpvCapabilitySampledBuffer:
3894 case SpvCapabilityImageBuffer:
3895 case SpvCapabilityImageQuery:
3896 case SpvCapabilityDerivativeControl:
3897 case SpvCapabilityInterpolationFunction:
3898 case SpvCapabilityMultiViewport:
3899 case SpvCapabilitySampleRateShading:
3900 case SpvCapabilityClipDistance:
3901 case SpvCapabilityCullDistance:
3902 case SpvCapabilityInputAttachment:
3903 case SpvCapabilityImageGatherExtended:
3904 case SpvCapabilityStorageImageExtendedFormats:
3905 case SpvCapabilityVector16:
3906 break;
3907
3908 case SpvCapabilityLinkage:
3909 case SpvCapabilityFloat16Buffer:
3910 case SpvCapabilitySparseResidency:
3911 vtn_warn("Unsupported SPIR-V capability: %s",
3912 spirv_capability_to_string(cap));
3913 break;
3914
3915 case SpvCapabilityMinLod:
3916 spv_check_supported(min_lod, cap);
3917 break;
3918
3919 case SpvCapabilityAtomicStorage:
3920 spv_check_supported(atomic_storage, cap);
3921 break;
3922
3923 case SpvCapabilityFloat64:
3924 spv_check_supported(float64, cap);
3925 break;
3926 case SpvCapabilityInt64:
3927 spv_check_supported(int64, cap);
3928 break;
3929 case SpvCapabilityInt16:
3930 spv_check_supported(int16, cap);
3931 break;
3932 case SpvCapabilityInt8:
3933 spv_check_supported(int8, cap);
3934 break;
3935
3936 case SpvCapabilityTransformFeedback:
3937 spv_check_supported(transform_feedback, cap);
3938 break;
3939
3940 case SpvCapabilityGeometryStreams:
3941 spv_check_supported(geometry_streams, cap);
3942 break;
3943
3944 case SpvCapabilityInt64Atomics:
3945 spv_check_supported(int64_atomics, cap);
3946 break;
3947
3948 case SpvCapabilityStorageImageMultisample:
3949 spv_check_supported(storage_image_ms, cap);
3950 break;
3951
3952 case SpvCapabilityAddresses:
3953 spv_check_supported(address, cap);
3954 break;
3955
3956 case SpvCapabilityKernel:
3957 spv_check_supported(kernel, cap);
3958 break;
3959
3960 case SpvCapabilityImageBasic:
3961 case SpvCapabilityImageReadWrite:
3962 case SpvCapabilityImageMipmap:
3963 case SpvCapabilityPipes:
3964 case SpvCapabilityDeviceEnqueue:
3965 case SpvCapabilityLiteralSampler:
3966 case SpvCapabilityGenericPointer:
3967 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
3968 spirv_capability_to_string(cap));
3969 break;
3970
3971 case SpvCapabilityImageMSArray:
3972 spv_check_supported(image_ms_array, cap);
3973 break;
3974
3975 case SpvCapabilityTessellation:
3976 case SpvCapabilityTessellationPointSize:
3977 spv_check_supported(tessellation, cap);
3978 break;
3979
3980 case SpvCapabilityDrawParameters:
3981 spv_check_supported(draw_parameters, cap);
3982 break;
3983
3984 case SpvCapabilityStorageImageReadWithoutFormat:
3985 spv_check_supported(image_read_without_format, cap);
3986 break;
3987
3988 case SpvCapabilityStorageImageWriteWithoutFormat:
3989 spv_check_supported(image_write_without_format, cap);
3990 break;
3991
3992 case SpvCapabilityDeviceGroup:
3993 spv_check_supported(device_group, cap);
3994 break;
3995
3996 case SpvCapabilityMultiView:
3997 spv_check_supported(multiview, cap);
3998 break;
3999
4000 case SpvCapabilityGroupNonUniform:
4001 spv_check_supported(subgroup_basic, cap);
4002 break;
4003
4004 case SpvCapabilitySubgroupVoteKHR:
4005 case SpvCapabilityGroupNonUniformVote:
4006 spv_check_supported(subgroup_vote, cap);
4007 break;
4008
4009 case SpvCapabilitySubgroupBallotKHR:
4010 case SpvCapabilityGroupNonUniformBallot:
4011 spv_check_supported(subgroup_ballot, cap);
4012 break;
4013
4014 case SpvCapabilityGroupNonUniformShuffle:
4015 case SpvCapabilityGroupNonUniformShuffleRelative:
4016 spv_check_supported(subgroup_shuffle, cap);
4017 break;
4018
4019 case SpvCapabilityGroupNonUniformQuad:
4020 spv_check_supported(subgroup_quad, cap);
4021 break;
4022
4023 case SpvCapabilityGroupNonUniformArithmetic:
4024 case SpvCapabilityGroupNonUniformClustered:
4025 spv_check_supported(subgroup_arithmetic, cap);
4026 break;
4027
4028 case SpvCapabilityGroups:
4029 spv_check_supported(amd_shader_ballot, cap);
4030 break;
4031
4032 case SpvCapabilityVariablePointersStorageBuffer:
4033 case SpvCapabilityVariablePointers:
4034 spv_check_supported(variable_pointers, cap);
4035 b->variable_pointers = true;
4036 break;
4037
4038 case SpvCapabilityStorageUniformBufferBlock16:
4039 case SpvCapabilityStorageUniform16:
4040 case SpvCapabilityStoragePushConstant16:
4041 case SpvCapabilityStorageInputOutput16:
4042 spv_check_supported(storage_16bit, cap);
4043 break;
4044
4045 case SpvCapabilityShaderLayer:
4046 case SpvCapabilityShaderViewportIndex:
4047 case SpvCapabilityShaderViewportIndexLayerEXT:
4048 spv_check_supported(shader_viewport_index_layer, cap);
4049 break;
4050
4051 case SpvCapabilityStorageBuffer8BitAccess:
4052 case SpvCapabilityUniformAndStorageBuffer8BitAccess:
4053 case SpvCapabilityStoragePushConstant8:
4054 spv_check_supported(storage_8bit, cap);
4055 break;
4056
4057 case SpvCapabilityShaderNonUniformEXT:
4058 spv_check_supported(descriptor_indexing, cap);
4059 break;
4060
4061 case SpvCapabilityInputAttachmentArrayDynamicIndexingEXT:
4062 case SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT:
4063 case SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT:
4064 spv_check_supported(descriptor_array_dynamic_indexing, cap);
4065 break;
4066
4067 case SpvCapabilityUniformBufferArrayNonUniformIndexingEXT:
4068 case SpvCapabilitySampledImageArrayNonUniformIndexingEXT:
4069 case SpvCapabilityStorageBufferArrayNonUniformIndexingEXT:
4070 case SpvCapabilityStorageImageArrayNonUniformIndexingEXT:
4071 case SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT:
4072 case SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT:
4073 case SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT:
4074 spv_check_supported(descriptor_array_non_uniform_indexing, cap);
4075 break;
4076
4077 case SpvCapabilityRuntimeDescriptorArrayEXT:
4078 spv_check_supported(runtime_descriptor_array, cap);
4079 break;
4080
4081 case SpvCapabilityStencilExportEXT:
4082 spv_check_supported(stencil_export, cap);
4083 break;
4084
4085 case SpvCapabilitySampleMaskPostDepthCoverage:
4086 spv_check_supported(post_depth_coverage, cap);
4087 break;
4088
4089 case SpvCapabilityDenormFlushToZero:
4090 case SpvCapabilityDenormPreserve:
4091 case SpvCapabilitySignedZeroInfNanPreserve:
4092 case SpvCapabilityRoundingModeRTE:
4093 case SpvCapabilityRoundingModeRTZ:
4094 spv_check_supported(float_controls, cap);
4095 break;
4096
4097 case SpvCapabilityPhysicalStorageBufferAddresses:
4098 spv_check_supported(physical_storage_buffer_address, cap);
4099 break;
4100
4101 case SpvCapabilityComputeDerivativeGroupQuadsNV:
4102 case SpvCapabilityComputeDerivativeGroupLinearNV:
4103 spv_check_supported(derivative_group, cap);
4104 break;
4105
4106 case SpvCapabilityFloat16:
4107 spv_check_supported(float16, cap);
4108 break;
4109
4110 case SpvCapabilityFragmentShaderSampleInterlockEXT:
4111 spv_check_supported(fragment_shader_sample_interlock, cap);
4112 break;
4113
4114 case SpvCapabilityFragmentShaderPixelInterlockEXT:
4115 spv_check_supported(fragment_shader_pixel_interlock, cap);
4116 break;
4117
4118 case SpvCapabilityDemoteToHelperInvocationEXT:
4119 spv_check_supported(demote_to_helper_invocation, cap);
4120 break;
4121
4122 case SpvCapabilityShaderClockKHR:
4123 spv_check_supported(shader_clock, cap);
4124 break;
4125
4126 case SpvCapabilityVulkanMemoryModel:
4127 spv_check_supported(vk_memory_model, cap);
4128 break;
4129
4130 case SpvCapabilityVulkanMemoryModelDeviceScope:
4131 spv_check_supported(vk_memory_model_device_scope, cap);
4132 break;
4133
4134 case SpvCapabilityImageReadWriteLodAMD:
4135 spv_check_supported(amd_image_read_write_lod, cap);
4136 break;
4137
4138 case SpvCapabilityIntegerFunctions2INTEL:
4139 spv_check_supported(integer_functions2, cap);
4140 break;
4141
4142 case SpvCapabilityFragmentMaskAMD:
4143 spv_check_supported(amd_fragment_mask, cap);
4144 break;
4145
4146 default:
4147 vtn_fail("Unhandled capability: %s (%u)",
4148 spirv_capability_to_string(cap), cap);
4149 }
4150 break;
4151 }
4152
4153 case SpvOpExtInstImport:
4154 vtn_handle_extension(b, opcode, w, count);
4155 break;
4156
4157 case SpvOpMemoryModel:
4158 switch (w[1]) {
4159 case SpvAddressingModelPhysical32:
4160 vtn_fail_if(b->shader->info.stage != MESA_SHADER_KERNEL,
4161 "AddressingModelPhysical32 only supported for kernels");
4162 b->shader->info.cs.ptr_size = 32;
4163 b->physical_ptrs = true;
4164 b->options->shared_addr_format = nir_address_format_32bit_global;
4165 b->options->global_addr_format = nir_address_format_32bit_global;
4166 b->options->temp_addr_format = nir_address_format_32bit_global;
4167 break;
4168 case SpvAddressingModelPhysical64:
4169 vtn_fail_if(b->shader->info.stage != MESA_SHADER_KERNEL,
4170 "AddressingModelPhysical64 only supported for kernels");
4171 b->shader->info.cs.ptr_size = 64;
4172 b->physical_ptrs = true;
4173 b->options->shared_addr_format = nir_address_format_64bit_global;
4174 b->options->global_addr_format = nir_address_format_64bit_global;
4175 b->options->temp_addr_format = nir_address_format_64bit_global;
4176 break;
4177 case SpvAddressingModelLogical:
4178 vtn_fail_if(b->shader->info.stage == MESA_SHADER_KERNEL,
4179 "AddressingModelLogical only supported for shaders");
4180 b->physical_ptrs = false;
4181 break;
4182 case SpvAddressingModelPhysicalStorageBuffer64:
4183 vtn_fail_if(!b->options ||
4184 !b->options->caps.physical_storage_buffer_address,
4185 "AddressingModelPhysicalStorageBuffer64 not supported");
4186 break;
4187 default:
4188 vtn_fail("Unknown addressing model: %s (%u)",
4189 spirv_addressingmodel_to_string(w[1]), w[1]);
4190 break;
4191 }
4192
4193 switch (w[2]) {
4194 case SpvMemoryModelSimple:
4195 case SpvMemoryModelGLSL450:
4196 case SpvMemoryModelOpenCL:
4197 break;
4198 case SpvMemoryModelVulkan:
4199 vtn_fail_if(!b->options->caps.vk_memory_model,
4200 "Vulkan memory model is unsupported by this driver");
4201 break;
4202 default:
4203 vtn_fail("Unsupported memory model: %s",
4204 spirv_memorymodel_to_string(w[2]));
4205 break;
4206 }
4207 break;
4208
4209 case SpvOpEntryPoint:
4210 vtn_handle_entry_point(b, w, count);
4211 break;
4212
4213 case SpvOpString:
4214 vtn_push_value(b, w[1], vtn_value_type_string)->str =
4215 vtn_string_literal(b, &w[2], count - 2, NULL);
4216 break;
4217
4218 case SpvOpName:
4219 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
4220 break;
4221
4222 case SpvOpMemberName:
4223 /* TODO */
4224 break;
4225
4226 case SpvOpExecutionMode:
4227 case SpvOpExecutionModeId:
4228 case SpvOpDecorationGroup:
4229 case SpvOpDecorate:
4230 case SpvOpDecorateId:
4231 case SpvOpMemberDecorate:
4232 case SpvOpGroupDecorate:
4233 case SpvOpGroupMemberDecorate:
4234 case SpvOpDecorateString:
4235 case SpvOpMemberDecorateString:
4236 vtn_handle_decoration(b, opcode, w, count);
4237 break;
4238
4239 case SpvOpExtInst: {
4240 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
4241 if (val->ext_handler == vtn_handle_non_semantic_instruction) {
4242 /* NonSemantic extended instructions are acceptable in preamble. */
4243 vtn_handle_non_semantic_instruction(b, w[4], w, count);
4244 return true;
4245 } else {
4246 return false; /* End of preamble. */
4247 }
4248 }
4249
4250 default:
4251 return false; /* End of preamble */
4252 }
4253
4254 return true;
4255 }
4256
4257 static void
4258 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
4259 const struct vtn_decoration *mode, UNUSED void *data)
4260 {
4261 vtn_assert(b->entry_point == entry_point);
4262
4263 switch(mode->exec_mode) {
4264 case SpvExecutionModeOriginUpperLeft:
4265 case SpvExecutionModeOriginLowerLeft:
4266 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4267 b->shader->info.fs.origin_upper_left =
4268 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
4269 break;
4270
4271 case SpvExecutionModeEarlyFragmentTests:
4272 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4273 b->shader->info.fs.early_fragment_tests = true;
4274 break;
4275
4276 case SpvExecutionModePostDepthCoverage:
4277 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4278 b->shader->info.fs.post_depth_coverage = true;
4279 break;
4280
4281 case SpvExecutionModeInvocations:
4282 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4283 b->shader->info.gs.invocations = MAX2(1, mode->operands[0]);
4284 break;
4285
4286 case SpvExecutionModeDepthReplacing:
4287 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4288 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
4289 break;
4290 case SpvExecutionModeDepthGreater:
4291 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4292 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
4293 break;
4294 case SpvExecutionModeDepthLess:
4295 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4296 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
4297 break;
4298 case SpvExecutionModeDepthUnchanged:
4299 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4300 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
4301 break;
4302
4303 case SpvExecutionModeLocalSize:
4304 vtn_assert(gl_shader_stage_is_compute(b->shader->info.stage));
4305 b->shader->info.cs.local_size[0] = mode->operands[0];
4306 b->shader->info.cs.local_size[1] = mode->operands[1];
4307 b->shader->info.cs.local_size[2] = mode->operands[2];
4308 break;
4309
4310 case SpvExecutionModeLocalSizeId:
4311 b->shader->info.cs.local_size[0] = vtn_constant_uint(b, mode->operands[0]);
4312 b->shader->info.cs.local_size[1] = vtn_constant_uint(b, mode->operands[1]);
4313 b->shader->info.cs.local_size[2] = vtn_constant_uint(b, mode->operands[2]);
4314 break;
4315
4316 case SpvExecutionModeLocalSizeHint:
4317 case SpvExecutionModeLocalSizeHintId:
4318 break; /* Nothing to do with this */
4319
4320 case SpvExecutionModeOutputVertices:
4321 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4322 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
4323 b->shader->info.tess.tcs_vertices_out = mode->operands[0];
4324 } else {
4325 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4326 b->shader->info.gs.vertices_out = mode->operands[0];
4327 }
4328 break;
4329
4330 case SpvExecutionModeInputPoints:
4331 case SpvExecutionModeInputLines:
4332 case SpvExecutionModeInputLinesAdjacency:
4333 case SpvExecutionModeTriangles:
4334 case SpvExecutionModeInputTrianglesAdjacency:
4335 case SpvExecutionModeQuads:
4336 case SpvExecutionModeIsolines:
4337 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4338 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
4339 b->shader->info.tess.primitive_mode =
4340 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4341 } else {
4342 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4343 b->shader->info.gs.vertices_in =
4344 vertices_in_from_spv_execution_mode(b, mode->exec_mode);
4345 b->shader->info.gs.input_primitive =
4346 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4347 }
4348 break;
4349
4350 case SpvExecutionModeOutputPoints:
4351 case SpvExecutionModeOutputLineStrip:
4352 case SpvExecutionModeOutputTriangleStrip:
4353 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
4354 b->shader->info.gs.output_primitive =
4355 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
4356 break;
4357
4358 case SpvExecutionModeSpacingEqual:
4359 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4360 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4361 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
4362 break;
4363 case SpvExecutionModeSpacingFractionalEven:
4364 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4365 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4366 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
4367 break;
4368 case SpvExecutionModeSpacingFractionalOdd:
4369 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4370 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4371 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
4372 break;
4373 case SpvExecutionModeVertexOrderCw:
4374 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4375 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4376 b->shader->info.tess.ccw = false;
4377 break;
4378 case SpvExecutionModeVertexOrderCcw:
4379 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4380 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4381 b->shader->info.tess.ccw = true;
4382 break;
4383 case SpvExecutionModePointMode:
4384 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
4385 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
4386 b->shader->info.tess.point_mode = true;
4387 break;
4388
4389 case SpvExecutionModePixelCenterInteger:
4390 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4391 b->shader->info.fs.pixel_center_integer = true;
4392 break;
4393
4394 case SpvExecutionModeXfb:
4395 b->shader->info.has_transform_feedback_varyings = true;
4396 break;
4397
4398 case SpvExecutionModeVecTypeHint:
4399 break; /* OpenCL */
4400
4401 case SpvExecutionModeContractionOff:
4402 if (b->shader->info.stage != MESA_SHADER_KERNEL)
4403 vtn_warn("ExectionMode only allowed for CL-style kernels: %s",
4404 spirv_executionmode_to_string(mode->exec_mode));
4405 else
4406 b->exact = true;
4407 break;
4408
4409 case SpvExecutionModeStencilRefReplacingEXT:
4410 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4411 break;
4412
4413 case SpvExecutionModeDerivativeGroupQuadsNV:
4414 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
4415 b->shader->info.cs.derivative_group = DERIVATIVE_GROUP_QUADS;
4416 break;
4417
4418 case SpvExecutionModeDerivativeGroupLinearNV:
4419 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
4420 b->shader->info.cs.derivative_group = DERIVATIVE_GROUP_LINEAR;
4421 break;
4422
4423 case SpvExecutionModePixelInterlockOrderedEXT:
4424 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4425 b->shader->info.fs.pixel_interlock_ordered = true;
4426 break;
4427
4428 case SpvExecutionModePixelInterlockUnorderedEXT:
4429 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4430 b->shader->info.fs.pixel_interlock_unordered = true;
4431 break;
4432
4433 case SpvExecutionModeSampleInterlockOrderedEXT:
4434 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4435 b->shader->info.fs.sample_interlock_ordered = true;
4436 break;
4437
4438 case SpvExecutionModeSampleInterlockUnorderedEXT:
4439 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
4440 b->shader->info.fs.sample_interlock_unordered = true;
4441 break;
4442
4443 case SpvExecutionModeDenormPreserve:
4444 case SpvExecutionModeDenormFlushToZero:
4445 case SpvExecutionModeSignedZeroInfNanPreserve:
4446 case SpvExecutionModeRoundingModeRTE:
4447 case SpvExecutionModeRoundingModeRTZ:
4448 /* Already handled in vtn_handle_rounding_mode_in_execution_mode() */
4449 break;
4450
4451 default:
4452 vtn_fail("Unhandled execution mode: %s (%u)",
4453 spirv_executionmode_to_string(mode->exec_mode),
4454 mode->exec_mode);
4455 }
4456 }
4457
4458 static void
4459 vtn_handle_rounding_mode_in_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
4460 const struct vtn_decoration *mode, void *data)
4461 {
4462 vtn_assert(b->entry_point == entry_point);
4463
4464 unsigned execution_mode = 0;
4465
4466 switch(mode->exec_mode) {
4467 case SpvExecutionModeDenormPreserve:
4468 switch (mode->operands[0]) {
4469 case 16: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP16; break;
4470 case 32: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP32; break;
4471 case 64: execution_mode = FLOAT_CONTROLS_DENORM_PRESERVE_FP64; break;
4472 default: vtn_fail("Floating point type not supported");
4473 }
4474 break;
4475 case SpvExecutionModeDenormFlushToZero:
4476 switch (mode->operands[0]) {
4477 case 16: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP16; break;
4478 case 32: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP32; break;
4479 case 64: execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP64; break;
4480 default: vtn_fail("Floating point type not supported");
4481 }
4482 break;
4483 case SpvExecutionModeSignedZeroInfNanPreserve:
4484 switch (mode->operands[0]) {
4485 case 16: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP16; break;
4486 case 32: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP32; break;
4487 case 64: execution_mode = FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP64; break;
4488 default: vtn_fail("Floating point type not supported");
4489 }
4490 break;
4491 case SpvExecutionModeRoundingModeRTE:
4492 switch (mode->operands[0]) {
4493 case 16: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16; break;
4494 case 32: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32; break;
4495 case 64: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64; break;
4496 default: vtn_fail("Floating point type not supported");
4497 }
4498 break;
4499 case SpvExecutionModeRoundingModeRTZ:
4500 switch (mode->operands[0]) {
4501 case 16: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16; break;
4502 case 32: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32; break;
4503 case 64: execution_mode = FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64; break;
4504 default: vtn_fail("Floating point type not supported");
4505 }
4506 break;
4507
4508 default:
4509 break;
4510 }
4511
4512 b->shader->info.float_controls_execution_mode |= execution_mode;
4513 }
4514
4515 static bool
4516 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
4517 const uint32_t *w, unsigned count)
4518 {
4519 vtn_set_instruction_result_type(b, opcode, w, count);
4520
4521 switch (opcode) {
4522 case SpvOpSource:
4523 case SpvOpSourceContinued:
4524 case SpvOpSourceExtension:
4525 case SpvOpExtension:
4526 case SpvOpCapability:
4527 case SpvOpExtInstImport:
4528 case SpvOpMemoryModel:
4529 case SpvOpEntryPoint:
4530 case SpvOpExecutionMode:
4531 case SpvOpString:
4532 case SpvOpName:
4533 case SpvOpMemberName:
4534 case SpvOpDecorationGroup:
4535 case SpvOpDecorate:
4536 case SpvOpDecorateId:
4537 case SpvOpMemberDecorate:
4538 case SpvOpGroupDecorate:
4539 case SpvOpGroupMemberDecorate:
4540 case SpvOpDecorateString:
4541 case SpvOpMemberDecorateString:
4542 vtn_fail("Invalid opcode types and variables section");
4543 break;
4544
4545 case SpvOpTypeVoid:
4546 case SpvOpTypeBool:
4547 case SpvOpTypeInt:
4548 case SpvOpTypeFloat:
4549 case SpvOpTypeVector:
4550 case SpvOpTypeMatrix:
4551 case SpvOpTypeImage:
4552 case SpvOpTypeSampler:
4553 case SpvOpTypeSampledImage:
4554 case SpvOpTypeArray:
4555 case SpvOpTypeRuntimeArray:
4556 case SpvOpTypeStruct:
4557 case SpvOpTypeOpaque:
4558 case SpvOpTypePointer:
4559 case SpvOpTypeForwardPointer:
4560 case SpvOpTypeFunction:
4561 case SpvOpTypeEvent:
4562 case SpvOpTypeDeviceEvent:
4563 case SpvOpTypeReserveId:
4564 case SpvOpTypeQueue:
4565 case SpvOpTypePipe:
4566 vtn_handle_type(b, opcode, w, count);
4567 break;
4568
4569 case SpvOpConstantTrue:
4570 case SpvOpConstantFalse:
4571 case SpvOpConstant:
4572 case SpvOpConstantComposite:
4573 case SpvOpConstantSampler:
4574 case SpvOpConstantNull:
4575 case SpvOpSpecConstantTrue:
4576 case SpvOpSpecConstantFalse:
4577 case SpvOpSpecConstant:
4578 case SpvOpSpecConstantComposite:
4579 case SpvOpSpecConstantOp:
4580 vtn_handle_constant(b, opcode, w, count);
4581 break;
4582
4583 case SpvOpUndef:
4584 case SpvOpVariable:
4585 vtn_handle_variables(b, opcode, w, count);
4586 break;
4587
4588 case SpvOpExtInst: {
4589 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
4590 /* NonSemantic extended instructions are acceptable in preamble, others
4591 * will indicate the end of preamble.
4592 */
4593 return val->ext_handler == vtn_handle_non_semantic_instruction;
4594 }
4595
4596 default:
4597 return false; /* End of preamble */
4598 }
4599
4600 return true;
4601 }
4602
4603 static struct vtn_ssa_value *
4604 vtn_nir_select(struct vtn_builder *b, struct vtn_ssa_value *src0,
4605 struct vtn_ssa_value *src1, struct vtn_ssa_value *src2)
4606 {
4607 struct vtn_ssa_value *dest = rzalloc(b, struct vtn_ssa_value);
4608 dest->type = src1->type;
4609
4610 if (glsl_type_is_vector_or_scalar(src1->type)) {
4611 dest->def = nir_bcsel(&b->nb, src0->def, src1->def, src2->def);
4612 } else {
4613 unsigned elems = glsl_get_length(src1->type);
4614
4615 dest->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
4616 for (unsigned i = 0; i < elems; i++) {
4617 dest->elems[i] = vtn_nir_select(b, src0,
4618 src1->elems[i], src2->elems[i]);
4619 }
4620 }
4621
4622 return dest;
4623 }
4624
4625 static void
4626 vtn_handle_select(struct vtn_builder *b, SpvOp opcode,
4627 const uint32_t *w, unsigned count)
4628 {
4629 /* Handle OpSelect up-front here because it needs to be able to handle
4630 * pointers and not just regular vectors and scalars.
4631 */
4632 struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
4633 struct vtn_value *cond_val = vtn_untyped_value(b, w[3]);
4634 struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
4635 struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
4636
4637 vtn_fail_if(obj1_val->type != res_val->type ||
4638 obj2_val->type != res_val->type,
4639 "Object types must match the result type in OpSelect");
4640
4641 vtn_fail_if((cond_val->type->base_type != vtn_base_type_scalar &&
4642 cond_val->type->base_type != vtn_base_type_vector) ||
4643 !glsl_type_is_boolean(cond_val->type->type),
4644 "OpSelect must have either a vector of booleans or "
4645 "a boolean as Condition type");
4646
4647 vtn_fail_if(cond_val->type->base_type == vtn_base_type_vector &&
4648 (res_val->type->base_type != vtn_base_type_vector ||
4649 res_val->type->length != cond_val->type->length),
4650 "When Condition type in OpSelect is a vector, the Result "
4651 "type must be a vector of the same length");
4652
4653 switch (res_val->type->base_type) {
4654 case vtn_base_type_scalar:
4655 case vtn_base_type_vector:
4656 case vtn_base_type_matrix:
4657 case vtn_base_type_array:
4658 case vtn_base_type_struct:
4659 /* OK. */
4660 break;
4661 case vtn_base_type_pointer:
4662 /* We need to have actual storage for pointer types. */
4663 vtn_fail_if(res_val->type->type == NULL,
4664 "Invalid pointer result type for OpSelect");
4665 break;
4666 default:
4667 vtn_fail("Result type of OpSelect must be a scalar, composite, or pointer");
4668 }
4669
4670 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
4671 struct vtn_ssa_value *ssa = vtn_nir_select(b,
4672 vtn_ssa_value(b, w[3]), vtn_ssa_value(b, w[4]), vtn_ssa_value(b, w[5]));
4673
4674 vtn_push_ssa(b, w[2], res_type, ssa);
4675 }
4676
4677 static void
4678 vtn_handle_ptr(struct vtn_builder *b, SpvOp opcode,
4679 const uint32_t *w, unsigned count)
4680 {
4681 struct vtn_type *type1 = vtn_untyped_value(b, w[3])->type;
4682 struct vtn_type *type2 = vtn_untyped_value(b, w[4])->type;
4683 vtn_fail_if(type1->base_type != vtn_base_type_pointer ||
4684 type2->base_type != vtn_base_type_pointer,
4685 "%s operands must have pointer types",
4686 spirv_op_to_string(opcode));
4687 vtn_fail_if(type1->storage_class != type2->storage_class,
4688 "%s operands must have the same storage class",
4689 spirv_op_to_string(opcode));
4690
4691 struct vtn_type *vtn_type =
4692 vtn_value(b, w[1], vtn_value_type_type)->type;
4693 const struct glsl_type *type = vtn_type->type;
4694
4695 nir_address_format addr_format = vtn_mode_to_address_format(
4696 b, vtn_storage_class_to_mode(b, type1->storage_class, NULL, NULL));
4697
4698 nir_ssa_def *def;
4699
4700 switch (opcode) {
4701 case SpvOpPtrDiff: {
4702 /* OpPtrDiff returns the difference in number of elements (not byte offset). */
4703 unsigned elem_size, elem_align;
4704 glsl_get_natural_size_align_bytes(type1->deref->type,
4705 &elem_size, &elem_align);
4706
4707 def = nir_build_addr_isub(&b->nb,
4708 vtn_ssa_value(b, w[3])->def,
4709 vtn_ssa_value(b, w[4])->def,
4710 addr_format);
4711 def = nir_idiv(&b->nb, def, nir_imm_intN_t(&b->nb, elem_size, def->bit_size));
4712 def = nir_i2i(&b->nb, def, glsl_get_bit_size(type));
4713 break;
4714 }
4715
4716 case SpvOpPtrEqual:
4717 case SpvOpPtrNotEqual: {
4718 def = nir_build_addr_ieq(&b->nb,
4719 vtn_ssa_value(b, w[3])->def,
4720 vtn_ssa_value(b, w[4])->def,
4721 addr_format);
4722 if (opcode == SpvOpPtrNotEqual)
4723 def = nir_inot(&b->nb, def);
4724 break;
4725 }
4726
4727 default:
4728 unreachable("Invalid ptr operation");
4729 }
4730
4731 struct vtn_ssa_value *ssa_value = vtn_create_ssa_value(b, type);
4732 ssa_value->def = def;
4733 vtn_push_ssa(b, w[2], vtn_type, ssa_value);
4734 }
4735
4736 static bool
4737 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
4738 const uint32_t *w, unsigned count)
4739 {
4740 switch (opcode) {
4741 case SpvOpLabel:
4742 break;
4743
4744 case SpvOpLoopMerge:
4745 case SpvOpSelectionMerge:
4746 /* This is handled by cfg pre-pass and walk_blocks */
4747 break;
4748
4749 case SpvOpUndef: {
4750 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
4751 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
4752 break;
4753 }
4754
4755 case SpvOpExtInst:
4756 vtn_handle_extension(b, opcode, w, count);
4757 break;
4758
4759 case SpvOpVariable:
4760 case SpvOpLoad:
4761 case SpvOpStore:
4762 case SpvOpCopyMemory:
4763 case SpvOpCopyMemorySized:
4764 case SpvOpAccessChain:
4765 case SpvOpPtrAccessChain:
4766 case SpvOpInBoundsAccessChain:
4767 case SpvOpInBoundsPtrAccessChain:
4768 case SpvOpArrayLength:
4769 case SpvOpConvertPtrToU:
4770 case SpvOpConvertUToPtr:
4771 vtn_handle_variables(b, opcode, w, count);
4772 break;
4773
4774 case SpvOpFunctionCall:
4775 vtn_handle_function_call(b, opcode, w, count);
4776 break;
4777
4778 case SpvOpSampledImage:
4779 case SpvOpImage:
4780 case SpvOpImageSampleImplicitLod:
4781 case SpvOpImageSampleExplicitLod:
4782 case SpvOpImageSampleDrefImplicitLod:
4783 case SpvOpImageSampleDrefExplicitLod:
4784 case SpvOpImageSampleProjImplicitLod:
4785 case SpvOpImageSampleProjExplicitLod:
4786 case SpvOpImageSampleProjDrefImplicitLod:
4787 case SpvOpImageSampleProjDrefExplicitLod:
4788 case SpvOpImageFetch:
4789 case SpvOpImageGather:
4790 case SpvOpImageDrefGather:
4791 case SpvOpImageQuerySizeLod:
4792 case SpvOpImageQueryLod:
4793 case SpvOpImageQueryLevels:
4794 case SpvOpImageQuerySamples:
4795 vtn_handle_texture(b, opcode, w, count);
4796 break;
4797
4798 case SpvOpImageRead:
4799 case SpvOpImageWrite:
4800 case SpvOpImageTexelPointer:
4801 vtn_handle_image(b, opcode, w, count);
4802 break;
4803
4804 case SpvOpImageQuerySize: {
4805 struct vtn_pointer *image =
4806 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
4807 if (glsl_type_is_image(image->type->type)) {
4808 vtn_handle_image(b, opcode, w, count);
4809 } else {
4810 vtn_assert(glsl_type_is_sampler(image->type->type));
4811 vtn_handle_texture(b, opcode, w, count);
4812 }
4813 break;
4814 }
4815
4816 case SpvOpFragmentMaskFetchAMD:
4817 case SpvOpFragmentFetchAMD:
4818 vtn_handle_texture(b, opcode, w, count);
4819 break;
4820
4821 case SpvOpAtomicLoad:
4822 case SpvOpAtomicExchange:
4823 case SpvOpAtomicCompareExchange:
4824 case SpvOpAtomicCompareExchangeWeak:
4825 case SpvOpAtomicIIncrement:
4826 case SpvOpAtomicIDecrement:
4827 case SpvOpAtomicIAdd:
4828 case SpvOpAtomicISub:
4829 case SpvOpAtomicSMin:
4830 case SpvOpAtomicUMin:
4831 case SpvOpAtomicSMax:
4832 case SpvOpAtomicUMax:
4833 case SpvOpAtomicAnd:
4834 case SpvOpAtomicOr:
4835 case SpvOpAtomicXor: {
4836 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
4837 if (pointer->value_type == vtn_value_type_image_pointer) {
4838 vtn_handle_image(b, opcode, w, count);
4839 } else {
4840 vtn_assert(pointer->value_type == vtn_value_type_pointer);
4841 vtn_handle_atomics(b, opcode, w, count);
4842 }
4843 break;
4844 }
4845
4846 case SpvOpAtomicStore: {
4847 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
4848 if (pointer->value_type == vtn_value_type_image_pointer) {
4849 vtn_handle_image(b, opcode, w, count);
4850 } else {
4851 vtn_assert(pointer->value_type == vtn_value_type_pointer);
4852 vtn_handle_atomics(b, opcode, w, count);
4853 }
4854 break;
4855 }
4856
4857 case SpvOpSelect:
4858 vtn_handle_select(b, opcode, w, count);
4859 break;
4860
4861 case SpvOpSNegate:
4862 case SpvOpFNegate:
4863 case SpvOpNot:
4864 case SpvOpAny:
4865 case SpvOpAll:
4866 case SpvOpConvertFToU:
4867 case SpvOpConvertFToS:
4868 case SpvOpConvertSToF:
4869 case SpvOpConvertUToF:
4870 case SpvOpUConvert:
4871 case SpvOpSConvert:
4872 case SpvOpFConvert:
4873 case SpvOpQuantizeToF16:
4874 case SpvOpPtrCastToGeneric:
4875 case SpvOpGenericCastToPtr:
4876 case SpvOpIsNan:
4877 case SpvOpIsInf:
4878 case SpvOpIsFinite:
4879 case SpvOpIsNormal:
4880 case SpvOpSignBitSet:
4881 case SpvOpLessOrGreater:
4882 case SpvOpOrdered:
4883 case SpvOpUnordered:
4884 case SpvOpIAdd:
4885 case SpvOpFAdd:
4886 case SpvOpISub:
4887 case SpvOpFSub:
4888 case SpvOpIMul:
4889 case SpvOpFMul:
4890 case SpvOpUDiv:
4891 case SpvOpSDiv:
4892 case SpvOpFDiv:
4893 case SpvOpUMod:
4894 case SpvOpSRem:
4895 case SpvOpSMod:
4896 case SpvOpFRem:
4897 case SpvOpFMod:
4898 case SpvOpVectorTimesScalar:
4899 case SpvOpDot:
4900 case SpvOpIAddCarry:
4901 case SpvOpISubBorrow:
4902 case SpvOpUMulExtended:
4903 case SpvOpSMulExtended:
4904 case SpvOpShiftRightLogical:
4905 case SpvOpShiftRightArithmetic:
4906 case SpvOpShiftLeftLogical:
4907 case SpvOpLogicalEqual:
4908 case SpvOpLogicalNotEqual:
4909 case SpvOpLogicalOr:
4910 case SpvOpLogicalAnd:
4911 case SpvOpLogicalNot:
4912 case SpvOpBitwiseOr:
4913 case SpvOpBitwiseXor:
4914 case SpvOpBitwiseAnd:
4915 case SpvOpIEqual:
4916 case SpvOpFOrdEqual:
4917 case SpvOpFUnordEqual:
4918 case SpvOpINotEqual:
4919 case SpvOpFOrdNotEqual:
4920 case SpvOpFUnordNotEqual:
4921 case SpvOpULessThan:
4922 case SpvOpSLessThan:
4923 case SpvOpFOrdLessThan:
4924 case SpvOpFUnordLessThan:
4925 case SpvOpUGreaterThan:
4926 case SpvOpSGreaterThan:
4927 case SpvOpFOrdGreaterThan:
4928 case SpvOpFUnordGreaterThan:
4929 case SpvOpULessThanEqual:
4930 case SpvOpSLessThanEqual:
4931 case SpvOpFOrdLessThanEqual:
4932 case SpvOpFUnordLessThanEqual:
4933 case SpvOpUGreaterThanEqual:
4934 case SpvOpSGreaterThanEqual:
4935 case SpvOpFOrdGreaterThanEqual:
4936 case SpvOpFUnordGreaterThanEqual:
4937 case SpvOpDPdx:
4938 case SpvOpDPdy:
4939 case SpvOpFwidth:
4940 case SpvOpDPdxFine:
4941 case SpvOpDPdyFine:
4942 case SpvOpFwidthFine:
4943 case SpvOpDPdxCoarse:
4944 case SpvOpDPdyCoarse:
4945 case SpvOpFwidthCoarse:
4946 case SpvOpBitFieldInsert:
4947 case SpvOpBitFieldSExtract:
4948 case SpvOpBitFieldUExtract:
4949 case SpvOpBitReverse:
4950 case SpvOpBitCount:
4951 case SpvOpTranspose:
4952 case SpvOpOuterProduct:
4953 case SpvOpMatrixTimesScalar:
4954 case SpvOpVectorTimesMatrix:
4955 case SpvOpMatrixTimesVector:
4956 case SpvOpMatrixTimesMatrix:
4957 case SpvOpUCountLeadingZerosINTEL:
4958 case SpvOpUCountTrailingZerosINTEL:
4959 case SpvOpAbsISubINTEL:
4960 case SpvOpAbsUSubINTEL:
4961 case SpvOpIAddSatINTEL:
4962 case SpvOpUAddSatINTEL:
4963 case SpvOpIAverageINTEL:
4964 case SpvOpUAverageINTEL:
4965 case SpvOpIAverageRoundedINTEL:
4966 case SpvOpUAverageRoundedINTEL:
4967 case SpvOpISubSatINTEL:
4968 case SpvOpUSubSatINTEL:
4969 case SpvOpIMul32x16INTEL:
4970 case SpvOpUMul32x16INTEL:
4971 vtn_handle_alu(b, opcode, w, count);
4972 break;
4973
4974 case SpvOpBitcast:
4975 vtn_handle_bitcast(b, w, count);
4976 break;
4977
4978 case SpvOpVectorExtractDynamic:
4979 case SpvOpVectorInsertDynamic:
4980 case SpvOpVectorShuffle:
4981 case SpvOpCompositeConstruct:
4982 case SpvOpCompositeExtract:
4983 case SpvOpCompositeInsert:
4984 case SpvOpCopyLogical:
4985 case SpvOpCopyObject:
4986 vtn_handle_composite(b, opcode, w, count);
4987 break;
4988
4989 case SpvOpEmitVertex:
4990 case SpvOpEndPrimitive:
4991 case SpvOpEmitStreamVertex:
4992 case SpvOpEndStreamPrimitive:
4993 case SpvOpControlBarrier:
4994 case SpvOpMemoryBarrier:
4995 vtn_handle_barrier(b, opcode, w, count);
4996 break;
4997
4998 case SpvOpGroupNonUniformElect:
4999 case SpvOpGroupNonUniformAll:
5000 case SpvOpGroupNonUniformAny:
5001 case SpvOpGroupNonUniformAllEqual:
5002 case SpvOpGroupNonUniformBroadcast:
5003 case SpvOpGroupNonUniformBroadcastFirst:
5004 case SpvOpGroupNonUniformBallot:
5005 case SpvOpGroupNonUniformInverseBallot:
5006 case SpvOpGroupNonUniformBallotBitExtract:
5007 case SpvOpGroupNonUniformBallotBitCount:
5008 case SpvOpGroupNonUniformBallotFindLSB:
5009 case SpvOpGroupNonUniformBallotFindMSB:
5010 case SpvOpGroupNonUniformShuffle:
5011 case SpvOpGroupNonUniformShuffleXor:
5012 case SpvOpGroupNonUniformShuffleUp:
5013 case SpvOpGroupNonUniformShuffleDown:
5014 case SpvOpGroupNonUniformIAdd:
5015 case SpvOpGroupNonUniformFAdd:
5016 case SpvOpGroupNonUniformIMul:
5017 case SpvOpGroupNonUniformFMul:
5018 case SpvOpGroupNonUniformSMin:
5019 case SpvOpGroupNonUniformUMin:
5020 case SpvOpGroupNonUniformFMin:
5021 case SpvOpGroupNonUniformSMax:
5022 case SpvOpGroupNonUniformUMax:
5023 case SpvOpGroupNonUniformFMax:
5024 case SpvOpGroupNonUniformBitwiseAnd:
5025 case SpvOpGroupNonUniformBitwiseOr:
5026 case SpvOpGroupNonUniformBitwiseXor:
5027 case SpvOpGroupNonUniformLogicalAnd:
5028 case SpvOpGroupNonUniformLogicalOr:
5029 case SpvOpGroupNonUniformLogicalXor:
5030 case SpvOpGroupNonUniformQuadBroadcast:
5031 case SpvOpGroupNonUniformQuadSwap:
5032 case SpvOpGroupAll:
5033 case SpvOpGroupAny:
5034 case SpvOpGroupBroadcast:
5035 case SpvOpGroupIAdd:
5036 case SpvOpGroupFAdd:
5037 case SpvOpGroupFMin:
5038 case SpvOpGroupUMin:
5039 case SpvOpGroupSMin:
5040 case SpvOpGroupFMax:
5041 case SpvOpGroupUMax:
5042 case SpvOpGroupSMax:
5043 case SpvOpSubgroupBallotKHR:
5044 case SpvOpSubgroupFirstInvocationKHR:
5045 case SpvOpSubgroupReadInvocationKHR:
5046 case SpvOpSubgroupAllKHR:
5047 case SpvOpSubgroupAnyKHR:
5048 case SpvOpSubgroupAllEqualKHR:
5049 case SpvOpGroupIAddNonUniformAMD:
5050 case SpvOpGroupFAddNonUniformAMD:
5051 case SpvOpGroupFMinNonUniformAMD:
5052 case SpvOpGroupUMinNonUniformAMD:
5053 case SpvOpGroupSMinNonUniformAMD:
5054 case SpvOpGroupFMaxNonUniformAMD:
5055 case SpvOpGroupUMaxNonUniformAMD:
5056 case SpvOpGroupSMaxNonUniformAMD:
5057 vtn_handle_subgroup(b, opcode, w, count);
5058 break;
5059
5060 case SpvOpPtrDiff:
5061 case SpvOpPtrEqual:
5062 case SpvOpPtrNotEqual:
5063 vtn_handle_ptr(b, opcode, w, count);
5064 break;
5065
5066 case SpvOpBeginInvocationInterlockEXT:
5067 vtn_emit_barrier(b, nir_intrinsic_begin_invocation_interlock);
5068 break;
5069
5070 case SpvOpEndInvocationInterlockEXT:
5071 vtn_emit_barrier(b, nir_intrinsic_end_invocation_interlock);
5072 break;
5073
5074 case SpvOpDemoteToHelperInvocationEXT: {
5075 nir_intrinsic_instr *intrin =
5076 nir_intrinsic_instr_create(b->shader, nir_intrinsic_demote);
5077 nir_builder_instr_insert(&b->nb, &intrin->instr);
5078 break;
5079 }
5080
5081 case SpvOpIsHelperInvocationEXT: {
5082 nir_intrinsic_instr *intrin =
5083 nir_intrinsic_instr_create(b->shader, nir_intrinsic_is_helper_invocation);
5084 nir_ssa_dest_init(&intrin->instr, &intrin->dest, 1, 1, NULL);
5085 nir_builder_instr_insert(&b->nb, &intrin->instr);
5086
5087 struct vtn_type *res_type =
5088 vtn_value(b, w[1], vtn_value_type_type)->type;
5089 struct vtn_ssa_value *val = vtn_create_ssa_value(b, res_type->type);
5090 val->def = &intrin->dest.ssa;
5091
5092 vtn_push_ssa(b, w[2], res_type, val);
5093 break;
5094 }
5095
5096 case SpvOpReadClockKHR: {
5097 assert(vtn_constant_uint(b, w[3]) == SpvScopeSubgroup);
5098
5099 /* Operation supports two result types: uvec2 and uint64_t. The NIR
5100 * intrinsic gives uvec2, so pack the result for the other case.
5101 */
5102 nir_intrinsic_instr *intrin =
5103 nir_intrinsic_instr_create(b->nb.shader, nir_intrinsic_shader_clock);
5104 nir_ssa_dest_init(&intrin->instr, &intrin->dest, 2, 32, NULL);
5105 nir_builder_instr_insert(&b->nb, &intrin->instr);
5106
5107 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
5108 const struct glsl_type *dest_type = type->type;
5109 nir_ssa_def *result;
5110
5111 if (glsl_type_is_vector(dest_type)) {
5112 assert(dest_type == glsl_vector_type(GLSL_TYPE_UINT, 2));
5113 result = &intrin->dest.ssa;
5114 } else {
5115 assert(glsl_type_is_scalar(dest_type));
5116 assert(glsl_get_base_type(dest_type) == GLSL_TYPE_UINT64);
5117 result = nir_pack_64_2x32(&b->nb, &intrin->dest.ssa);
5118 }
5119
5120 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
5121 val->type = type;
5122 val->ssa = vtn_create_ssa_value(b, dest_type);
5123 val->ssa->def = result;
5124 break;
5125 }
5126
5127 case SpvOpLifetimeStart:
5128 case SpvOpLifetimeStop:
5129 break;
5130
5131 default:
5132 vtn_fail_with_opcode("Unhandled opcode", opcode);
5133 }
5134
5135 return true;
5136 }
5137
5138 struct vtn_builder*
5139 vtn_create_builder(const uint32_t *words, size_t word_count,
5140 gl_shader_stage stage, const char *entry_point_name,
5141 const struct spirv_to_nir_options *options)
5142 {
5143 /* Initialize the vtn_builder object */
5144 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
5145 struct spirv_to_nir_options *dup_options =
5146 ralloc(b, struct spirv_to_nir_options);
5147 *dup_options = *options;
5148
5149 b->spirv = words;
5150 b->spirv_word_count = word_count;
5151 b->file = NULL;
5152 b->line = -1;
5153 b->col = -1;
5154 list_inithead(&b->functions);
5155 b->entry_point_stage = stage;
5156 b->entry_point_name = entry_point_name;
5157 b->options = dup_options;
5158
5159 /*
5160 * Handle the SPIR-V header (first 5 dwords).
5161 * Can't use vtx_assert() as the setjmp(3) target isn't initialized yet.
5162 */
5163 if (word_count <= 5)
5164 goto fail;
5165
5166 if (words[0] != SpvMagicNumber) {
5167 vtn_err("words[0] was 0x%x, want 0x%x", words[0], SpvMagicNumber);
5168 goto fail;
5169 }
5170 if (words[1] < 0x10000) {
5171 vtn_err("words[1] was 0x%x, want >= 0x10000", words[1]);
5172 goto fail;
5173 }
5174
5175 uint16_t generator_id = words[2] >> 16;
5176 uint16_t generator_version = words[2];
5177
5178 /* The first GLSLang version bump actually 1.5 years after #179 was fixed
5179 * but this should at least let us shut the workaround off for modern
5180 * versions of GLSLang.
5181 */
5182 b->wa_glslang_179 = (generator_id == 8 && generator_version == 1);
5183
5184 /* In GLSLang commit 8297936dd6eb3, their handling of barrier() was fixed
5185 * to provide correct memory semantics on compute shader barrier()
5186 * commands. Prior to that, we need to fix them up ourselves. This
5187 * GLSLang fix caused them to bump to generator version 3.
5188 */
5189 b->wa_glslang_cs_barrier = (generator_id == 8 && generator_version < 3);
5190
5191 /* words[2] == generator magic */
5192 unsigned value_id_bound = words[3];
5193 if (words[4] != 0) {
5194 vtn_err("words[4] was %u, want 0", words[4]);
5195 goto fail;
5196 }
5197
5198 b->value_id_bound = value_id_bound;
5199 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
5200
5201 return b;
5202 fail:
5203 ralloc_free(b);
5204 return NULL;
5205 }
5206
5207 static nir_function *
5208 vtn_emit_kernel_entry_point_wrapper(struct vtn_builder *b,
5209 nir_function *entry_point)
5210 {
5211 vtn_assert(entry_point == b->entry_point->func->impl->function);
5212 vtn_fail_if(!entry_point->name, "entry points are required to have a name");
5213 const char *func_name =
5214 ralloc_asprintf(b->shader, "__wrapped_%s", entry_point->name);
5215
5216 /* we shouldn't have any inputs yet */
5217 vtn_assert(!entry_point->shader->num_inputs);
5218 vtn_assert(b->shader->info.stage == MESA_SHADER_KERNEL);
5219
5220 nir_function *main_entry_point = nir_function_create(b->shader, func_name);
5221 main_entry_point->impl = nir_function_impl_create(main_entry_point);
5222 nir_builder_init(&b->nb, main_entry_point->impl);
5223 b->nb.cursor = nir_after_cf_list(&main_entry_point->impl->body);
5224 b->func_param_idx = 0;
5225
5226 nir_call_instr *call = nir_call_instr_create(b->nb.shader, entry_point);
5227
5228 for (unsigned i = 0; i < entry_point->num_params; ++i) {
5229 struct vtn_type *param_type = b->entry_point->func->type->params[i];
5230
5231 /* consider all pointers to function memory to be parameters passed
5232 * by value
5233 */
5234 bool is_by_val = param_type->base_type == vtn_base_type_pointer &&
5235 param_type->storage_class == SpvStorageClassFunction;
5236
5237 /* input variable */
5238 nir_variable *in_var = rzalloc(b->nb.shader, nir_variable);
5239 in_var->data.mode = nir_var_shader_in;
5240 in_var->data.read_only = true;
5241 in_var->data.location = i;
5242
5243 if (is_by_val)
5244 in_var->type = param_type->deref->type;
5245 else
5246 in_var->type = param_type->type;
5247
5248 nir_shader_add_variable(b->nb.shader, in_var);
5249 b->nb.shader->num_inputs++;
5250
5251 /* we have to copy the entire variable into function memory */
5252 if (is_by_val) {
5253 nir_variable *copy_var =
5254 nir_local_variable_create(main_entry_point->impl, in_var->type,
5255 "copy_in");
5256 nir_copy_var(&b->nb, copy_var, in_var);
5257 call->params[i] =
5258 nir_src_for_ssa(&nir_build_deref_var(&b->nb, copy_var)->dest.ssa);
5259 } else {
5260 call->params[i] = nir_src_for_ssa(nir_load_var(&b->nb, in_var));
5261 }
5262 }
5263
5264 nir_builder_instr_insert(&b->nb, &call->instr);
5265
5266 return main_entry_point;
5267 }
5268
5269 nir_shader *
5270 spirv_to_nir(const uint32_t *words, size_t word_count,
5271 struct nir_spirv_specialization *spec, unsigned num_spec,
5272 gl_shader_stage stage, const char *entry_point_name,
5273 const struct spirv_to_nir_options *options,
5274 const nir_shader_compiler_options *nir_options)
5275
5276 {
5277 const uint32_t *word_end = words + word_count;
5278
5279 struct vtn_builder *b = vtn_create_builder(words, word_count,
5280 stage, entry_point_name,
5281 options);
5282
5283 if (b == NULL)
5284 return NULL;
5285
5286 /* See also _vtn_fail() */
5287 if (setjmp(b->fail_jump)) {
5288 ralloc_free(b);
5289 return NULL;
5290 }
5291
5292 /* Skip the SPIR-V header, handled at vtn_create_builder */
5293 words+= 5;
5294
5295 b->shader = nir_shader_create(b, stage, nir_options, NULL);
5296
5297 /* Handle all the preamble instructions */
5298 words = vtn_foreach_instruction(b, words, word_end,
5299 vtn_handle_preamble_instruction);
5300
5301 if (b->entry_point == NULL) {
5302 vtn_fail("Entry point not found");
5303 ralloc_free(b);
5304 return NULL;
5305 }
5306
5307 /* Set shader info defaults */
5308 if (stage == MESA_SHADER_GEOMETRY)
5309 b->shader->info.gs.invocations = 1;
5310
5311 /* Parse rounding mode execution modes. This has to happen earlier than
5312 * other changes in the execution modes since they can affect, for example,
5313 * the result of the floating point constants.
5314 */
5315 vtn_foreach_execution_mode(b, b->entry_point,
5316 vtn_handle_rounding_mode_in_execution_mode, NULL);
5317
5318 b->specializations = spec;
5319 b->num_specializations = num_spec;
5320
5321 /* Handle all variable, type, and constant instructions */
5322 words = vtn_foreach_instruction(b, words, word_end,
5323 vtn_handle_variable_or_type_instruction);
5324
5325 /* Parse execution modes */
5326 vtn_foreach_execution_mode(b, b->entry_point,
5327 vtn_handle_execution_mode, NULL);
5328
5329 if (b->workgroup_size_builtin) {
5330 vtn_assert(b->workgroup_size_builtin->type->type ==
5331 glsl_vector_type(GLSL_TYPE_UINT, 3));
5332
5333 nir_const_value *const_size =
5334 b->workgroup_size_builtin->constant->values;
5335
5336 b->shader->info.cs.local_size[0] = const_size[0].u32;
5337 b->shader->info.cs.local_size[1] = const_size[1].u32;
5338 b->shader->info.cs.local_size[2] = const_size[2].u32;
5339 }
5340
5341 /* Set types on all vtn_values */
5342 vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
5343
5344 vtn_build_cfg(b, words, word_end);
5345
5346 assert(b->entry_point->value_type == vtn_value_type_function);
5347 b->entry_point->func->referenced = true;
5348
5349 bool progress;
5350 do {
5351 progress = false;
5352 vtn_foreach_cf_node(node, &b->functions) {
5353 struct vtn_function *func = vtn_cf_node_as_function(node);
5354 if (func->referenced && !func->emitted) {
5355 b->const_table = _mesa_pointer_hash_table_create(b);
5356
5357 vtn_function_emit(b, func, vtn_handle_body_instruction);
5358 progress = true;
5359 }
5360 }
5361 } while (progress);
5362
5363 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
5364 nir_function *entry_point = b->entry_point->func->impl->function;
5365 vtn_assert(entry_point);
5366
5367 /* post process entry_points with input params */
5368 if (entry_point->num_params && b->shader->info.stage == MESA_SHADER_KERNEL)
5369 entry_point = vtn_emit_kernel_entry_point_wrapper(b, entry_point);
5370
5371 entry_point->is_entrypoint = true;
5372
5373 /* When multiple shader stages exist in the same SPIR-V module, we
5374 * generate input and output variables for every stage, in the same
5375 * NIR program. These dead variables can be invalid NIR. For example,
5376 * TCS outputs must be per-vertex arrays (or decorated 'patch'), while
5377 * VS output variables wouldn't be.
5378 *
5379 * To ensure we have valid NIR, we eliminate any dead inputs and outputs
5380 * right away. In order to do so, we must lower any constant initializers
5381 * on outputs so nir_remove_dead_variables sees that they're written to.
5382 */
5383 nir_lower_variable_initializers(b->shader, nir_var_shader_out);
5384 nir_remove_dead_variables(b->shader,
5385 nir_var_shader_in | nir_var_shader_out);
5386
5387 /* We sometimes generate bogus derefs that, while never used, give the
5388 * validator a bit of heartburn. Run dead code to get rid of them.
5389 */
5390 nir_opt_dce(b->shader);
5391
5392 /* Unparent the shader from the vtn_builder before we delete the builder */
5393 ralloc_steal(NULL, b->shader);
5394
5395 nir_shader *shader = b->shader;
5396 ralloc_free(b);
5397
5398 return shader;
5399 }