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