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