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