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