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