2 * Copyright © 2015 Intel Corporation
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:
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
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
24 * Jason Ekstrand (jason@jlekstrand.net)
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 "spirv_info.h"
37 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
38 size_t spirv_offset, const char *message)
40 if (b->options->debug.func) {
41 b->options->debug.func(b->options->debug.private_data,
42 level, spirv_offset, message);
46 if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
47 fprintf(stderr, "%s\n", message);
52 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
53 size_t spirv_offset, const char *fmt, ...)
59 msg = ralloc_vasprintf(NULL, fmt, args);
62 vtn_log(b, level, spirv_offset, msg);
68 vtn_log_err(struct vtn_builder *b,
69 enum nir_spirv_debug_level level, const char *prefix,
70 const char *file, unsigned line,
71 const char *fmt, va_list args)
75 msg = ralloc_strdup(NULL, prefix);
78 ralloc_asprintf_append(&msg, " In file %s:%u\n", file, line);
81 ralloc_asprintf_append(&msg, " ");
83 ralloc_vasprintf_append(&msg, fmt, args);
85 ralloc_asprintf_append(&msg, "\n %zu bytes into the SPIR-V binary",
89 ralloc_asprintf_append(&msg,
90 "\n in SPIR-V source file %s, line %d, col %d",
91 b->file, b->line, b->col);
94 vtn_log(b, level, b->spirv_offset, msg);
100 vtn_dump_shader(struct vtn_builder *b, const char *path, const char *prefix)
105 int len = snprintf(filename, sizeof(filename), "%s/%s-%d.spirv",
106 path, prefix, idx++);
107 if (len < 0 || len >= sizeof(filename))
110 FILE *f = fopen(filename, "w");
114 fwrite(b->spirv, sizeof(*b->spirv), b->spirv_word_count, f);
117 vtn_info("SPIR-V shader dumped to %s", filename);
121 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
122 const char *fmt, ...)
127 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
128 file, line, fmt, args);
133 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
134 const char *fmt, ...)
139 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
140 file, line, fmt, args);
143 const char *dump_path = getenv("MESA_SPIRV_FAIL_DUMP_PATH");
145 vtn_dump_shader(b, dump_path, "fail");
147 longjmp(b->fail_jump, 1);
150 struct spec_constant_value {
158 static struct vtn_ssa_value *
159 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
161 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
164 if (glsl_type_is_vector_or_scalar(type)) {
165 unsigned num_components = glsl_get_vector_elements(val->type);
166 unsigned bit_size = glsl_get_bit_size(val->type);
167 val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
169 unsigned elems = glsl_get_length(val->type);
170 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
171 if (glsl_type_is_matrix(type)) {
172 const struct glsl_type *elem_type =
173 glsl_vector_type(glsl_get_base_type(type),
174 glsl_get_vector_elements(type));
176 for (unsigned i = 0; i < elems; i++)
177 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
178 } else if (glsl_type_is_array(type)) {
179 const struct glsl_type *elem_type = glsl_get_array_element(type);
180 for (unsigned i = 0; i < elems; i++)
181 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
183 for (unsigned i = 0; i < elems; i++) {
184 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
185 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
193 static struct vtn_ssa_value *
194 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
195 const struct glsl_type *type)
197 struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
202 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
205 switch (glsl_get_base_type(type)) {
208 case GLSL_TYPE_INT16:
209 case GLSL_TYPE_UINT16:
210 case GLSL_TYPE_UINT8:
212 case GLSL_TYPE_INT64:
213 case GLSL_TYPE_UINT64:
215 case GLSL_TYPE_FLOAT:
216 case GLSL_TYPE_FLOAT16:
217 case GLSL_TYPE_DOUBLE: {
218 int bit_size = glsl_get_bit_size(type);
219 if (glsl_type_is_vector_or_scalar(type)) {
220 unsigned num_components = glsl_get_vector_elements(val->type);
221 nir_load_const_instr *load =
222 nir_load_const_instr_create(b->shader, num_components, bit_size);
224 load->value = constant->values[0];
226 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
227 val->def = &load->def;
229 assert(glsl_type_is_matrix(type));
230 unsigned rows = glsl_get_vector_elements(val->type);
231 unsigned columns = glsl_get_matrix_columns(val->type);
232 val->elems = ralloc_array(b, struct vtn_ssa_value *, columns);
234 for (unsigned i = 0; i < columns; i++) {
235 struct vtn_ssa_value *col_val = rzalloc(b, struct vtn_ssa_value);
236 col_val->type = glsl_get_column_type(val->type);
237 nir_load_const_instr *load =
238 nir_load_const_instr_create(b->shader, rows, bit_size);
240 load->value = constant->values[i];
242 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
243 col_val->def = &load->def;
245 val->elems[i] = col_val;
251 case GLSL_TYPE_ARRAY: {
252 unsigned elems = glsl_get_length(val->type);
253 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
254 const struct glsl_type *elem_type = glsl_get_array_element(val->type);
255 for (unsigned i = 0; i < elems; i++)
256 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
261 case GLSL_TYPE_STRUCT: {
262 unsigned elems = glsl_get_length(val->type);
263 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
264 for (unsigned i = 0; i < elems; i++) {
265 const struct glsl_type *elem_type =
266 glsl_get_struct_field(val->type, i);
267 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
274 vtn_fail("bad constant type");
280 struct vtn_ssa_value *
281 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
283 struct vtn_value *val = vtn_untyped_value(b, value_id);
284 switch (val->value_type) {
285 case vtn_value_type_undef:
286 return vtn_undef_ssa_value(b, val->type->type);
288 case vtn_value_type_constant:
289 return vtn_const_ssa_value(b, val->constant, val->type->type);
291 case vtn_value_type_ssa:
294 case vtn_value_type_pointer:
295 vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
296 struct vtn_ssa_value *ssa =
297 vtn_create_ssa_value(b, val->pointer->ptr_type->type);
298 ssa->def = vtn_pointer_to_ssa(b, val->pointer);
302 vtn_fail("Invalid type for an SSA value");
307 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
308 unsigned word_count, unsigned *words_used)
310 char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
312 /* Ammount of space taken by the string (including the null) */
313 unsigned len = strlen(dup) + 1;
314 *words_used = DIV_ROUND_UP(len, sizeof(*words));
320 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
321 const uint32_t *end, vtn_instruction_handler handler)
327 const uint32_t *w = start;
329 SpvOp opcode = w[0] & SpvOpCodeMask;
330 unsigned count = w[0] >> SpvWordCountShift;
331 vtn_assert(count >= 1 && w + count <= end);
333 b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
337 break; /* Do nothing */
340 b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
352 if (!handler(b, opcode, w, count))
370 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
371 const uint32_t *w, unsigned count)
374 case SpvOpExtInstImport: {
375 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
376 if (strcmp((const char *)&w[2], "GLSL.std.450") == 0) {
377 val->ext_handler = vtn_handle_glsl450_instruction;
378 } else if ((strcmp((const char *)&w[2], "SPV_AMD_gcn_shader") == 0)
379 && (b->options && b->options->caps.gcn_shader)) {
380 val->ext_handler = vtn_handle_amd_gcn_shader_instruction;
381 } else if ((strcmp((const char *)&w[2], "SPV_AMD_shader_trinary_minmax") == 0)
382 && (b->options && b->options->caps.trinary_minmax)) {
383 val->ext_handler = vtn_handle_amd_shader_trinary_minmax_instruction;
385 vtn_fail("Unsupported extension");
391 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
392 bool handled = val->ext_handler(b, w[4], w, count);
398 vtn_fail("Unhandled opcode");
403 _foreach_decoration_helper(struct vtn_builder *b,
404 struct vtn_value *base_value,
406 struct vtn_value *value,
407 vtn_decoration_foreach_cb cb, void *data)
409 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
411 if (dec->scope == VTN_DEC_DECORATION) {
412 member = parent_member;
413 } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
414 vtn_fail_if(value->value_type != vtn_value_type_type ||
415 value->type->base_type != vtn_base_type_struct,
416 "OpMemberDecorate and OpGroupMemberDecorate are only "
417 "allowed on OpTypeStruct");
418 /* This means we haven't recursed yet */
419 assert(value == base_value);
421 member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
423 vtn_fail_if(member >= base_value->type->length,
424 "OpMemberDecorate specifies member %d but the "
425 "OpTypeStruct has only %u members",
426 member, base_value->type->length);
428 /* Not a decoration */
429 assert(dec->scope == VTN_DEC_EXECUTION_MODE);
434 assert(dec->group->value_type == vtn_value_type_decoration_group);
435 _foreach_decoration_helper(b, base_value, member, dec->group,
438 cb(b, base_value, member, dec, data);
443 /** Iterates (recursively if needed) over all of the decorations on a value
445 * This function iterates over all of the decorations applied to a given
446 * value. If it encounters a decoration group, it recurses into the group
447 * and iterates over all of those decorations as well.
450 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
451 vtn_decoration_foreach_cb cb, void *data)
453 _foreach_decoration_helper(b, value, -1, value, cb, data);
457 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
458 vtn_execution_mode_foreach_cb cb, void *data)
460 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
461 if (dec->scope != VTN_DEC_EXECUTION_MODE)
464 assert(dec->group == NULL);
465 cb(b, value, dec, data);
470 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
471 const uint32_t *w, unsigned count)
473 const uint32_t *w_end = w + count;
474 const uint32_t target = w[1];
478 case SpvOpDecorationGroup:
479 vtn_push_value(b, target, vtn_value_type_decoration_group);
483 case SpvOpMemberDecorate:
484 case SpvOpExecutionMode: {
485 struct vtn_value *val = vtn_untyped_value(b, target);
487 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
490 dec->scope = VTN_DEC_DECORATION;
492 case SpvOpMemberDecorate:
493 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(w++);
494 vtn_fail_if(dec->scope < VTN_DEC_STRUCT_MEMBER0, /* overflow */
495 "Member argument of OpMemberDecorate too large");
497 case SpvOpExecutionMode:
498 dec->scope = VTN_DEC_EXECUTION_MODE;
501 unreachable("Invalid decoration opcode");
503 dec->decoration = *(w++);
506 /* Link into the list */
507 dec->next = val->decoration;
508 val->decoration = dec;
512 case SpvOpGroupMemberDecorate:
513 case SpvOpGroupDecorate: {
514 struct vtn_value *group =
515 vtn_value(b, target, vtn_value_type_decoration_group);
517 for (; w < w_end; w++) {
518 struct vtn_value *val = vtn_untyped_value(b, *w);
519 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
522 if (opcode == SpvOpGroupDecorate) {
523 dec->scope = VTN_DEC_DECORATION;
525 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
526 vtn_fail_if(dec->scope < 0, /* Check for overflow */
527 "Member argument of OpGroupMemberDecorate too large");
530 /* Link into the list */
531 dec->next = val->decoration;
532 val->decoration = dec;
538 unreachable("Unhandled opcode");
542 struct member_decoration_ctx {
544 struct glsl_struct_field *fields;
545 struct vtn_type *type;
548 /** Returns true if two types are "compatible", i.e. you can do an OpLoad,
549 * OpStore, or OpCopyMemory between them without breaking anything.
550 * Technically, the SPIR-V rules require the exact same type ID but this lets
551 * us internally be a bit looser.
554 vtn_types_compatible(struct vtn_builder *b,
555 struct vtn_type *t1, struct vtn_type *t2)
557 if (t1->id == t2->id)
560 if (t1->base_type != t2->base_type)
563 switch (t1->base_type) {
564 case vtn_base_type_void:
565 case vtn_base_type_scalar:
566 case vtn_base_type_vector:
567 case vtn_base_type_matrix:
568 case vtn_base_type_image:
569 case vtn_base_type_sampler:
570 case vtn_base_type_sampled_image:
571 return t1->type == t2->type;
573 case vtn_base_type_array:
574 return t1->length == t2->length &&
575 vtn_types_compatible(b, t1->array_element, t2->array_element);
577 case vtn_base_type_pointer:
578 return vtn_types_compatible(b, t1->deref, t2->deref);
580 case vtn_base_type_struct:
581 if (t1->length != t2->length)
584 for (unsigned i = 0; i < t1->length; i++) {
585 if (!vtn_types_compatible(b, t1->members[i], t2->members[i]))
590 case vtn_base_type_function:
591 /* This case shouldn't get hit since you can't copy around function
592 * types. Just require them to be identical.
597 vtn_fail("Invalid base type");
600 /* does a shallow copy of a vtn_type */
602 static struct vtn_type *
603 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
605 struct vtn_type *dest = ralloc(b, struct vtn_type);
608 switch (src->base_type) {
609 case vtn_base_type_void:
610 case vtn_base_type_scalar:
611 case vtn_base_type_vector:
612 case vtn_base_type_matrix:
613 case vtn_base_type_array:
614 case vtn_base_type_pointer:
615 case vtn_base_type_image:
616 case vtn_base_type_sampler:
617 case vtn_base_type_sampled_image:
618 /* Nothing more to do */
621 case vtn_base_type_struct:
622 dest->members = ralloc_array(b, struct vtn_type *, src->length);
623 memcpy(dest->members, src->members,
624 src->length * sizeof(src->members[0]));
626 dest->offsets = ralloc_array(b, unsigned, src->length);
627 memcpy(dest->offsets, src->offsets,
628 src->length * sizeof(src->offsets[0]));
631 case vtn_base_type_function:
632 dest->params = ralloc_array(b, struct vtn_type *, src->length);
633 memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
640 static struct vtn_type *
641 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
643 type->members[member] = vtn_type_copy(b, type->members[member]);
644 type = type->members[member];
646 /* We may have an array of matrices.... Oh, joy! */
647 while (glsl_type_is_array(type->type)) {
648 type->array_element = vtn_type_copy(b, type->array_element);
649 type = type->array_element;
652 vtn_assert(glsl_type_is_matrix(type->type));
658 struct_member_decoration_cb(struct vtn_builder *b,
659 struct vtn_value *val, int member,
660 const struct vtn_decoration *dec, void *void_ctx)
662 struct member_decoration_ctx *ctx = void_ctx;
667 assert(member < ctx->num_fields);
669 switch (dec->decoration) {
670 case SpvDecorationNonWritable:
671 case SpvDecorationNonReadable:
672 case SpvDecorationRelaxedPrecision:
673 case SpvDecorationVolatile:
674 case SpvDecorationCoherent:
675 case SpvDecorationUniform:
676 break; /* FIXME: Do nothing with this for now. */
677 case SpvDecorationNoPerspective:
678 ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
680 case SpvDecorationFlat:
681 ctx->fields[member].interpolation = INTERP_MODE_FLAT;
683 case SpvDecorationCentroid:
684 ctx->fields[member].centroid = true;
686 case SpvDecorationSample:
687 ctx->fields[member].sample = true;
689 case SpvDecorationStream:
690 /* Vulkan only allows one GS stream */
691 vtn_assert(dec->literals[0] == 0);
693 case SpvDecorationLocation:
694 ctx->fields[member].location = dec->literals[0];
696 case SpvDecorationComponent:
697 break; /* FIXME: What should we do with these? */
698 case SpvDecorationBuiltIn:
699 ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
700 ctx->type->members[member]->is_builtin = true;
701 ctx->type->members[member]->builtin = dec->literals[0];
702 ctx->type->builtin_block = true;
704 case SpvDecorationOffset:
705 ctx->type->offsets[member] = dec->literals[0];
707 case SpvDecorationMatrixStride:
708 /* Handled as a second pass */
710 case SpvDecorationColMajor:
711 break; /* Nothing to do here. Column-major is the default. */
712 case SpvDecorationRowMajor:
713 mutable_matrix_member(b, ctx->type, member)->row_major = true;
716 case SpvDecorationPatch:
719 case SpvDecorationSpecId:
720 case SpvDecorationBlock:
721 case SpvDecorationBufferBlock:
722 case SpvDecorationArrayStride:
723 case SpvDecorationGLSLShared:
724 case SpvDecorationGLSLPacked:
725 case SpvDecorationInvariant:
726 case SpvDecorationRestrict:
727 case SpvDecorationAliased:
728 case SpvDecorationConstant:
729 case SpvDecorationIndex:
730 case SpvDecorationBinding:
731 case SpvDecorationDescriptorSet:
732 case SpvDecorationLinkageAttributes:
733 case SpvDecorationNoContraction:
734 case SpvDecorationInputAttachmentIndex:
735 vtn_warn("Decoration not allowed on struct members: %s",
736 spirv_decoration_to_string(dec->decoration));
739 case SpvDecorationXfbBuffer:
740 case SpvDecorationXfbStride:
741 vtn_warn("Vulkan does not have transform feedback");
744 case SpvDecorationCPacked:
745 case SpvDecorationSaturatedConversion:
746 case SpvDecorationFuncParamAttr:
747 case SpvDecorationFPRoundingMode:
748 case SpvDecorationFPFastMathMode:
749 case SpvDecorationAlignment:
750 vtn_warn("Decoration only allowed for CL-style kernels: %s",
751 spirv_decoration_to_string(dec->decoration));
755 vtn_fail("Unhandled decoration");
759 /* Matrix strides are handled as a separate pass because we need to know
760 * whether the matrix is row-major or not first.
763 struct_member_matrix_stride_cb(struct vtn_builder *b,
764 struct vtn_value *val, int member,
765 const struct vtn_decoration *dec,
768 if (dec->decoration != SpvDecorationMatrixStride)
771 vtn_fail_if(member < 0,
772 "The MatrixStride decoration is only allowed on members "
775 struct member_decoration_ctx *ctx = void_ctx;
777 struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
778 if (mat_type->row_major) {
779 mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
780 mat_type->stride = mat_type->array_element->stride;
781 mat_type->array_element->stride = dec->literals[0];
783 vtn_assert(mat_type->array_element->stride > 0);
784 mat_type->stride = dec->literals[0];
789 type_decoration_cb(struct vtn_builder *b,
790 struct vtn_value *val, int member,
791 const struct vtn_decoration *dec, void *ctx)
793 struct vtn_type *type = val->type;
796 /* This should have been handled by OpTypeStruct */
797 assert(val->type->base_type == vtn_base_type_struct);
798 assert(member >= 0 && member < val->type->length);
802 switch (dec->decoration) {
803 case SpvDecorationArrayStride:
804 vtn_assert(type->base_type == vtn_base_type_matrix ||
805 type->base_type == vtn_base_type_array ||
806 type->base_type == vtn_base_type_pointer);
807 type->stride = dec->literals[0];
809 case SpvDecorationBlock:
810 vtn_assert(type->base_type == vtn_base_type_struct);
813 case SpvDecorationBufferBlock:
814 vtn_assert(type->base_type == vtn_base_type_struct);
815 type->buffer_block = true;
817 case SpvDecorationGLSLShared:
818 case SpvDecorationGLSLPacked:
819 /* Ignore these, since we get explicit offsets anyways */
822 case SpvDecorationRowMajor:
823 case SpvDecorationColMajor:
824 case SpvDecorationMatrixStride:
825 case SpvDecorationBuiltIn:
826 case SpvDecorationNoPerspective:
827 case SpvDecorationFlat:
828 case SpvDecorationPatch:
829 case SpvDecorationCentroid:
830 case SpvDecorationSample:
831 case SpvDecorationVolatile:
832 case SpvDecorationCoherent:
833 case SpvDecorationNonWritable:
834 case SpvDecorationNonReadable:
835 case SpvDecorationUniform:
836 case SpvDecorationStream:
837 case SpvDecorationLocation:
838 case SpvDecorationComponent:
839 case SpvDecorationOffset:
840 case SpvDecorationXfbBuffer:
841 case SpvDecorationXfbStride:
842 vtn_warn("Decoration only allowed for struct members: %s",
843 spirv_decoration_to_string(dec->decoration));
846 case SpvDecorationRelaxedPrecision:
847 case SpvDecorationSpecId:
848 case SpvDecorationInvariant:
849 case SpvDecorationRestrict:
850 case SpvDecorationAliased:
851 case SpvDecorationConstant:
852 case SpvDecorationIndex:
853 case SpvDecorationBinding:
854 case SpvDecorationDescriptorSet:
855 case SpvDecorationLinkageAttributes:
856 case SpvDecorationNoContraction:
857 case SpvDecorationInputAttachmentIndex:
858 vtn_warn("Decoration not allowed on types: %s",
859 spirv_decoration_to_string(dec->decoration));
862 case SpvDecorationCPacked:
863 case SpvDecorationSaturatedConversion:
864 case SpvDecorationFuncParamAttr:
865 case SpvDecorationFPRoundingMode:
866 case SpvDecorationFPFastMathMode:
867 case SpvDecorationAlignment:
868 vtn_warn("Decoration only allowed for CL-style kernels: %s",
869 spirv_decoration_to_string(dec->decoration));
873 vtn_fail("Unhandled decoration");
878 translate_image_format(struct vtn_builder *b, SpvImageFormat format)
881 case SpvImageFormatUnknown: return 0; /* GL_NONE */
882 case SpvImageFormatRgba32f: return 0x8814; /* GL_RGBA32F */
883 case SpvImageFormatRgba16f: return 0x881A; /* GL_RGBA16F */
884 case SpvImageFormatR32f: return 0x822E; /* GL_R32F */
885 case SpvImageFormatRgba8: return 0x8058; /* GL_RGBA8 */
886 case SpvImageFormatRgba8Snorm: return 0x8F97; /* GL_RGBA8_SNORM */
887 case SpvImageFormatRg32f: return 0x8230; /* GL_RG32F */
888 case SpvImageFormatRg16f: return 0x822F; /* GL_RG16F */
889 case SpvImageFormatR11fG11fB10f: return 0x8C3A; /* GL_R11F_G11F_B10F */
890 case SpvImageFormatR16f: return 0x822D; /* GL_R16F */
891 case SpvImageFormatRgba16: return 0x805B; /* GL_RGBA16 */
892 case SpvImageFormatRgb10A2: return 0x8059; /* GL_RGB10_A2 */
893 case SpvImageFormatRg16: return 0x822C; /* GL_RG16 */
894 case SpvImageFormatRg8: return 0x822B; /* GL_RG8 */
895 case SpvImageFormatR16: return 0x822A; /* GL_R16 */
896 case SpvImageFormatR8: return 0x8229; /* GL_R8 */
897 case SpvImageFormatRgba16Snorm: return 0x8F9B; /* GL_RGBA16_SNORM */
898 case SpvImageFormatRg16Snorm: return 0x8F99; /* GL_RG16_SNORM */
899 case SpvImageFormatRg8Snorm: return 0x8F95; /* GL_RG8_SNORM */
900 case SpvImageFormatR16Snorm: return 0x8F98; /* GL_R16_SNORM */
901 case SpvImageFormatR8Snorm: return 0x8F94; /* GL_R8_SNORM */
902 case SpvImageFormatRgba32i: return 0x8D82; /* GL_RGBA32I */
903 case SpvImageFormatRgba16i: return 0x8D88; /* GL_RGBA16I */
904 case SpvImageFormatRgba8i: return 0x8D8E; /* GL_RGBA8I */
905 case SpvImageFormatR32i: return 0x8235; /* GL_R32I */
906 case SpvImageFormatRg32i: return 0x823B; /* GL_RG32I */
907 case SpvImageFormatRg16i: return 0x8239; /* GL_RG16I */
908 case SpvImageFormatRg8i: return 0x8237; /* GL_RG8I */
909 case SpvImageFormatR16i: return 0x8233; /* GL_R16I */
910 case SpvImageFormatR8i: return 0x8231; /* GL_R8I */
911 case SpvImageFormatRgba32ui: return 0x8D70; /* GL_RGBA32UI */
912 case SpvImageFormatRgba16ui: return 0x8D76; /* GL_RGBA16UI */
913 case SpvImageFormatRgba8ui: return 0x8D7C; /* GL_RGBA8UI */
914 case SpvImageFormatR32ui: return 0x8236; /* GL_R32UI */
915 case SpvImageFormatRgb10a2ui: return 0x906F; /* GL_RGB10_A2UI */
916 case SpvImageFormatRg32ui: return 0x823C; /* GL_RG32UI */
917 case SpvImageFormatRg16ui: return 0x823A; /* GL_RG16UI */
918 case SpvImageFormatRg8ui: return 0x8238; /* GL_RG8UI */
919 case SpvImageFormatR16ui: return 0x8234; /* GL_R16UI */
920 case SpvImageFormatR8ui: return 0x8232; /* GL_R8UI */
922 vtn_fail("Invalid image format");
926 static struct vtn_type *
927 vtn_type_layout_std430(struct vtn_builder *b, struct vtn_type *type,
928 uint32_t *size_out, uint32_t *align_out)
930 switch (type->base_type) {
931 case vtn_base_type_scalar: {
932 uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
933 *size_out = comp_size;
934 *align_out = comp_size;
938 case vtn_base_type_vector: {
939 uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
940 unsigned align_comps = type->length == 3 ? 4 : type->length;
941 *size_out = comp_size * type->length,
942 *align_out = comp_size * align_comps;
946 case vtn_base_type_matrix:
947 case vtn_base_type_array: {
948 /* We're going to add an array stride */
949 type = vtn_type_copy(b, type);
950 uint32_t elem_size, elem_align;
951 type->array_element = vtn_type_layout_std430(b, type->array_element,
952 &elem_size, &elem_align);
953 type->stride = vtn_align_u32(elem_size, elem_align);
954 *size_out = type->stride * type->length;
955 *align_out = elem_align;
959 case vtn_base_type_struct: {
960 /* We're going to add member offsets */
961 type = vtn_type_copy(b, type);
964 for (unsigned i = 0; i < type->length; i++) {
965 uint32_t mem_size, mem_align;
966 type->members[i] = vtn_type_layout_std430(b, type->members[i],
967 &mem_size, &mem_align);
968 offset = vtn_align_u32(offset, mem_align);
969 type->offsets[i] = offset;
971 align = MAX2(align, mem_align);
979 unreachable("Invalid SPIR-V type for std430");
984 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
985 const uint32_t *w, unsigned count)
987 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_type);
989 val->type = rzalloc(b, struct vtn_type);
990 val->type->id = w[1];
994 val->type->base_type = vtn_base_type_void;
995 val->type->type = glsl_void_type();
998 val->type->base_type = vtn_base_type_scalar;
999 val->type->type = glsl_bool_type();
1000 val->type->length = 1;
1002 case SpvOpTypeInt: {
1003 int bit_size = w[2];
1004 const bool signedness = w[3];
1005 val->type->base_type = vtn_base_type_scalar;
1008 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1011 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1014 val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1017 val->type->type = (signedness ? glsl_int8_t_type() : glsl_uint8_t_type());
1020 vtn_fail("Invalid int bit size");
1022 val->type->length = 1;
1026 case SpvOpTypeFloat: {
1027 int bit_size = w[2];
1028 val->type->base_type = vtn_base_type_scalar;
1031 val->type->type = glsl_float16_t_type();
1034 val->type->type = glsl_float_type();
1037 val->type->type = glsl_double_type();
1040 vtn_fail("Invalid float bit size");
1042 val->type->length = 1;
1046 case SpvOpTypeVector: {
1047 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1048 unsigned elems = w[3];
1050 vtn_fail_if(base->base_type != vtn_base_type_scalar,
1051 "Base type for OpTypeVector must be a scalar");
1052 vtn_fail_if((elems < 2 || elems > 4) && (elems != 8) && (elems != 16),
1053 "Invalid component count for OpTypeVector");
1055 val->type->base_type = vtn_base_type_vector;
1056 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1057 val->type->length = elems;
1058 val->type->stride = glsl_get_bit_size(base->type) / 8;
1059 val->type->array_element = base;
1063 case SpvOpTypeMatrix: {
1064 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1065 unsigned columns = w[3];
1067 vtn_fail_if(base->base_type != vtn_base_type_vector,
1068 "Base type for OpTypeMatrix must be a vector");
1069 vtn_fail_if(columns < 2 || columns > 4,
1070 "Invalid column count for OpTypeMatrix");
1072 val->type->base_type = vtn_base_type_matrix;
1073 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1074 glsl_get_vector_elements(base->type),
1076 vtn_fail_if(glsl_type_is_error(val->type->type),
1077 "Unsupported base type for OpTypeMatrix");
1078 assert(!glsl_type_is_error(val->type->type));
1079 val->type->length = columns;
1080 val->type->array_element = base;
1081 val->type->row_major = false;
1082 val->type->stride = 0;
1086 case SpvOpTypeRuntimeArray:
1087 case SpvOpTypeArray: {
1088 struct vtn_type *array_element =
1089 vtn_value(b, w[2], vtn_value_type_type)->type;
1091 if (opcode == SpvOpTypeRuntimeArray) {
1092 /* A length of 0 is used to denote unsized arrays */
1093 val->type->length = 0;
1096 vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
1099 val->type->base_type = vtn_base_type_array;
1100 val->type->type = glsl_array_type(array_element->type, val->type->length);
1101 val->type->array_element = array_element;
1102 val->type->stride = 0;
1106 case SpvOpTypeStruct: {
1107 unsigned num_fields = count - 2;
1108 val->type->base_type = vtn_base_type_struct;
1109 val->type->length = num_fields;
1110 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1111 val->type->offsets = ralloc_array(b, unsigned, num_fields);
1113 NIR_VLA(struct glsl_struct_field, fields, count);
1114 for (unsigned i = 0; i < num_fields; i++) {
1115 val->type->members[i] =
1116 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
1117 fields[i] = (struct glsl_struct_field) {
1118 .type = val->type->members[i]->type,
1119 .name = ralloc_asprintf(b, "field%d", i),
1124 struct member_decoration_ctx ctx = {
1125 .num_fields = num_fields,
1130 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1131 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1133 const char *name = val->name ? val->name : "struct";
1135 val->type->type = glsl_struct_type(fields, num_fields, name);
1139 case SpvOpTypeFunction: {
1140 val->type->base_type = vtn_base_type_function;
1141 val->type->type = NULL;
1143 val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
1145 const unsigned num_params = count - 3;
1146 val->type->length = num_params;
1147 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1148 for (unsigned i = 0; i < count - 3; i++) {
1149 val->type->params[i] =
1150 vtn_value(b, w[i + 3], vtn_value_type_type)->type;
1155 case SpvOpTypePointer: {
1156 SpvStorageClass storage_class = w[2];
1157 struct vtn_type *deref_type =
1158 vtn_value(b, w[3], vtn_value_type_type)->type;
1160 val->type->base_type = vtn_base_type_pointer;
1161 val->type->storage_class = storage_class;
1162 val->type->deref = deref_type;
1164 if (storage_class == SpvStorageClassUniform ||
1165 storage_class == SpvStorageClassStorageBuffer) {
1166 /* These can actually be stored to nir_variables and used as SSA
1167 * values so they need a real glsl_type.
1169 val->type->type = glsl_vector_type(GLSL_TYPE_UINT, 2);
1172 if (storage_class == SpvStorageClassWorkgroup &&
1173 b->options->lower_workgroup_access_to_offsets) {
1174 uint32_t size, align;
1175 val->type->deref = vtn_type_layout_std430(b, val->type->deref,
1177 val->type->length = size;
1178 val->type->align = align;
1179 /* These can actually be stored to nir_variables and used as SSA
1180 * values so they need a real glsl_type.
1182 val->type->type = glsl_uint_type();
1187 case SpvOpTypeImage: {
1188 val->type->base_type = vtn_base_type_image;
1190 const struct vtn_type *sampled_type =
1191 vtn_value(b, w[2], vtn_value_type_type)->type;
1193 vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1194 glsl_get_bit_size(sampled_type->type) != 32,
1195 "Sampled type of OpTypeImage must be a 32-bit scalar");
1197 enum glsl_sampler_dim dim;
1198 switch ((SpvDim)w[3]) {
1199 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
1200 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
1201 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
1202 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
1203 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
1204 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
1205 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1207 vtn_fail("Invalid SPIR-V image dimensionality");
1210 bool is_shadow = w[4];
1211 bool is_array = w[5];
1212 bool multisampled = w[6];
1213 unsigned sampled = w[7];
1214 SpvImageFormat format = w[8];
1217 val->type->access_qualifier = w[9];
1219 val->type->access_qualifier = SpvAccessQualifierReadWrite;
1222 if (dim == GLSL_SAMPLER_DIM_2D)
1223 dim = GLSL_SAMPLER_DIM_MS;
1224 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1225 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1227 vtn_fail("Unsupported multisampled image type");
1230 val->type->image_format = translate_image_format(b, format);
1232 enum glsl_base_type sampled_base_type =
1233 glsl_get_base_type(sampled_type->type);
1235 val->type->sampled = true;
1236 val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
1238 } else if (sampled == 2) {
1239 vtn_assert(!is_shadow);
1240 val->type->sampled = false;
1241 val->type->type = glsl_image_type(dim, is_array, sampled_base_type);
1243 vtn_fail("We need to know if the image will be sampled");
1248 case SpvOpTypeSampledImage:
1249 val->type->base_type = vtn_base_type_sampled_image;
1250 val->type->image = vtn_value(b, w[2], vtn_value_type_type)->type;
1251 val->type->type = val->type->image->type;
1254 case SpvOpTypeSampler:
1255 /* The actual sampler type here doesn't really matter. It gets
1256 * thrown away the moment you combine it with an image. What really
1257 * matters is that it's a sampler type as opposed to an integer type
1258 * so the backend knows what to do.
1260 val->type->base_type = vtn_base_type_sampler;
1261 val->type->type = glsl_bare_sampler_type();
1264 case SpvOpTypeOpaque:
1265 case SpvOpTypeEvent:
1266 case SpvOpTypeDeviceEvent:
1267 case SpvOpTypeReserveId:
1268 case SpvOpTypeQueue:
1271 vtn_fail("Unhandled opcode");
1274 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1277 static nir_constant *
1278 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
1280 nir_constant *c = rzalloc(b, nir_constant);
1282 /* For pointers and other typeless things, we have to return something but
1283 * it doesn't matter what.
1288 switch (glsl_get_base_type(type)) {
1290 case GLSL_TYPE_UINT:
1291 case GLSL_TYPE_INT16:
1292 case GLSL_TYPE_UINT16:
1293 case GLSL_TYPE_UINT8:
1294 case GLSL_TYPE_INT8:
1295 case GLSL_TYPE_INT64:
1296 case GLSL_TYPE_UINT64:
1297 case GLSL_TYPE_BOOL:
1298 case GLSL_TYPE_FLOAT:
1299 case GLSL_TYPE_FLOAT16:
1300 case GLSL_TYPE_DOUBLE:
1301 /* Nothing to do here. It's already initialized to zero */
1304 case GLSL_TYPE_ARRAY:
1305 vtn_assert(glsl_get_length(type) > 0);
1306 c->num_elements = glsl_get_length(type);
1307 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1309 c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
1310 for (unsigned i = 1; i < c->num_elements; i++)
1311 c->elements[i] = c->elements[0];
1314 case GLSL_TYPE_STRUCT:
1315 c->num_elements = glsl_get_length(type);
1316 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1318 for (unsigned i = 0; i < c->num_elements; i++) {
1319 c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
1324 vtn_fail("Invalid type for null constant");
1331 spec_constant_decoration_cb(struct vtn_builder *b, struct vtn_value *v,
1332 int member, const struct vtn_decoration *dec,
1335 vtn_assert(member == -1);
1336 if (dec->decoration != SpvDecorationSpecId)
1339 struct spec_constant_value *const_value = data;
1341 for (unsigned i = 0; i < b->num_specializations; i++) {
1342 if (b->specializations[i].id == dec->literals[0]) {
1343 if (const_value->is_double)
1344 const_value->data64 = b->specializations[i].data64;
1346 const_value->data32 = b->specializations[i].data32;
1353 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1354 uint32_t const_value)
1356 struct spec_constant_value data;
1357 data.is_double = false;
1358 data.data32 = const_value;
1359 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1364 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1365 uint64_t const_value)
1367 struct spec_constant_value data;
1368 data.is_double = true;
1369 data.data64 = const_value;
1370 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1375 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1376 struct vtn_value *val,
1378 const struct vtn_decoration *dec,
1381 vtn_assert(member == -1);
1382 if (dec->decoration != SpvDecorationBuiltIn ||
1383 dec->literals[0] != SpvBuiltInWorkgroupSize)
1386 vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1388 b->shader->info.cs.local_size[0] = val->constant->values[0].u32[0];
1389 b->shader->info.cs.local_size[1] = val->constant->values[0].u32[1];
1390 b->shader->info.cs.local_size[2] = val->constant->values[0].u32[2];
1394 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1395 const uint32_t *w, unsigned count)
1397 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1398 val->constant = rzalloc(b, nir_constant);
1400 case SpvOpConstantTrue:
1401 case SpvOpConstantFalse:
1402 case SpvOpSpecConstantTrue:
1403 case SpvOpSpecConstantFalse: {
1404 vtn_fail_if(val->type->type != glsl_bool_type(),
1405 "Result type of %s must be OpTypeBool",
1406 spirv_op_to_string(opcode));
1408 uint32_t int_val = (opcode == SpvOpConstantTrue ||
1409 opcode == SpvOpSpecConstantTrue);
1411 if (opcode == SpvOpSpecConstantTrue ||
1412 opcode == SpvOpSpecConstantFalse)
1413 int_val = get_specialization(b, val, int_val);
1415 val->constant->values[0].u32[0] = int_val ? NIR_TRUE : NIR_FALSE;
1419 case SpvOpConstant: {
1420 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1421 "Result type of %s must be a scalar",
1422 spirv_op_to_string(opcode));
1423 int bit_size = glsl_get_bit_size(val->type->type);
1426 val->constant->values->u64[0] = vtn_u64_literal(&w[3]);
1429 val->constant->values->u32[0] = w[3];
1432 val->constant->values->u16[0] = w[3];
1435 val->constant->values->u8[0] = w[3];
1438 vtn_fail("Unsupported SpvOpConstant bit size");
1443 case SpvOpSpecConstant: {
1444 vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1445 "Result type of %s must be a scalar",
1446 spirv_op_to_string(opcode));
1447 int bit_size = glsl_get_bit_size(val->type->type);
1450 val->constant->values[0].u64[0] =
1451 get_specialization64(b, val, vtn_u64_literal(&w[3]));
1454 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1457 val->constant->values[0].u16[0] = get_specialization(b, val, w[3]);
1460 val->constant->values[0].u8[0] = get_specialization(b, val, w[3]);
1463 vtn_fail("Unsupported SpvOpSpecConstant bit size");
1468 case SpvOpSpecConstantComposite:
1469 case SpvOpConstantComposite: {
1470 unsigned elem_count = count - 3;
1471 vtn_fail_if(elem_count != val->type->length,
1472 "%s has %u constituents, expected %u",
1473 spirv_op_to_string(opcode), elem_count, val->type->length);
1475 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1476 for (unsigned i = 0; i < elem_count; i++)
1477 elems[i] = vtn_value(b, w[i + 3], vtn_value_type_constant)->constant;
1479 switch (val->type->base_type) {
1480 case vtn_base_type_vector: {
1481 assert(glsl_type_is_vector(val->type->type));
1482 int bit_size = glsl_get_bit_size(val->type->type);
1483 for (unsigned i = 0; i < elem_count; i++) {
1486 val->constant->values[0].u64[i] = elems[i]->values[0].u64[0];
1489 val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1492 val->constant->values[0].u16[i] = elems[i]->values[0].u16[0];
1495 val->constant->values[0].u8[i] = elems[i]->values[0].u8[0];
1498 vtn_fail("Invalid SpvOpConstantComposite bit size");
1504 case vtn_base_type_matrix:
1505 assert(glsl_type_is_matrix(val->type->type));
1506 for (unsigned i = 0; i < elem_count; i++)
1507 val->constant->values[i] = elems[i]->values[0];
1510 case vtn_base_type_struct:
1511 case vtn_base_type_array:
1512 ralloc_steal(val->constant, elems);
1513 val->constant->num_elements = elem_count;
1514 val->constant->elements = elems;
1518 vtn_fail("Result type of %s must be a composite type",
1519 spirv_op_to_string(opcode));
1524 case SpvOpSpecConstantOp: {
1525 SpvOp opcode = get_specialization(b, val, w[3]);
1527 case SpvOpVectorShuffle: {
1528 struct vtn_value *v0 = &b->values[w[4]];
1529 struct vtn_value *v1 = &b->values[w[5]];
1531 vtn_assert(v0->value_type == vtn_value_type_constant ||
1532 v0->value_type == vtn_value_type_undef);
1533 vtn_assert(v1->value_type == vtn_value_type_constant ||
1534 v1->value_type == vtn_value_type_undef);
1536 unsigned len0 = glsl_get_vector_elements(v0->type->type);
1537 unsigned len1 = glsl_get_vector_elements(v1->type->type);
1539 vtn_assert(len0 + len1 < 16);
1541 unsigned bit_size = glsl_get_bit_size(val->type->type);
1542 unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1543 unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1545 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1546 (void)bit_size0; (void)bit_size1;
1548 if (bit_size == 64) {
1550 if (v0->value_type == vtn_value_type_constant) {
1551 for (unsigned i = 0; i < len0; i++)
1552 u64[i] = v0->constant->values[0].u64[i];
1554 if (v1->value_type == vtn_value_type_constant) {
1555 for (unsigned i = 0; i < len1; i++)
1556 u64[len0 + i] = v1->constant->values[0].u64[i];
1559 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1560 uint32_t comp = w[i + 6];
1561 /* If component is not used, set the value to a known constant
1562 * to detect if it is wrongly used.
1564 if (comp == (uint32_t)-1)
1565 val->constant->values[0].u64[j] = 0xdeadbeefdeadbeef;
1567 val->constant->values[0].u64[j] = u64[comp];
1570 /* This is for both 32-bit and 16-bit values */
1572 if (v0->value_type == vtn_value_type_constant) {
1573 for (unsigned i = 0; i < len0; i++)
1574 u32[i] = v0->constant->values[0].u32[i];
1576 if (v1->value_type == vtn_value_type_constant) {
1577 for (unsigned i = 0; i < len1; i++)
1578 u32[len0 + i] = v1->constant->values[0].u32[i];
1581 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1582 uint32_t comp = w[i + 6];
1583 /* If component is not used, set the value to a known constant
1584 * to detect if it is wrongly used.
1586 if (comp == (uint32_t)-1)
1587 val->constant->values[0].u32[j] = 0xdeadbeef;
1589 val->constant->values[0].u32[j] = u32[comp];
1595 case SpvOpCompositeExtract:
1596 case SpvOpCompositeInsert: {
1597 struct vtn_value *comp;
1598 unsigned deref_start;
1599 struct nir_constant **c;
1600 if (opcode == SpvOpCompositeExtract) {
1601 comp = vtn_value(b, w[4], vtn_value_type_constant);
1603 c = &comp->constant;
1605 comp = vtn_value(b, w[5], vtn_value_type_constant);
1607 val->constant = nir_constant_clone(comp->constant,
1614 const struct vtn_type *type = comp->type;
1615 for (unsigned i = deref_start; i < count; i++) {
1616 vtn_fail_if(w[i] > type->length,
1617 "%uth index of %s is %u but the type has only "
1618 "%u elements", i - deref_start,
1619 spirv_op_to_string(opcode), w[i], type->length);
1621 switch (type->base_type) {
1622 case vtn_base_type_vector:
1624 type = type->array_element;
1627 case vtn_base_type_matrix:
1628 assert(col == 0 && elem == -1);
1631 type = type->array_element;
1634 case vtn_base_type_array:
1635 c = &(*c)->elements[w[i]];
1636 type = type->array_element;
1639 case vtn_base_type_struct:
1640 c = &(*c)->elements[w[i]];
1641 type = type->members[w[i]];
1645 vtn_fail("%s must only index into composite types",
1646 spirv_op_to_string(opcode));
1650 if (opcode == SpvOpCompositeExtract) {
1654 unsigned num_components = type->length;
1655 unsigned bit_size = glsl_get_bit_size(type->type);
1656 for (unsigned i = 0; i < num_components; i++)
1659 val->constant->values[0].u64[i] = (*c)->values[col].u64[elem + i];
1662 val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1665 val->constant->values[0].u16[i] = (*c)->values[col].u16[elem + i];
1668 val->constant->values[0].u8[i] = (*c)->values[col].u8[elem + i];
1671 vtn_fail("Invalid SpvOpCompositeExtract bit size");
1675 struct vtn_value *insert =
1676 vtn_value(b, w[4], vtn_value_type_constant);
1677 vtn_assert(insert->type == type);
1679 *c = insert->constant;
1681 unsigned num_components = type->length;
1682 unsigned bit_size = glsl_get_bit_size(type->type);
1683 for (unsigned i = 0; i < num_components; i++)
1686 (*c)->values[col].u64[elem + i] = insert->constant->values[0].u64[i];
1689 (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1692 (*c)->values[col].u16[elem + i] = insert->constant->values[0].u16[i];
1695 (*c)->values[col].u8[elem + i] = insert->constant->values[0].u8[i];
1698 vtn_fail("Invalid SpvOpCompositeInsert bit size");
1707 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
1708 nir_alu_type src_alu_type = dst_alu_type;
1709 unsigned num_components = glsl_get_vector_elements(val->type->type);
1712 vtn_assert(count <= 7);
1717 /* We have a source in a conversion */
1719 nir_get_nir_type_for_glsl_type(
1720 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1721 /* We use the bitsize of the conversion source to evaluate the opcode later */
1722 bit_size = glsl_get_bit_size(
1723 vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1726 bit_size = glsl_get_bit_size(val->type->type);
1729 nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
1730 nir_alu_type_get_type_size(src_alu_type),
1731 nir_alu_type_get_type_size(dst_alu_type));
1732 nir_const_value src[4];
1734 for (unsigned i = 0; i < count - 4; i++) {
1736 vtn_value(b, w[4 + i], vtn_value_type_constant)->constant;
1738 unsigned j = swap ? 1 - i : i;
1739 src[j] = c->values[0];
1742 val->constant->values[0] =
1743 nir_eval_const_opcode(op, num_components, bit_size, src);
1750 case SpvOpConstantNull:
1751 val->constant = vtn_null_constant(b, val->type->type);
1754 case SpvOpConstantSampler:
1755 vtn_fail("OpConstantSampler requires Kernel Capability");
1759 vtn_fail("Unhandled opcode");
1762 /* Now that we have the value, update the workgroup size if needed */
1763 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1767 vtn_handle_function_call(struct vtn_builder *b, SpvOp opcode,
1768 const uint32_t *w, unsigned count)
1770 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1771 struct vtn_function *vtn_callee =
1772 vtn_value(b, w[3], vtn_value_type_function)->func;
1773 struct nir_function *callee = vtn_callee->impl->function;
1775 vtn_callee->referenced = true;
1777 nir_call_instr *call = nir_call_instr_create(b->nb.shader, callee);
1778 for (unsigned i = 0; i < call->num_params; i++) {
1779 unsigned arg_id = w[4 + i];
1780 struct vtn_value *arg = vtn_untyped_value(b, arg_id);
1781 if (arg->value_type == vtn_value_type_pointer &&
1782 arg->pointer->ptr_type->type == NULL) {
1783 nir_deref_var *d = vtn_pointer_to_deref(b, arg->pointer);
1784 call->params[i] = nir_deref_var_clone(d, call);
1786 struct vtn_ssa_value *arg_ssa = vtn_ssa_value(b, arg_id);
1788 /* Make a temporary to store the argument in */
1790 nir_local_variable_create(b->nb.impl, arg_ssa->type, "arg_tmp");
1791 call->params[i] = nir_deref_var_create(call, tmp);
1793 vtn_local_store(b, arg_ssa, call->params[i]);
1797 nir_variable *out_tmp = NULL;
1798 vtn_assert(res_type->type == callee->return_type);
1799 if (!glsl_type_is_void(callee->return_type)) {
1800 out_tmp = nir_local_variable_create(b->nb.impl, callee->return_type,
1802 call->return_deref = nir_deref_var_create(call, out_tmp);
1805 nir_builder_instr_insert(&b->nb, &call->instr);
1807 if (glsl_type_is_void(callee->return_type)) {
1808 vtn_push_value(b, w[2], vtn_value_type_undef);
1810 vtn_push_ssa(b, w[2], res_type, vtn_local_load(b, call->return_deref));
1814 struct vtn_ssa_value *
1815 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1817 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1820 if (!glsl_type_is_vector_or_scalar(type)) {
1821 unsigned elems = glsl_get_length(type);
1822 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1823 for (unsigned i = 0; i < elems; i++) {
1824 const struct glsl_type *child_type;
1826 switch (glsl_get_base_type(type)) {
1828 case GLSL_TYPE_UINT:
1829 case GLSL_TYPE_INT16:
1830 case GLSL_TYPE_UINT16:
1831 case GLSL_TYPE_UINT8:
1832 case GLSL_TYPE_INT8:
1833 case GLSL_TYPE_INT64:
1834 case GLSL_TYPE_UINT64:
1835 case GLSL_TYPE_BOOL:
1836 case GLSL_TYPE_FLOAT:
1837 case GLSL_TYPE_FLOAT16:
1838 case GLSL_TYPE_DOUBLE:
1839 child_type = glsl_get_column_type(type);
1841 case GLSL_TYPE_ARRAY:
1842 child_type = glsl_get_array_element(type);
1844 case GLSL_TYPE_STRUCT:
1845 child_type = glsl_get_struct_field(type, i);
1848 vtn_fail("unkown base type");
1851 val->elems[i] = vtn_create_ssa_value(b, child_type);
1859 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1862 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
1863 src.src_type = type;
1868 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
1869 const uint32_t *w, unsigned count)
1871 if (opcode == SpvOpSampledImage) {
1872 struct vtn_value *val =
1873 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
1874 val->sampled_image = ralloc(b, struct vtn_sampled_image);
1875 val->sampled_image->type =
1876 vtn_value(b, w[1], vtn_value_type_type)->type;
1877 val->sampled_image->image =
1878 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
1879 val->sampled_image->sampler =
1880 vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
1882 } else if (opcode == SpvOpImage) {
1883 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
1884 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
1885 if (src_val->value_type == vtn_value_type_sampled_image) {
1886 val->pointer = src_val->sampled_image->image;
1888 vtn_assert(src_val->value_type == vtn_value_type_pointer);
1889 val->pointer = src_val->pointer;
1894 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1895 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1897 struct vtn_sampled_image sampled;
1898 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
1899 if (sampled_val->value_type == vtn_value_type_sampled_image) {
1900 sampled = *sampled_val->sampled_image;
1902 vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
1903 sampled.type = sampled_val->pointer->type;
1904 sampled.image = NULL;
1905 sampled.sampler = sampled_val->pointer;
1908 const struct glsl_type *image_type = sampled.type->type;
1909 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
1910 const bool is_array = glsl_sampler_type_is_array(image_type);
1912 /* Figure out the base texture operation */
1915 case SpvOpImageSampleImplicitLod:
1916 case SpvOpImageSampleDrefImplicitLod:
1917 case SpvOpImageSampleProjImplicitLod:
1918 case SpvOpImageSampleProjDrefImplicitLod:
1919 texop = nir_texop_tex;
1922 case SpvOpImageSampleExplicitLod:
1923 case SpvOpImageSampleDrefExplicitLod:
1924 case SpvOpImageSampleProjExplicitLod:
1925 case SpvOpImageSampleProjDrefExplicitLod:
1926 texop = nir_texop_txl;
1929 case SpvOpImageFetch:
1930 if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
1931 texop = nir_texop_txf_ms;
1933 texop = nir_texop_txf;
1937 case SpvOpImageGather:
1938 case SpvOpImageDrefGather:
1939 texop = nir_texop_tg4;
1942 case SpvOpImageQuerySizeLod:
1943 case SpvOpImageQuerySize:
1944 texop = nir_texop_txs;
1947 case SpvOpImageQueryLod:
1948 texop = nir_texop_lod;
1951 case SpvOpImageQueryLevels:
1952 texop = nir_texop_query_levels;
1955 case SpvOpImageQuerySamples:
1956 texop = nir_texop_texture_samples;
1960 vtn_fail("Unhandled opcode");
1963 nir_tex_src srcs[8]; /* 8 should be enough */
1964 nir_tex_src *p = srcs;
1968 struct nir_ssa_def *coord;
1969 unsigned coord_components;
1971 case SpvOpImageSampleImplicitLod:
1972 case SpvOpImageSampleExplicitLod:
1973 case SpvOpImageSampleDrefImplicitLod:
1974 case SpvOpImageSampleDrefExplicitLod:
1975 case SpvOpImageSampleProjImplicitLod:
1976 case SpvOpImageSampleProjExplicitLod:
1977 case SpvOpImageSampleProjDrefImplicitLod:
1978 case SpvOpImageSampleProjDrefExplicitLod:
1979 case SpvOpImageFetch:
1980 case SpvOpImageGather:
1981 case SpvOpImageDrefGather:
1982 case SpvOpImageQueryLod: {
1983 /* All these types have the coordinate as their first real argument */
1984 switch (sampler_dim) {
1985 case GLSL_SAMPLER_DIM_1D:
1986 case GLSL_SAMPLER_DIM_BUF:
1987 coord_components = 1;
1989 case GLSL_SAMPLER_DIM_2D:
1990 case GLSL_SAMPLER_DIM_RECT:
1991 case GLSL_SAMPLER_DIM_MS:
1992 coord_components = 2;
1994 case GLSL_SAMPLER_DIM_3D:
1995 case GLSL_SAMPLER_DIM_CUBE:
1996 coord_components = 3;
1999 vtn_fail("Invalid sampler type");
2002 if (is_array && texop != nir_texop_lod)
2005 coord = vtn_ssa_value(b, w[idx++])->def;
2006 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
2007 (1 << coord_components) - 1));
2008 p->src_type = nir_tex_src_coord;
2015 coord_components = 0;
2020 case SpvOpImageSampleProjImplicitLod:
2021 case SpvOpImageSampleProjExplicitLod:
2022 case SpvOpImageSampleProjDrefImplicitLod:
2023 case SpvOpImageSampleProjDrefExplicitLod:
2024 /* These have the projector as the last coordinate component */
2025 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
2026 p->src_type = nir_tex_src_projector;
2034 bool is_shadow = false;
2035 unsigned gather_component = 0;
2037 case SpvOpImageSampleDrefImplicitLod:
2038 case SpvOpImageSampleDrefExplicitLod:
2039 case SpvOpImageSampleProjDrefImplicitLod:
2040 case SpvOpImageSampleProjDrefExplicitLod:
2041 case SpvOpImageDrefGather:
2042 /* These all have an explicit depth value as their next source */
2044 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2047 case SpvOpImageGather:
2048 /* This has a component as its next source */
2050 vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
2057 /* For OpImageQuerySizeLod, we always have an LOD */
2058 if (opcode == SpvOpImageQuerySizeLod)
2059 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2061 /* Now we need to handle some number of optional arguments */
2062 const struct vtn_ssa_value *gather_offsets = NULL;
2064 uint32_t operands = w[idx++];
2066 if (operands & SpvImageOperandsBiasMask) {
2067 vtn_assert(texop == nir_texop_tex);
2068 texop = nir_texop_txb;
2069 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
2072 if (operands & SpvImageOperandsLodMask) {
2073 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2074 texop == nir_texop_txs);
2075 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2078 if (operands & SpvImageOperandsGradMask) {
2079 vtn_assert(texop == nir_texop_txl);
2080 texop = nir_texop_txd;
2081 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
2082 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
2085 if (operands & SpvImageOperandsOffsetMask ||
2086 operands & SpvImageOperandsConstOffsetMask)
2087 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
2089 if (operands & SpvImageOperandsConstOffsetsMask) {
2090 nir_tex_src none = {0};
2091 gather_offsets = vtn_ssa_value(b, w[idx++]);
2095 if (operands & SpvImageOperandsSampleMask) {
2096 vtn_assert(texop == nir_texop_txf_ms);
2097 texop = nir_texop_txf_ms;
2098 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2101 /* We should have now consumed exactly all of the arguments */
2102 vtn_assert(idx == count);
2104 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2107 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2109 instr->coord_components = coord_components;
2110 instr->sampler_dim = sampler_dim;
2111 instr->is_array = is_array;
2112 instr->is_shadow = is_shadow;
2113 instr->is_new_style_shadow =
2114 is_shadow && glsl_get_components(ret_type->type) == 1;
2115 instr->component = gather_component;
2117 switch (glsl_get_sampler_result_type(image_type)) {
2118 case GLSL_TYPE_FLOAT: instr->dest_type = nir_type_float; break;
2119 case GLSL_TYPE_INT: instr->dest_type = nir_type_int; break;
2120 case GLSL_TYPE_UINT: instr->dest_type = nir_type_uint; break;
2121 case GLSL_TYPE_BOOL: instr->dest_type = nir_type_bool; break;
2123 vtn_fail("Invalid base type for sampler result");
2126 nir_deref_var *sampler = vtn_pointer_to_deref(b, sampled.sampler);
2127 nir_deref_var *texture;
2128 if (sampled.image) {
2129 nir_deref_var *image = vtn_pointer_to_deref(b, sampled.image);
2135 instr->texture = nir_deref_var_clone(texture, instr);
2137 switch (instr->op) {
2143 /* These operations require a sampler */
2144 instr->sampler = nir_deref_var_clone(sampler, instr);
2147 case nir_texop_txf_ms:
2150 case nir_texop_query_levels:
2151 case nir_texop_texture_samples:
2152 case nir_texop_samples_identical:
2154 instr->sampler = NULL;
2156 case nir_texop_txf_ms_mcs:
2157 vtn_fail("unexpected nir_texop_txf_ms_mcs");
2160 nir_ssa_dest_init(&instr->instr, &instr->dest,
2161 nir_tex_instr_dest_size(instr), 32, NULL);
2163 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2164 nir_tex_instr_dest_size(instr));
2167 nir_instr *instruction;
2168 if (gather_offsets) {
2169 vtn_assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
2170 vtn_assert(glsl_get_length(gather_offsets->type) == 4);
2171 nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
2173 /* Copy the current instruction 4x */
2174 for (uint32_t i = 1; i < 4; i++) {
2175 instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
2176 instrs[i]->op = instr->op;
2177 instrs[i]->coord_components = instr->coord_components;
2178 instrs[i]->sampler_dim = instr->sampler_dim;
2179 instrs[i]->is_array = instr->is_array;
2180 instrs[i]->is_shadow = instr->is_shadow;
2181 instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
2182 instrs[i]->component = instr->component;
2183 instrs[i]->dest_type = instr->dest_type;
2184 instrs[i]->texture = nir_deref_var_clone(texture, instrs[i]);
2185 instrs[i]->sampler = NULL;
2187 memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
2189 nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
2190 nir_tex_instr_dest_size(instr), 32, NULL);
2193 /* Fill in the last argument with the offset from the passed in offsets
2194 * and insert the instruction into the stream.
2196 for (uint32_t i = 0; i < 4; i++) {
2198 src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
2199 src.src_type = nir_tex_src_offset;
2200 instrs[i]->src[instrs[i]->num_srcs - 1] = src;
2201 nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
2204 /* Combine the results of the 4 instructions by taking their .w
2207 nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
2208 nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
2209 vec4->dest.write_mask = 0xf;
2210 for (uint32_t i = 0; i < 4; i++) {
2211 vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
2212 vec4->src[i].swizzle[0] = 3;
2214 def = &vec4->dest.dest.ssa;
2215 instruction = &vec4->instr;
2217 def = &instr->dest.ssa;
2218 instruction = &instr->instr;
2221 val->ssa = vtn_create_ssa_value(b, ret_type->type);
2222 val->ssa->def = def;
2224 nir_builder_instr_insert(&b->nb, instruction);
2228 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2229 const uint32_t *w, nir_src *src)
2232 case SpvOpAtomicIIncrement:
2233 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2236 case SpvOpAtomicIDecrement:
2237 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2240 case SpvOpAtomicISub:
2242 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
2245 case SpvOpAtomicCompareExchange:
2246 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
2247 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
2250 case SpvOpAtomicExchange:
2251 case SpvOpAtomicIAdd:
2252 case SpvOpAtomicSMin:
2253 case SpvOpAtomicUMin:
2254 case SpvOpAtomicSMax:
2255 case SpvOpAtomicUMax:
2256 case SpvOpAtomicAnd:
2258 case SpvOpAtomicXor:
2259 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
2263 vtn_fail("Invalid SPIR-V atomic");
2267 static nir_ssa_def *
2268 get_image_coord(struct vtn_builder *b, uint32_t value)
2270 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
2272 /* The image_load_store intrinsics assume a 4-dim coordinate */
2273 unsigned dim = glsl_get_vector_elements(coord->type);
2274 unsigned swizzle[4];
2275 for (unsigned i = 0; i < 4; i++)
2276 swizzle[i] = MIN2(i, dim - 1);
2278 return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
2282 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2283 const uint32_t *w, unsigned count)
2285 /* Just get this one out of the way */
2286 if (opcode == SpvOpImageTexelPointer) {
2287 struct vtn_value *val =
2288 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2289 val->image = ralloc(b, struct vtn_image_pointer);
2291 val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2292 val->image->coord = get_image_coord(b, w[4]);
2293 val->image->sample = vtn_ssa_value(b, w[5])->def;
2297 struct vtn_image_pointer image;
2300 case SpvOpAtomicExchange:
2301 case SpvOpAtomicCompareExchange:
2302 case SpvOpAtomicCompareExchangeWeak:
2303 case SpvOpAtomicIIncrement:
2304 case SpvOpAtomicIDecrement:
2305 case SpvOpAtomicIAdd:
2306 case SpvOpAtomicISub:
2307 case SpvOpAtomicLoad:
2308 case SpvOpAtomicSMin:
2309 case SpvOpAtomicUMin:
2310 case SpvOpAtomicSMax:
2311 case SpvOpAtomicUMax:
2312 case SpvOpAtomicAnd:
2314 case SpvOpAtomicXor:
2315 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2318 case SpvOpAtomicStore:
2319 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2322 case SpvOpImageQuerySize:
2323 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2325 image.sample = NULL;
2328 case SpvOpImageRead:
2329 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2330 image.coord = get_image_coord(b, w[4]);
2332 if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
2333 vtn_assert(w[5] == SpvImageOperandsSampleMask);
2334 image.sample = vtn_ssa_value(b, w[6])->def;
2336 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2340 case SpvOpImageWrite:
2341 image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2342 image.coord = get_image_coord(b, w[2]);
2346 if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
2347 vtn_assert(w[4] == SpvImageOperandsSampleMask);
2348 image.sample = vtn_ssa_value(b, w[5])->def;
2350 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2355 vtn_fail("Invalid image opcode");
2358 nir_intrinsic_op op;
2360 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_var_##N; break;
2361 OP(ImageQuerySize, size)
2363 OP(ImageWrite, store)
2364 OP(AtomicLoad, load)
2365 OP(AtomicStore, store)
2366 OP(AtomicExchange, atomic_exchange)
2367 OP(AtomicCompareExchange, atomic_comp_swap)
2368 OP(AtomicIIncrement, atomic_add)
2369 OP(AtomicIDecrement, atomic_add)
2370 OP(AtomicIAdd, atomic_add)
2371 OP(AtomicISub, atomic_add)
2372 OP(AtomicSMin, atomic_min)
2373 OP(AtomicUMin, atomic_min)
2374 OP(AtomicSMax, atomic_max)
2375 OP(AtomicUMax, atomic_max)
2376 OP(AtomicAnd, atomic_and)
2377 OP(AtomicOr, atomic_or)
2378 OP(AtomicXor, atomic_xor)
2381 vtn_fail("Invalid image opcode");
2384 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2386 nir_deref_var *image_deref = vtn_pointer_to_deref(b, image.image);
2387 intrin->variables[0] = nir_deref_var_clone(image_deref, intrin);
2389 /* ImageQuerySize doesn't take any extra parameters */
2390 if (opcode != SpvOpImageQuerySize) {
2391 /* The image coordinate is always 4 components but we may not have that
2392 * many. Swizzle to compensate.
2395 for (unsigned i = 0; i < 4; i++)
2396 swiz[i] = i < image.coord->num_components ? i : 0;
2397 intrin->src[0] = nir_src_for_ssa(nir_swizzle(&b->nb, image.coord,
2399 intrin->src[1] = nir_src_for_ssa(image.sample);
2403 case SpvOpAtomicLoad:
2404 case SpvOpImageQuerySize:
2405 case SpvOpImageRead:
2407 case SpvOpAtomicStore:
2408 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2410 case SpvOpImageWrite:
2411 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[3])->def);
2414 case SpvOpAtomicCompareExchange:
2415 case SpvOpAtomicIIncrement:
2416 case SpvOpAtomicIDecrement:
2417 case SpvOpAtomicExchange:
2418 case SpvOpAtomicIAdd:
2419 case SpvOpAtomicISub:
2420 case SpvOpAtomicSMin:
2421 case SpvOpAtomicUMin:
2422 case SpvOpAtomicSMax:
2423 case SpvOpAtomicUMax:
2424 case SpvOpAtomicAnd:
2426 case SpvOpAtomicXor:
2427 fill_common_atomic_sources(b, opcode, w, &intrin->src[2]);
2431 vtn_fail("Invalid image opcode");
2434 if (opcode != SpvOpImageWrite) {
2435 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2436 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2438 unsigned dest_components = nir_intrinsic_dest_components(intrin);
2439 if (intrin->intrinsic == nir_intrinsic_image_var_size) {
2440 dest_components = intrin->num_components =
2441 glsl_get_vector_elements(type->type);
2444 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2445 dest_components, 32, NULL);
2447 nir_builder_instr_insert(&b->nb, &intrin->instr);
2449 val->ssa = vtn_create_ssa_value(b, type->type);
2450 val->ssa->def = &intrin->dest.ssa;
2452 nir_builder_instr_insert(&b->nb, &intrin->instr);
2456 static nir_intrinsic_op
2457 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2460 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
2461 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
2462 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2463 OP(AtomicExchange, atomic_exchange)
2464 OP(AtomicCompareExchange, atomic_comp_swap)
2465 OP(AtomicIIncrement, atomic_add)
2466 OP(AtomicIDecrement, atomic_add)
2467 OP(AtomicIAdd, atomic_add)
2468 OP(AtomicISub, atomic_add)
2469 OP(AtomicSMin, atomic_imin)
2470 OP(AtomicUMin, atomic_umin)
2471 OP(AtomicSMax, atomic_imax)
2472 OP(AtomicUMax, atomic_umax)
2473 OP(AtomicAnd, atomic_and)
2474 OP(AtomicOr, atomic_or)
2475 OP(AtomicXor, atomic_xor)
2478 vtn_fail("Invalid SSBO atomic");
2482 static nir_intrinsic_op
2483 get_shared_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2486 case SpvOpAtomicLoad: return nir_intrinsic_load_shared;
2487 case SpvOpAtomicStore: return nir_intrinsic_store_shared;
2488 #define OP(S, N) case SpvOp##S: return nir_intrinsic_shared_##N;
2489 OP(AtomicExchange, atomic_exchange)
2490 OP(AtomicCompareExchange, atomic_comp_swap)
2491 OP(AtomicIIncrement, atomic_add)
2492 OP(AtomicIDecrement, atomic_add)
2493 OP(AtomicIAdd, atomic_add)
2494 OP(AtomicISub, atomic_add)
2495 OP(AtomicSMin, atomic_imin)
2496 OP(AtomicUMin, atomic_umin)
2497 OP(AtomicSMax, atomic_imax)
2498 OP(AtomicUMax, atomic_umax)
2499 OP(AtomicAnd, atomic_and)
2500 OP(AtomicOr, atomic_or)
2501 OP(AtomicXor, atomic_xor)
2504 vtn_fail("Invalid shared atomic");
2508 static nir_intrinsic_op
2509 get_var_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2512 case SpvOpAtomicLoad: return nir_intrinsic_load_var;
2513 case SpvOpAtomicStore: return nir_intrinsic_store_var;
2514 #define OP(S, N) case SpvOp##S: return nir_intrinsic_var_##N;
2515 OP(AtomicExchange, atomic_exchange)
2516 OP(AtomicCompareExchange, atomic_comp_swap)
2517 OP(AtomicIIncrement, atomic_add)
2518 OP(AtomicIDecrement, atomic_add)
2519 OP(AtomicIAdd, atomic_add)
2520 OP(AtomicISub, atomic_add)
2521 OP(AtomicSMin, atomic_imin)
2522 OP(AtomicUMin, atomic_umin)
2523 OP(AtomicSMax, atomic_imax)
2524 OP(AtomicUMax, atomic_umax)
2525 OP(AtomicAnd, atomic_and)
2526 OP(AtomicOr, atomic_or)
2527 OP(AtomicXor, atomic_xor)
2530 vtn_fail("Invalid shared atomic");
2535 vtn_handle_ssbo_or_shared_atomic(struct vtn_builder *b, SpvOp opcode,
2536 const uint32_t *w, unsigned count)
2538 struct vtn_pointer *ptr;
2539 nir_intrinsic_instr *atomic;
2542 case SpvOpAtomicLoad:
2543 case SpvOpAtomicExchange:
2544 case SpvOpAtomicCompareExchange:
2545 case SpvOpAtomicCompareExchangeWeak:
2546 case SpvOpAtomicIIncrement:
2547 case SpvOpAtomicIDecrement:
2548 case SpvOpAtomicIAdd:
2549 case SpvOpAtomicISub:
2550 case SpvOpAtomicSMin:
2551 case SpvOpAtomicUMin:
2552 case SpvOpAtomicSMax:
2553 case SpvOpAtomicUMax:
2554 case SpvOpAtomicAnd:
2556 case SpvOpAtomicXor:
2557 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2560 case SpvOpAtomicStore:
2561 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2565 vtn_fail("Invalid SPIR-V atomic");
2569 SpvScope scope = w[4];
2570 SpvMemorySemanticsMask semantics = w[5];
2573 if (ptr->mode == vtn_variable_mode_workgroup &&
2574 !b->options->lower_workgroup_access_to_offsets) {
2575 nir_deref_var *deref = vtn_pointer_to_deref(b, ptr);
2576 const struct glsl_type *deref_type = nir_deref_tail(&deref->deref)->type;
2577 nir_intrinsic_op op = get_var_nir_atomic_op(b, opcode);
2578 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2579 atomic->variables[0] = nir_deref_var_clone(deref, atomic);
2582 case SpvOpAtomicLoad:
2583 atomic->num_components = glsl_get_vector_elements(deref_type);
2586 case SpvOpAtomicStore:
2587 atomic->num_components = glsl_get_vector_elements(deref_type);
2588 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2589 atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2592 case SpvOpAtomicExchange:
2593 case SpvOpAtomicCompareExchange:
2594 case SpvOpAtomicCompareExchangeWeak:
2595 case SpvOpAtomicIIncrement:
2596 case SpvOpAtomicIDecrement:
2597 case SpvOpAtomicIAdd:
2598 case SpvOpAtomicISub:
2599 case SpvOpAtomicSMin:
2600 case SpvOpAtomicUMin:
2601 case SpvOpAtomicSMax:
2602 case SpvOpAtomicUMax:
2603 case SpvOpAtomicAnd:
2605 case SpvOpAtomicXor:
2606 fill_common_atomic_sources(b, opcode, w, &atomic->src[0]);
2610 vtn_fail("Invalid SPIR-V atomic");
2614 nir_ssa_def *offset, *index;
2615 offset = vtn_pointer_to_offset(b, ptr, &index, NULL);
2617 nir_intrinsic_op op;
2618 if (ptr->mode == vtn_variable_mode_ssbo) {
2619 op = get_ssbo_nir_atomic_op(b, opcode);
2621 vtn_assert(ptr->mode == vtn_variable_mode_workgroup &&
2622 b->options->lower_workgroup_access_to_offsets);
2623 op = get_shared_nir_atomic_op(b, opcode);
2626 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2630 case SpvOpAtomicLoad:
2631 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2632 if (ptr->mode == vtn_variable_mode_ssbo)
2633 atomic->src[src++] = nir_src_for_ssa(index);
2634 atomic->src[src++] = nir_src_for_ssa(offset);
2637 case SpvOpAtomicStore:
2638 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2639 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2640 atomic->src[src++] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2641 if (ptr->mode == vtn_variable_mode_ssbo)
2642 atomic->src[src++] = nir_src_for_ssa(index);
2643 atomic->src[src++] = nir_src_for_ssa(offset);
2646 case SpvOpAtomicExchange:
2647 case SpvOpAtomicCompareExchange:
2648 case SpvOpAtomicCompareExchangeWeak:
2649 case SpvOpAtomicIIncrement:
2650 case SpvOpAtomicIDecrement:
2651 case SpvOpAtomicIAdd:
2652 case SpvOpAtomicISub:
2653 case SpvOpAtomicSMin:
2654 case SpvOpAtomicUMin:
2655 case SpvOpAtomicSMax:
2656 case SpvOpAtomicUMax:
2657 case SpvOpAtomicAnd:
2659 case SpvOpAtomicXor:
2660 if (ptr->mode == vtn_variable_mode_ssbo)
2661 atomic->src[src++] = nir_src_for_ssa(index);
2662 atomic->src[src++] = nir_src_for_ssa(offset);
2663 fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
2667 vtn_fail("Invalid SPIR-V atomic");
2671 if (opcode != SpvOpAtomicStore) {
2672 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2674 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2675 glsl_get_vector_elements(type->type),
2676 glsl_get_bit_size(type->type), NULL);
2678 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2679 val->ssa = rzalloc(b, struct vtn_ssa_value);
2680 val->ssa->def = &atomic->dest.ssa;
2681 val->ssa->type = type->type;
2684 nir_builder_instr_insert(&b->nb, &atomic->instr);
2687 static nir_alu_instr *
2688 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
2691 switch (num_components) {
2692 case 1: op = nir_op_fmov; break;
2693 case 2: op = nir_op_vec2; break;
2694 case 3: op = nir_op_vec3; break;
2695 case 4: op = nir_op_vec4; break;
2696 default: vtn_fail("bad vector size");
2699 nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
2700 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2702 vec->dest.write_mask = (1 << num_components) - 1;
2707 struct vtn_ssa_value *
2708 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2710 if (src->transposed)
2711 return src->transposed;
2713 struct vtn_ssa_value *dest =
2714 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2716 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2717 nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
2718 glsl_get_bit_size(src->type));
2719 if (glsl_type_is_vector_or_scalar(src->type)) {
2720 vec->src[0].src = nir_src_for_ssa(src->def);
2721 vec->src[0].swizzle[0] = i;
2723 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2724 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2725 vec->src[j].swizzle[0] = i;
2728 nir_builder_instr_insert(&b->nb, &vec->instr);
2729 dest->elems[i]->def = &vec->dest.dest.ssa;
2732 dest->transposed = src;
2738 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2740 unsigned swiz[4] = { index };
2741 return nir_swizzle(&b->nb, src, swiz, 1, true);
2745 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2748 nir_alu_instr *vec = create_vec(b, src->num_components,
2751 for (unsigned i = 0; i < src->num_components; i++) {
2753 vec->src[i].src = nir_src_for_ssa(insert);
2755 vec->src[i].src = nir_src_for_ssa(src);
2756 vec->src[i].swizzle[0] = i;
2760 nir_builder_instr_insert(&b->nb, &vec->instr);
2762 return &vec->dest.dest.ssa;
2766 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2769 nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
2770 for (unsigned i = 1; i < src->num_components; i++)
2771 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2772 vtn_vector_extract(b, src, i), dest);
2778 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2779 nir_ssa_def *insert, nir_ssa_def *index)
2781 nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
2782 for (unsigned i = 1; i < src->num_components; i++)
2783 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2784 vtn_vector_insert(b, src, insert, i), dest);
2789 static nir_ssa_def *
2790 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
2791 nir_ssa_def *src0, nir_ssa_def *src1,
2792 const uint32_t *indices)
2794 nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
2796 for (unsigned i = 0; i < num_components; i++) {
2797 uint32_t index = indices[i];
2798 if (index == 0xffffffff) {
2800 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
2801 } else if (index < src0->num_components) {
2802 vec->src[i].src = nir_src_for_ssa(src0);
2803 vec->src[i].swizzle[0] = index;
2805 vec->src[i].src = nir_src_for_ssa(src1);
2806 vec->src[i].swizzle[0] = index - src0->num_components;
2810 nir_builder_instr_insert(&b->nb, &vec->instr);
2812 return &vec->dest.dest.ssa;
2816 * Concatentates a number of vectors/scalars together to produce a vector
2818 static nir_ssa_def *
2819 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
2820 unsigned num_srcs, nir_ssa_def **srcs)
2822 nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
2824 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2826 * "When constructing a vector, there must be at least two Constituent
2829 vtn_assert(num_srcs >= 2);
2831 unsigned dest_idx = 0;
2832 for (unsigned i = 0; i < num_srcs; i++) {
2833 nir_ssa_def *src = srcs[i];
2834 vtn_assert(dest_idx + src->num_components <= num_components);
2835 for (unsigned j = 0; j < src->num_components; j++) {
2836 vec->src[dest_idx].src = nir_src_for_ssa(src);
2837 vec->src[dest_idx].swizzle[0] = j;
2842 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2844 * "When constructing a vector, the total number of components in all
2845 * the operands must equal the number of components in Result Type."
2847 vtn_assert(dest_idx == num_components);
2849 nir_builder_instr_insert(&b->nb, &vec->instr);
2851 return &vec->dest.dest.ssa;
2854 static struct vtn_ssa_value *
2855 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
2857 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
2858 dest->type = src->type;
2860 if (glsl_type_is_vector_or_scalar(src->type)) {
2861 dest->def = src->def;
2863 unsigned elems = glsl_get_length(src->type);
2865 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
2866 for (unsigned i = 0; i < elems; i++)
2867 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
2873 static struct vtn_ssa_value *
2874 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
2875 struct vtn_ssa_value *insert, const uint32_t *indices,
2876 unsigned num_indices)
2878 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
2880 struct vtn_ssa_value *cur = dest;
2882 for (i = 0; i < num_indices - 1; i++) {
2883 cur = cur->elems[indices[i]];
2886 if (glsl_type_is_vector_or_scalar(cur->type)) {
2887 /* According to the SPIR-V spec, OpCompositeInsert may work down to
2888 * the component granularity. In that case, the last index will be
2889 * the index to insert the scalar into the vector.
2892 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
2894 cur->elems[indices[i]] = insert;
2900 static struct vtn_ssa_value *
2901 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
2902 const uint32_t *indices, unsigned num_indices)
2904 struct vtn_ssa_value *cur = src;
2905 for (unsigned i = 0; i < num_indices; i++) {
2906 if (glsl_type_is_vector_or_scalar(cur->type)) {
2907 vtn_assert(i == num_indices - 1);
2908 /* According to the SPIR-V spec, OpCompositeExtract may work down to
2909 * the component granularity. The last index will be the index of the
2910 * vector to extract.
2913 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
2914 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
2915 ret->def = vtn_vector_extract(b, cur->def, indices[i]);
2918 cur = cur->elems[indices[i]];
2926 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
2927 const uint32_t *w, unsigned count)
2929 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2930 const struct glsl_type *type =
2931 vtn_value(b, w[1], vtn_value_type_type)->type->type;
2932 val->ssa = vtn_create_ssa_value(b, type);
2935 case SpvOpVectorExtractDynamic:
2936 val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
2937 vtn_ssa_value(b, w[4])->def);
2940 case SpvOpVectorInsertDynamic:
2941 val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
2942 vtn_ssa_value(b, w[4])->def,
2943 vtn_ssa_value(b, w[5])->def);
2946 case SpvOpVectorShuffle:
2947 val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
2948 vtn_ssa_value(b, w[3])->def,
2949 vtn_ssa_value(b, w[4])->def,
2953 case SpvOpCompositeConstruct: {
2954 unsigned elems = count - 3;
2956 if (glsl_type_is_vector_or_scalar(type)) {
2957 nir_ssa_def *srcs[4];
2958 for (unsigned i = 0; i < elems; i++)
2959 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
2961 vtn_vector_construct(b, glsl_get_vector_elements(type),
2964 val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2965 for (unsigned i = 0; i < elems; i++)
2966 val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
2970 case SpvOpCompositeExtract:
2971 val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
2975 case SpvOpCompositeInsert:
2976 val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
2977 vtn_ssa_value(b, w[3]),
2981 case SpvOpCopyObject:
2982 val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
2986 vtn_fail("unknown composite operation");
2991 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
2993 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2994 nir_builder_instr_insert(&b->nb, &intrin->instr);
2998 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
2999 SpvMemorySemanticsMask semantics)
3001 static const SpvMemorySemanticsMask all_memory_semantics =
3002 SpvMemorySemanticsUniformMemoryMask |
3003 SpvMemorySemanticsWorkgroupMemoryMask |
3004 SpvMemorySemanticsAtomicCounterMemoryMask |
3005 SpvMemorySemanticsImageMemoryMask;
3007 /* If we're not actually doing a memory barrier, bail */
3008 if (!(semantics & all_memory_semantics))
3011 /* GL and Vulkan don't have these */
3012 vtn_assert(scope != SpvScopeCrossDevice);
3014 if (scope == SpvScopeSubgroup)
3015 return; /* Nothing to do here */
3017 if (scope == SpvScopeWorkgroup) {
3018 vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
3022 /* There's only two scopes thing left */
3023 vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
3025 if ((semantics & all_memory_semantics) == all_memory_semantics) {
3026 vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
3030 /* Issue a bunch of more specific barriers */
3031 uint32_t bits = semantics;
3033 SpvMemorySemanticsMask semantic = 1 << u_bit_scan(&bits);
3035 case SpvMemorySemanticsUniformMemoryMask:
3036 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3038 case SpvMemorySemanticsWorkgroupMemoryMask:
3039 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3041 case SpvMemorySemanticsAtomicCounterMemoryMask:
3042 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3044 case SpvMemorySemanticsImageMemoryMask:
3045 vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3054 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3055 const uint32_t *w, unsigned count)
3058 case SpvOpEmitVertex:
3059 case SpvOpEmitStreamVertex:
3060 case SpvOpEndPrimitive:
3061 case SpvOpEndStreamPrimitive: {
3062 nir_intrinsic_op intrinsic_op;
3064 case SpvOpEmitVertex:
3065 case SpvOpEmitStreamVertex:
3066 intrinsic_op = nir_intrinsic_emit_vertex;
3068 case SpvOpEndPrimitive:
3069 case SpvOpEndStreamPrimitive:
3070 intrinsic_op = nir_intrinsic_end_primitive;
3073 unreachable("Invalid opcode");
3076 nir_intrinsic_instr *intrin =
3077 nir_intrinsic_instr_create(b->shader, intrinsic_op);
3080 case SpvOpEmitStreamVertex:
3081 case SpvOpEndStreamPrimitive:
3082 nir_intrinsic_set_stream_id(intrin, w[1]);
3088 nir_builder_instr_insert(&b->nb, &intrin->instr);
3092 case SpvOpMemoryBarrier: {
3093 SpvScope scope = vtn_constant_value(b, w[1])->values[0].u32[0];
3094 SpvMemorySemanticsMask semantics =
3095 vtn_constant_value(b, w[2])->values[0].u32[0];
3096 vtn_emit_memory_barrier(b, scope, semantics);
3100 case SpvOpControlBarrier: {
3101 SpvScope execution_scope =
3102 vtn_constant_value(b, w[1])->values[0].u32[0];
3103 if (execution_scope == SpvScopeWorkgroup)
3104 vtn_emit_barrier(b, nir_intrinsic_barrier);
3106 SpvScope memory_scope =
3107 vtn_constant_value(b, w[2])->values[0].u32[0];
3108 SpvMemorySemanticsMask memory_semantics =
3109 vtn_constant_value(b, w[3])->values[0].u32[0];
3110 vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3115 unreachable("unknown barrier instruction");
3120 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
3121 SpvExecutionMode mode)
3124 case SpvExecutionModeInputPoints:
3125 case SpvExecutionModeOutputPoints:
3126 return 0; /* GL_POINTS */
3127 case SpvExecutionModeInputLines:
3128 return 1; /* GL_LINES */
3129 case SpvExecutionModeInputLinesAdjacency:
3130 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
3131 case SpvExecutionModeTriangles:
3132 return 4; /* GL_TRIANGLES */
3133 case SpvExecutionModeInputTrianglesAdjacency:
3134 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
3135 case SpvExecutionModeQuads:
3136 return 7; /* GL_QUADS */
3137 case SpvExecutionModeIsolines:
3138 return 0x8E7A; /* GL_ISOLINES */
3139 case SpvExecutionModeOutputLineStrip:
3140 return 3; /* GL_LINE_STRIP */
3141 case SpvExecutionModeOutputTriangleStrip:
3142 return 5; /* GL_TRIANGLE_STRIP */
3144 vtn_fail("Invalid primitive type");
3149 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
3150 SpvExecutionMode mode)
3153 case SpvExecutionModeInputPoints:
3155 case SpvExecutionModeInputLines:
3157 case SpvExecutionModeInputLinesAdjacency:
3159 case SpvExecutionModeTriangles:
3161 case SpvExecutionModeInputTrianglesAdjacency:
3164 vtn_fail("Invalid GS input mode");
3168 static gl_shader_stage
3169 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
3172 case SpvExecutionModelVertex:
3173 return MESA_SHADER_VERTEX;
3174 case SpvExecutionModelTessellationControl:
3175 return MESA_SHADER_TESS_CTRL;
3176 case SpvExecutionModelTessellationEvaluation:
3177 return MESA_SHADER_TESS_EVAL;
3178 case SpvExecutionModelGeometry:
3179 return MESA_SHADER_GEOMETRY;
3180 case SpvExecutionModelFragment:
3181 return MESA_SHADER_FRAGMENT;
3182 case SpvExecutionModelGLCompute:
3183 return MESA_SHADER_COMPUTE;
3185 vtn_fail("Unsupported execution model");
3189 #define spv_check_supported(name, cap) do { \
3190 if (!(b->options && b->options->caps.name)) \
3191 vtn_warn("Unsupported SPIR-V capability: %s", \
3192 spirv_capability_to_string(cap)); \
3197 vtn_handle_entry_point(struct vtn_builder *b, const uint32_t *w,
3200 struct vtn_value *entry_point = &b->values[w[2]];
3201 /* Let this be a name label regardless */
3202 unsigned name_words;
3203 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
3205 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
3206 stage_for_execution_model(b, w[1]) != b->entry_point_stage)
3209 vtn_assert(b->entry_point == NULL);
3210 b->entry_point = entry_point;
3214 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
3215 const uint32_t *w, unsigned count)
3222 case SpvSourceLanguageUnknown: lang = "unknown"; break;
3223 case SpvSourceLanguageESSL: lang = "ESSL"; break;
3224 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
3225 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
3226 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
3227 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
3230 uint32_t version = w[2];
3233 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
3235 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
3239 case SpvOpSourceExtension:
3240 case SpvOpSourceContinued:
3241 case SpvOpExtension:
3242 case SpvOpModuleProcessed:
3243 /* Unhandled, but these are for debug so that's ok. */
3246 case SpvOpCapability: {
3247 SpvCapability cap = w[1];
3249 case SpvCapabilityMatrix:
3250 case SpvCapabilityShader:
3251 case SpvCapabilityGeometry:
3252 case SpvCapabilityGeometryPointSize:
3253 case SpvCapabilityUniformBufferArrayDynamicIndexing:
3254 case SpvCapabilitySampledImageArrayDynamicIndexing:
3255 case SpvCapabilityStorageBufferArrayDynamicIndexing:
3256 case SpvCapabilityStorageImageArrayDynamicIndexing:
3257 case SpvCapabilityImageRect:
3258 case SpvCapabilitySampledRect:
3259 case SpvCapabilitySampled1D:
3260 case SpvCapabilityImage1D:
3261 case SpvCapabilitySampledCubeArray:
3262 case SpvCapabilityImageCubeArray:
3263 case SpvCapabilitySampledBuffer:
3264 case SpvCapabilityImageBuffer:
3265 case SpvCapabilityImageQuery:
3266 case SpvCapabilityDerivativeControl:
3267 case SpvCapabilityInterpolationFunction:
3268 case SpvCapabilityMultiViewport:
3269 case SpvCapabilitySampleRateShading:
3270 case SpvCapabilityClipDistance:
3271 case SpvCapabilityCullDistance:
3272 case SpvCapabilityInputAttachment:
3273 case SpvCapabilityImageGatherExtended:
3274 case SpvCapabilityStorageImageExtendedFormats:
3277 case SpvCapabilityGeometryStreams:
3278 case SpvCapabilityLinkage:
3279 case SpvCapabilityVector16:
3280 case SpvCapabilityFloat16Buffer:
3281 case SpvCapabilityFloat16:
3282 case SpvCapabilityInt64Atomics:
3283 case SpvCapabilityAtomicStorage:
3284 case SpvCapabilityInt16:
3285 case SpvCapabilityStorageImageMultisample:
3286 case SpvCapabilityInt8:
3287 case SpvCapabilitySparseResidency:
3288 case SpvCapabilityMinLod:
3289 case SpvCapabilityTransformFeedback:
3290 vtn_warn("Unsupported SPIR-V capability: %s",
3291 spirv_capability_to_string(cap));
3294 case SpvCapabilityFloat64:
3295 spv_check_supported(float64, cap);
3297 case SpvCapabilityInt64:
3298 spv_check_supported(int64, cap);
3301 case SpvCapabilityAddresses:
3302 case SpvCapabilityKernel:
3303 case SpvCapabilityImageBasic:
3304 case SpvCapabilityImageReadWrite:
3305 case SpvCapabilityImageMipmap:
3306 case SpvCapabilityPipes:
3307 case SpvCapabilityGroups:
3308 case SpvCapabilityDeviceEnqueue:
3309 case SpvCapabilityLiteralSampler:
3310 case SpvCapabilityGenericPointer:
3311 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
3312 spirv_capability_to_string(cap));
3315 case SpvCapabilityImageMSArray:
3316 spv_check_supported(image_ms_array, cap);
3319 case SpvCapabilityTessellation:
3320 case SpvCapabilityTessellationPointSize:
3321 spv_check_supported(tessellation, cap);
3324 case SpvCapabilityDrawParameters:
3325 spv_check_supported(draw_parameters, cap);
3328 case SpvCapabilityStorageImageReadWithoutFormat:
3329 spv_check_supported(image_read_without_format, cap);
3332 case SpvCapabilityStorageImageWriteWithoutFormat:
3333 spv_check_supported(image_write_without_format, cap);
3336 case SpvCapabilityDeviceGroup:
3337 spv_check_supported(device_group, cap);
3340 case SpvCapabilityMultiView:
3341 spv_check_supported(multiview, cap);
3344 case SpvCapabilityGroupNonUniform:
3345 spv_check_supported(subgroup_basic, cap);
3348 case SpvCapabilityGroupNonUniformVote:
3349 spv_check_supported(subgroup_vote, cap);
3352 case SpvCapabilitySubgroupBallotKHR:
3353 case SpvCapabilityGroupNonUniformBallot:
3354 spv_check_supported(subgroup_ballot, cap);
3357 case SpvCapabilityGroupNonUniformShuffle:
3358 case SpvCapabilityGroupNonUniformShuffleRelative:
3359 spv_check_supported(subgroup_shuffle, cap);
3362 case SpvCapabilityGroupNonUniformQuad:
3363 spv_check_supported(subgroup_quad, cap);
3366 case SpvCapabilityGroupNonUniformArithmetic:
3367 case SpvCapabilityGroupNonUniformClustered:
3368 spv_check_supported(subgroup_arithmetic, cap);
3371 case SpvCapabilityVariablePointersStorageBuffer:
3372 case SpvCapabilityVariablePointers:
3373 spv_check_supported(variable_pointers, cap);
3376 case SpvCapabilityStorageUniformBufferBlock16:
3377 case SpvCapabilityStorageUniform16:
3378 case SpvCapabilityStoragePushConstant16:
3379 case SpvCapabilityStorageInputOutput16:
3380 spv_check_supported(storage_16bit, cap);
3383 case SpvCapabilityShaderViewportIndexLayerEXT:
3384 spv_check_supported(shader_viewport_index_layer, cap);
3387 case SpvCapabilityInputAttachmentArrayDynamicIndexingEXT:
3388 case SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT:
3389 case SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT:
3390 spv_check_supported(descriptor_array_dynamic_indexing, cap);
3393 case SpvCapabilityRuntimeDescriptorArrayEXT:
3394 spv_check_supported(runtime_descriptor_array, cap);
3398 vtn_fail("Unhandled capability");
3403 case SpvOpExtInstImport:
3404 vtn_handle_extension(b, opcode, w, count);
3407 case SpvOpMemoryModel:
3408 vtn_assert(w[1] == SpvAddressingModelLogical);
3409 vtn_assert(w[2] == SpvMemoryModelSimple ||
3410 w[2] == SpvMemoryModelGLSL450);
3413 case SpvOpEntryPoint:
3414 vtn_handle_entry_point(b, w, count);
3418 vtn_push_value(b, w[1], vtn_value_type_string)->str =
3419 vtn_string_literal(b, &w[2], count - 2, NULL);
3423 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
3426 case SpvOpMemberName:
3430 case SpvOpExecutionMode:
3431 case SpvOpDecorationGroup:
3433 case SpvOpMemberDecorate:
3434 case SpvOpGroupDecorate:
3435 case SpvOpGroupMemberDecorate:
3436 vtn_handle_decoration(b, opcode, w, count);
3440 return false; /* End of preamble */
3447 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
3448 const struct vtn_decoration *mode, void *data)
3450 vtn_assert(b->entry_point == entry_point);
3452 switch(mode->exec_mode) {
3453 case SpvExecutionModeOriginUpperLeft:
3454 case SpvExecutionModeOriginLowerLeft:
3455 b->origin_upper_left =
3456 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
3459 case SpvExecutionModeEarlyFragmentTests:
3460 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3461 b->shader->info.fs.early_fragment_tests = true;
3464 case SpvExecutionModeInvocations:
3465 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3466 b->shader->info.gs.invocations = MAX2(1, mode->literals[0]);
3469 case SpvExecutionModeDepthReplacing:
3470 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3471 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
3473 case SpvExecutionModeDepthGreater:
3474 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3475 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
3477 case SpvExecutionModeDepthLess:
3478 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3479 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
3481 case SpvExecutionModeDepthUnchanged:
3482 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3483 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3486 case SpvExecutionModeLocalSize:
3487 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
3488 b->shader->info.cs.local_size[0] = mode->literals[0];
3489 b->shader->info.cs.local_size[1] = mode->literals[1];
3490 b->shader->info.cs.local_size[2] = mode->literals[2];
3492 case SpvExecutionModeLocalSizeHint:
3493 break; /* Nothing to do with this */
3495 case SpvExecutionModeOutputVertices:
3496 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3497 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3498 b->shader->info.tess.tcs_vertices_out = mode->literals[0];
3500 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3501 b->shader->info.gs.vertices_out = mode->literals[0];
3505 case SpvExecutionModeInputPoints:
3506 case SpvExecutionModeInputLines:
3507 case SpvExecutionModeInputLinesAdjacency:
3508 case SpvExecutionModeTriangles:
3509 case SpvExecutionModeInputTrianglesAdjacency:
3510 case SpvExecutionModeQuads:
3511 case SpvExecutionModeIsolines:
3512 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3513 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3514 b->shader->info.tess.primitive_mode =
3515 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3517 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3518 b->shader->info.gs.vertices_in =
3519 vertices_in_from_spv_execution_mode(b, mode->exec_mode);
3523 case SpvExecutionModeOutputPoints:
3524 case SpvExecutionModeOutputLineStrip:
3525 case SpvExecutionModeOutputTriangleStrip:
3526 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3527 b->shader->info.gs.output_primitive =
3528 gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3531 case SpvExecutionModeSpacingEqual:
3532 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3533 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3534 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
3536 case SpvExecutionModeSpacingFractionalEven:
3537 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3538 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3539 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
3541 case SpvExecutionModeSpacingFractionalOdd:
3542 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3543 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3544 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
3546 case SpvExecutionModeVertexOrderCw:
3547 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3548 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3549 b->shader->info.tess.ccw = false;
3551 case SpvExecutionModeVertexOrderCcw:
3552 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3553 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3554 b->shader->info.tess.ccw = true;
3556 case SpvExecutionModePointMode:
3557 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3558 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3559 b->shader->info.tess.point_mode = true;
3562 case SpvExecutionModePixelCenterInteger:
3563 b->pixel_center_integer = true;
3566 case SpvExecutionModeXfb:
3567 vtn_fail("Unhandled execution mode");
3570 case SpvExecutionModeVecTypeHint:
3571 case SpvExecutionModeContractionOff:
3575 vtn_fail("Unhandled execution mode");
3580 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
3581 const uint32_t *w, unsigned count)
3583 vtn_set_instruction_result_type(b, opcode, w, count);
3587 case SpvOpSourceContinued:
3588 case SpvOpSourceExtension:
3589 case SpvOpExtension:
3590 case SpvOpCapability:
3591 case SpvOpExtInstImport:
3592 case SpvOpMemoryModel:
3593 case SpvOpEntryPoint:
3594 case SpvOpExecutionMode:
3597 case SpvOpMemberName:
3598 case SpvOpDecorationGroup:
3600 case SpvOpMemberDecorate:
3601 case SpvOpGroupDecorate:
3602 case SpvOpGroupMemberDecorate:
3603 vtn_fail("Invalid opcode types and variables section");
3609 case SpvOpTypeFloat:
3610 case SpvOpTypeVector:
3611 case SpvOpTypeMatrix:
3612 case SpvOpTypeImage:
3613 case SpvOpTypeSampler:
3614 case SpvOpTypeSampledImage:
3615 case SpvOpTypeArray:
3616 case SpvOpTypeRuntimeArray:
3617 case SpvOpTypeStruct:
3618 case SpvOpTypeOpaque:
3619 case SpvOpTypePointer:
3620 case SpvOpTypeFunction:
3621 case SpvOpTypeEvent:
3622 case SpvOpTypeDeviceEvent:
3623 case SpvOpTypeReserveId:
3624 case SpvOpTypeQueue:
3626 vtn_handle_type(b, opcode, w, count);
3629 case SpvOpConstantTrue:
3630 case SpvOpConstantFalse:
3632 case SpvOpConstantComposite:
3633 case SpvOpConstantSampler:
3634 case SpvOpConstantNull:
3635 case SpvOpSpecConstantTrue:
3636 case SpvOpSpecConstantFalse:
3637 case SpvOpSpecConstant:
3638 case SpvOpSpecConstantComposite:
3639 case SpvOpSpecConstantOp:
3640 vtn_handle_constant(b, opcode, w, count);
3645 vtn_handle_variables(b, opcode, w, count);
3649 return false; /* End of preamble */
3656 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
3657 const uint32_t *w, unsigned count)
3663 case SpvOpLoopMerge:
3664 case SpvOpSelectionMerge:
3665 /* This is handled by cfg pre-pass and walk_blocks */
3669 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
3670 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
3675 vtn_handle_extension(b, opcode, w, count);
3681 case SpvOpCopyMemory:
3682 case SpvOpCopyMemorySized:
3683 case SpvOpAccessChain:
3684 case SpvOpPtrAccessChain:
3685 case SpvOpInBoundsAccessChain:
3686 case SpvOpArrayLength:
3687 vtn_handle_variables(b, opcode, w, count);
3690 case SpvOpFunctionCall:
3691 vtn_handle_function_call(b, opcode, w, count);
3694 case SpvOpSampledImage:
3696 case SpvOpImageSampleImplicitLod:
3697 case SpvOpImageSampleExplicitLod:
3698 case SpvOpImageSampleDrefImplicitLod:
3699 case SpvOpImageSampleDrefExplicitLod:
3700 case SpvOpImageSampleProjImplicitLod:
3701 case SpvOpImageSampleProjExplicitLod:
3702 case SpvOpImageSampleProjDrefImplicitLod:
3703 case SpvOpImageSampleProjDrefExplicitLod:
3704 case SpvOpImageFetch:
3705 case SpvOpImageGather:
3706 case SpvOpImageDrefGather:
3707 case SpvOpImageQuerySizeLod:
3708 case SpvOpImageQueryLod:
3709 case SpvOpImageQueryLevels:
3710 case SpvOpImageQuerySamples:
3711 vtn_handle_texture(b, opcode, w, count);
3714 case SpvOpImageRead:
3715 case SpvOpImageWrite:
3716 case SpvOpImageTexelPointer:
3717 vtn_handle_image(b, opcode, w, count);
3720 case SpvOpImageQuerySize: {
3721 struct vtn_pointer *image =
3722 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3723 if (image->mode == vtn_variable_mode_image) {
3724 vtn_handle_image(b, opcode, w, count);
3726 vtn_assert(image->mode == vtn_variable_mode_sampler);
3727 vtn_handle_texture(b, opcode, w, count);
3732 case SpvOpAtomicLoad:
3733 case SpvOpAtomicExchange:
3734 case SpvOpAtomicCompareExchange:
3735 case SpvOpAtomicCompareExchangeWeak:
3736 case SpvOpAtomicIIncrement:
3737 case SpvOpAtomicIDecrement:
3738 case SpvOpAtomicIAdd:
3739 case SpvOpAtomicISub:
3740 case SpvOpAtomicSMin:
3741 case SpvOpAtomicUMin:
3742 case SpvOpAtomicSMax:
3743 case SpvOpAtomicUMax:
3744 case SpvOpAtomicAnd:
3746 case SpvOpAtomicXor: {
3747 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
3748 if (pointer->value_type == vtn_value_type_image_pointer) {
3749 vtn_handle_image(b, opcode, w, count);
3751 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3752 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3757 case SpvOpAtomicStore: {
3758 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
3759 if (pointer->value_type == vtn_value_type_image_pointer) {
3760 vtn_handle_image(b, opcode, w, count);
3762 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3763 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3769 /* Handle OpSelect up-front here because it needs to be able to handle
3770 * pointers and not just regular vectors and scalars.
3772 struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
3773 struct vtn_value *sel_val = vtn_untyped_value(b, w[3]);
3774 struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
3775 struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
3777 const struct glsl_type *sel_type;
3778 switch (res_val->type->base_type) {
3779 case vtn_base_type_scalar:
3780 sel_type = glsl_bool_type();
3782 case vtn_base_type_vector:
3783 sel_type = glsl_vector_type(GLSL_TYPE_BOOL, res_val->type->length);
3785 case vtn_base_type_pointer:
3786 /* We need to have actual storage for pointer types */
3787 vtn_fail_if(res_val->type->type == NULL,
3788 "Invalid pointer result type for OpSelect");
3789 sel_type = glsl_bool_type();
3792 vtn_fail("Result type of OpSelect must be a scalar, vector, or pointer");
3795 if (unlikely(sel_val->type->type != sel_type)) {
3796 if (sel_val->type->type == glsl_bool_type()) {
3797 /* This case is illegal but some older versions of GLSLang produce
3798 * it. The GLSLang issue was fixed on March 30, 2017:
3800 * https://github.com/KhronosGroup/glslang/issues/809
3802 * Unfortunately, there are applications in the wild which are
3803 * shipping with this bug so it isn't nice to fail on them so we
3804 * throw a warning instead. It's not actually a problem for us as
3805 * nir_builder will just splat the condition out which is most
3806 * likely what the client wanted anyway.
3808 vtn_warn("Condition type of OpSelect must have the same number "
3809 "of components as Result Type");
3811 vtn_fail("Condition type of OpSelect must be a scalar or vector "
3812 "of Boolean type. It must have the same number of "
3813 "components as Result Type");
3817 vtn_fail_if(obj1_val->type != res_val->type ||
3818 obj2_val->type != res_val->type,
3819 "Object types must match the result type in OpSelect");
3821 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
3822 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, res_type->type);
3823 ssa->def = nir_bcsel(&b->nb, vtn_ssa_value(b, w[3])->def,
3824 vtn_ssa_value(b, w[4])->def,
3825 vtn_ssa_value(b, w[5])->def);
3826 vtn_push_ssa(b, w[2], res_type, ssa);
3835 case SpvOpConvertFToU:
3836 case SpvOpConvertFToS:
3837 case SpvOpConvertSToF:
3838 case SpvOpConvertUToF:
3842 case SpvOpQuantizeToF16:
3843 case SpvOpConvertPtrToU:
3844 case SpvOpConvertUToPtr:
3845 case SpvOpPtrCastToGeneric:
3846 case SpvOpGenericCastToPtr:
3852 case SpvOpSignBitSet:
3853 case SpvOpLessOrGreater:
3855 case SpvOpUnordered:
3870 case SpvOpVectorTimesScalar:
3872 case SpvOpIAddCarry:
3873 case SpvOpISubBorrow:
3874 case SpvOpUMulExtended:
3875 case SpvOpSMulExtended:
3876 case SpvOpShiftRightLogical:
3877 case SpvOpShiftRightArithmetic:
3878 case SpvOpShiftLeftLogical:
3879 case SpvOpLogicalEqual:
3880 case SpvOpLogicalNotEqual:
3881 case SpvOpLogicalOr:
3882 case SpvOpLogicalAnd:
3883 case SpvOpLogicalNot:
3884 case SpvOpBitwiseOr:
3885 case SpvOpBitwiseXor:
3886 case SpvOpBitwiseAnd:
3888 case SpvOpFOrdEqual:
3889 case SpvOpFUnordEqual:
3890 case SpvOpINotEqual:
3891 case SpvOpFOrdNotEqual:
3892 case SpvOpFUnordNotEqual:
3893 case SpvOpULessThan:
3894 case SpvOpSLessThan:
3895 case SpvOpFOrdLessThan:
3896 case SpvOpFUnordLessThan:
3897 case SpvOpUGreaterThan:
3898 case SpvOpSGreaterThan:
3899 case SpvOpFOrdGreaterThan:
3900 case SpvOpFUnordGreaterThan:
3901 case SpvOpULessThanEqual:
3902 case SpvOpSLessThanEqual:
3903 case SpvOpFOrdLessThanEqual:
3904 case SpvOpFUnordLessThanEqual:
3905 case SpvOpUGreaterThanEqual:
3906 case SpvOpSGreaterThanEqual:
3907 case SpvOpFOrdGreaterThanEqual:
3908 case SpvOpFUnordGreaterThanEqual:
3914 case SpvOpFwidthFine:
3915 case SpvOpDPdxCoarse:
3916 case SpvOpDPdyCoarse:
3917 case SpvOpFwidthCoarse:
3918 case SpvOpBitFieldInsert:
3919 case SpvOpBitFieldSExtract:
3920 case SpvOpBitFieldUExtract:
3921 case SpvOpBitReverse:
3923 case SpvOpTranspose:
3924 case SpvOpOuterProduct:
3925 case SpvOpMatrixTimesScalar:
3926 case SpvOpVectorTimesMatrix:
3927 case SpvOpMatrixTimesVector:
3928 case SpvOpMatrixTimesMatrix:
3929 vtn_handle_alu(b, opcode, w, count);
3932 case SpvOpVectorExtractDynamic:
3933 case SpvOpVectorInsertDynamic:
3934 case SpvOpVectorShuffle:
3935 case SpvOpCompositeConstruct:
3936 case SpvOpCompositeExtract:
3937 case SpvOpCompositeInsert:
3938 case SpvOpCopyObject:
3939 vtn_handle_composite(b, opcode, w, count);
3942 case SpvOpEmitVertex:
3943 case SpvOpEndPrimitive:
3944 case SpvOpEmitStreamVertex:
3945 case SpvOpEndStreamPrimitive:
3946 case SpvOpControlBarrier:
3947 case SpvOpMemoryBarrier:
3948 vtn_handle_barrier(b, opcode, w, count);
3951 case SpvOpGroupNonUniformElect:
3952 case SpvOpGroupNonUniformAll:
3953 case SpvOpGroupNonUniformAny:
3954 case SpvOpGroupNonUniformAllEqual:
3955 case SpvOpGroupNonUniformBroadcast:
3956 case SpvOpGroupNonUniformBroadcastFirst:
3957 case SpvOpGroupNonUniformBallot:
3958 case SpvOpGroupNonUniformInverseBallot:
3959 case SpvOpGroupNonUniformBallotBitExtract:
3960 case SpvOpGroupNonUniformBallotBitCount:
3961 case SpvOpGroupNonUniformBallotFindLSB:
3962 case SpvOpGroupNonUniformBallotFindMSB:
3963 case SpvOpGroupNonUniformShuffle:
3964 case SpvOpGroupNonUniformShuffleXor:
3965 case SpvOpGroupNonUniformShuffleUp:
3966 case SpvOpGroupNonUniformShuffleDown:
3967 case SpvOpGroupNonUniformIAdd:
3968 case SpvOpGroupNonUniformFAdd:
3969 case SpvOpGroupNonUniformIMul:
3970 case SpvOpGroupNonUniformFMul:
3971 case SpvOpGroupNonUniformSMin:
3972 case SpvOpGroupNonUniformUMin:
3973 case SpvOpGroupNonUniformFMin:
3974 case SpvOpGroupNonUniformSMax:
3975 case SpvOpGroupNonUniformUMax:
3976 case SpvOpGroupNonUniformFMax:
3977 case SpvOpGroupNonUniformBitwiseAnd:
3978 case SpvOpGroupNonUniformBitwiseOr:
3979 case SpvOpGroupNonUniformBitwiseXor:
3980 case SpvOpGroupNonUniformLogicalAnd:
3981 case SpvOpGroupNonUniformLogicalOr:
3982 case SpvOpGroupNonUniformLogicalXor:
3983 case SpvOpGroupNonUniformQuadBroadcast:
3984 case SpvOpGroupNonUniformQuadSwap:
3985 vtn_handle_subgroup(b, opcode, w, count);
3989 vtn_fail("Unhandled opcode");
3996 vtn_create_builder(const uint32_t *words, size_t word_count,
3997 gl_shader_stage stage, const char *entry_point_name,
3998 const struct spirv_to_nir_options *options)
4000 /* Initialize the vtn_builder object */
4001 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
4003 b->spirv_word_count = word_count;
4007 exec_list_make_empty(&b->functions);
4008 b->entry_point_stage = stage;
4009 b->entry_point_name = entry_point_name;
4010 b->options = options;
4012 /* Handle the SPIR-V header (first 4 dwords) */
4013 vtn_assert(word_count > 5);
4015 vtn_assert(words[0] == SpvMagicNumber);
4016 vtn_assert(words[1] >= 0x10000);
4017 /* words[2] == generator magic */
4018 unsigned value_id_bound = words[3];
4019 vtn_assert(words[4] == 0);
4021 b->value_id_bound = value_id_bound;
4022 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
4028 spirv_to_nir(const uint32_t *words, size_t word_count,
4029 struct nir_spirv_specialization *spec, unsigned num_spec,
4030 gl_shader_stage stage, const char *entry_point_name,
4031 const struct spirv_to_nir_options *options,
4032 const nir_shader_compiler_options *nir_options)
4035 const uint32_t *word_end = words + word_count;
4037 struct vtn_builder *b = vtn_create_builder(words, word_count,
4038 stage, entry_point_name,
4044 /* See also _vtn_fail() */
4045 if (setjmp(b->fail_jump)) {
4050 /* Skip the SPIR-V header, handled at vtn_create_builder */
4053 /* Handle all the preamble instructions */
4054 words = vtn_foreach_instruction(b, words, word_end,
4055 vtn_handle_preamble_instruction);
4057 if (b->entry_point == NULL) {
4058 vtn_fail("Entry point not found");
4063 b->shader = nir_shader_create(b, stage, nir_options, NULL);
4065 /* Set shader info defaults */
4066 b->shader->info.gs.invocations = 1;
4068 /* Parse execution modes */
4069 vtn_foreach_execution_mode(b, b->entry_point,
4070 vtn_handle_execution_mode, NULL);
4072 b->specializations = spec;
4073 b->num_specializations = num_spec;
4075 /* Handle all variable, type, and constant instructions */
4076 words = vtn_foreach_instruction(b, words, word_end,
4077 vtn_handle_variable_or_type_instruction);
4079 /* Set types on all vtn_values */
4080 vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
4082 vtn_build_cfg(b, words, word_end);
4084 assert(b->entry_point->value_type == vtn_value_type_function);
4085 b->entry_point->func->referenced = true;
4090 foreach_list_typed(struct vtn_function, func, node, &b->functions) {
4091 if (func->referenced && !func->emitted) {
4092 b->const_table = _mesa_hash_table_create(b, _mesa_hash_pointer,
4093 _mesa_key_pointer_equal);
4095 vtn_function_emit(b, func, vtn_handle_body_instruction);
4101 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
4102 nir_function *entry_point = b->entry_point->func->impl->function;
4103 vtn_assert(entry_point);
4105 /* Unparent the shader from the vtn_builder before we delete the builder */
4106 ralloc_steal(NULL, b->shader);