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