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