spirv: Replace assert with vtn_assert
[mesa.git] / src / compiler / spirv / spirv_to_nir.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Jason Ekstrand (jason@jlekstrand.net)
25 *
26 */
27
28 #include "vtn_private.h"
29 #include "nir/nir_vla.h"
30 #include "nir/nir_control_flow.h"
31 #include "nir/nir_constant_expressions.h"
32 #include "spirv_info.h"
33
34 void
35 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
36 size_t spirv_offset, const char *message)
37 {
38 if (b->options->debug.func) {
39 b->options->debug.func(b->options->debug.private_data,
40 level, spirv_offset, message);
41 }
42
43 #ifndef NDEBUG
44 if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
45 fprintf(stderr, "%s\n", message);
46 #endif
47 }
48
49 void
50 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
51 size_t spirv_offset, const char *fmt, ...)
52 {
53 va_list args;
54 char *msg;
55
56 va_start(args, fmt);
57 msg = ralloc_vasprintf(NULL, fmt, args);
58 va_end(args);
59
60 vtn_log(b, level, spirv_offset, msg);
61
62 ralloc_free(msg);
63 }
64
65 static void
66 vtn_log_err(struct vtn_builder *b,
67 enum nir_spirv_debug_level level, const char *prefix,
68 const char *file, unsigned line,
69 const char *fmt, va_list args)
70 {
71 char *msg;
72
73 msg = ralloc_strdup(NULL, prefix);
74
75 #ifndef NDEBUG
76 ralloc_asprintf_append(&msg, " In file %s:%u\n", file, line);
77 #endif
78
79 ralloc_asprintf_append(&msg, " ");
80
81 ralloc_vasprintf_append(&msg, fmt, args);
82
83 ralloc_asprintf_append(&msg, "\n %zu bytes into the SPIR-V binary",
84 b->spirv_offset);
85
86 if (b->file) {
87 ralloc_asprintf_append(&msg,
88 "\n in SPIR-V source file %s, line %d, col %d",
89 b->file, b->line, b->col);
90 }
91
92 vtn_log(b, level, b->spirv_offset, msg);
93
94 ralloc_free(msg);
95 }
96
97 void
98 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
99 const char *fmt, ...)
100 {
101 va_list args;
102
103 va_start(args, fmt);
104 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
105 file, line, fmt, args);
106 va_end(args);
107 }
108
109 void
110 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
111 const char *fmt, ...)
112 {
113 va_list args;
114
115 va_start(args, fmt);
116 vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
117 file, line, fmt, args);
118 va_end(args);
119
120 longjmp(b->fail_jump, 1);
121 }
122
123 struct spec_constant_value {
124 bool is_double;
125 union {
126 uint32_t data32;
127 uint64_t data64;
128 };
129 };
130
131 static struct vtn_ssa_value *
132 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
133 {
134 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
135 val->type = type;
136
137 if (glsl_type_is_vector_or_scalar(type)) {
138 unsigned num_components = glsl_get_vector_elements(val->type);
139 unsigned bit_size = glsl_get_bit_size(val->type);
140 val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
141 } else {
142 unsigned elems = glsl_get_length(val->type);
143 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
144 if (glsl_type_is_matrix(type)) {
145 const struct glsl_type *elem_type =
146 glsl_vector_type(glsl_get_base_type(type),
147 glsl_get_vector_elements(type));
148
149 for (unsigned i = 0; i < elems; i++)
150 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
151 } else if (glsl_type_is_array(type)) {
152 const struct glsl_type *elem_type = glsl_get_array_element(type);
153 for (unsigned i = 0; i < elems; i++)
154 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
155 } else {
156 for (unsigned i = 0; i < elems; i++) {
157 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
158 val->elems[i] = vtn_undef_ssa_value(b, elem_type);
159 }
160 }
161 }
162
163 return val;
164 }
165
166 static struct vtn_ssa_value *
167 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
168 const struct glsl_type *type)
169 {
170 struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
171
172 if (entry)
173 return entry->data;
174
175 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
176 val->type = type;
177
178 switch (glsl_get_base_type(type)) {
179 case GLSL_TYPE_INT:
180 case GLSL_TYPE_UINT:
181 case GLSL_TYPE_INT64:
182 case GLSL_TYPE_UINT64:
183 case GLSL_TYPE_BOOL:
184 case GLSL_TYPE_FLOAT:
185 case GLSL_TYPE_DOUBLE: {
186 int bit_size = glsl_get_bit_size(type);
187 if (glsl_type_is_vector_or_scalar(type)) {
188 unsigned num_components = glsl_get_vector_elements(val->type);
189 nir_load_const_instr *load =
190 nir_load_const_instr_create(b->shader, num_components, bit_size);
191
192 load->value = constant->values[0];
193
194 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
195 val->def = &load->def;
196 } else {
197 assert(glsl_type_is_matrix(type));
198 unsigned rows = glsl_get_vector_elements(val->type);
199 unsigned columns = glsl_get_matrix_columns(val->type);
200 val->elems = ralloc_array(b, struct vtn_ssa_value *, columns);
201
202 for (unsigned i = 0; i < columns; i++) {
203 struct vtn_ssa_value *col_val = rzalloc(b, struct vtn_ssa_value);
204 col_val->type = glsl_get_column_type(val->type);
205 nir_load_const_instr *load =
206 nir_load_const_instr_create(b->shader, rows, bit_size);
207
208 load->value = constant->values[i];
209
210 nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
211 col_val->def = &load->def;
212
213 val->elems[i] = col_val;
214 }
215 }
216 break;
217 }
218
219 case GLSL_TYPE_ARRAY: {
220 unsigned elems = glsl_get_length(val->type);
221 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
222 const struct glsl_type *elem_type = glsl_get_array_element(val->type);
223 for (unsigned i = 0; i < elems; i++)
224 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
225 elem_type);
226 break;
227 }
228
229 case GLSL_TYPE_STRUCT: {
230 unsigned elems = glsl_get_length(val->type);
231 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
232 for (unsigned i = 0; i < elems; i++) {
233 const struct glsl_type *elem_type =
234 glsl_get_struct_field(val->type, i);
235 val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
236 elem_type);
237 }
238 break;
239 }
240
241 default:
242 unreachable("bad constant type");
243 }
244
245 return val;
246 }
247
248 struct vtn_ssa_value *
249 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
250 {
251 struct vtn_value *val = vtn_untyped_value(b, value_id);
252 switch (val->value_type) {
253 case vtn_value_type_undef:
254 return vtn_undef_ssa_value(b, val->type->type);
255
256 case vtn_value_type_constant:
257 return vtn_const_ssa_value(b, val->constant, val->const_type);
258
259 case vtn_value_type_ssa:
260 return val->ssa;
261
262 case vtn_value_type_pointer:
263 vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
264 struct vtn_ssa_value *ssa =
265 vtn_create_ssa_value(b, val->pointer->ptr_type->type);
266 ssa->def = vtn_pointer_to_ssa(b, val->pointer);
267 return ssa;
268
269 default:
270 unreachable("Invalid type for an SSA value");
271 }
272 }
273
274 static char *
275 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
276 unsigned word_count, unsigned *words_used)
277 {
278 char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
279 if (words_used) {
280 /* Ammount of space taken by the string (including the null) */
281 unsigned len = strlen(dup) + 1;
282 *words_used = DIV_ROUND_UP(len, sizeof(*words));
283 }
284 return dup;
285 }
286
287 const uint32_t *
288 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
289 const uint32_t *end, vtn_instruction_handler handler)
290 {
291 b->file = NULL;
292 b->line = -1;
293 b->col = -1;
294
295 const uint32_t *w = start;
296 while (w < end) {
297 SpvOp opcode = w[0] & SpvOpCodeMask;
298 unsigned count = w[0] >> SpvWordCountShift;
299 vtn_assert(count >= 1 && w + count <= end);
300
301 b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
302
303 switch (opcode) {
304 case SpvOpNop:
305 break; /* Do nothing */
306
307 case SpvOpLine:
308 b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
309 b->line = w[2];
310 b->col = w[3];
311 break;
312
313 case SpvOpNoLine:
314 b->file = NULL;
315 b->line = -1;
316 b->col = -1;
317 break;
318
319 default:
320 if (!handler(b, opcode, w, count))
321 return w;
322 break;
323 }
324
325 w += count;
326 }
327
328 b->spirv_offset = 0;
329 b->file = NULL;
330 b->line = -1;
331 b->col = -1;
332
333 assert(w == end);
334 return w;
335 }
336
337 static void
338 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
339 const uint32_t *w, unsigned count)
340 {
341 switch (opcode) {
342 case SpvOpExtInstImport: {
343 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
344 if (strcmp((const char *)&w[2], "GLSL.std.450") == 0) {
345 val->ext_handler = vtn_handle_glsl450_instruction;
346 } else {
347 unreachable("Unsupported extension");
348 }
349 break;
350 }
351
352 case SpvOpExtInst: {
353 struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
354 bool handled = val->ext_handler(b, w[4], w, count);
355 vtn_assert(handled);
356 break;
357 }
358
359 default:
360 unreachable("Unhandled opcode");
361 }
362 }
363
364 static void
365 _foreach_decoration_helper(struct vtn_builder *b,
366 struct vtn_value *base_value,
367 int parent_member,
368 struct vtn_value *value,
369 vtn_decoration_foreach_cb cb, void *data)
370 {
371 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
372 int member;
373 if (dec->scope == VTN_DEC_DECORATION) {
374 member = parent_member;
375 } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
376 vtn_assert(parent_member == -1);
377 member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
378 } else {
379 /* Not a decoration */
380 continue;
381 }
382
383 if (dec->group) {
384 vtn_assert(dec->group->value_type == vtn_value_type_decoration_group);
385 _foreach_decoration_helper(b, base_value, member, dec->group,
386 cb, data);
387 } else {
388 cb(b, base_value, member, dec, data);
389 }
390 }
391 }
392
393 /** Iterates (recursively if needed) over all of the decorations on a value
394 *
395 * This function iterates over all of the decorations applied to a given
396 * value. If it encounters a decoration group, it recurses into the group
397 * and iterates over all of those decorations as well.
398 */
399 void
400 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
401 vtn_decoration_foreach_cb cb, void *data)
402 {
403 _foreach_decoration_helper(b, value, -1, value, cb, data);
404 }
405
406 void
407 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
408 vtn_execution_mode_foreach_cb cb, void *data)
409 {
410 for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
411 if (dec->scope != VTN_DEC_EXECUTION_MODE)
412 continue;
413
414 vtn_assert(dec->group == NULL);
415 cb(b, value, dec, data);
416 }
417 }
418
419 static void
420 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
421 const uint32_t *w, unsigned count)
422 {
423 const uint32_t *w_end = w + count;
424 const uint32_t target = w[1];
425 w += 2;
426
427 switch (opcode) {
428 case SpvOpDecorationGroup:
429 vtn_push_value(b, target, vtn_value_type_decoration_group);
430 break;
431
432 case SpvOpDecorate:
433 case SpvOpMemberDecorate:
434 case SpvOpExecutionMode: {
435 struct vtn_value *val = &b->values[target];
436
437 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
438 switch (opcode) {
439 case SpvOpDecorate:
440 dec->scope = VTN_DEC_DECORATION;
441 break;
442 case SpvOpMemberDecorate:
443 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(w++);
444 break;
445 case SpvOpExecutionMode:
446 dec->scope = VTN_DEC_EXECUTION_MODE;
447 break;
448 default:
449 unreachable("Invalid decoration opcode");
450 }
451 dec->decoration = *(w++);
452 dec->literals = w;
453
454 /* Link into the list */
455 dec->next = val->decoration;
456 val->decoration = dec;
457 break;
458 }
459
460 case SpvOpGroupMemberDecorate:
461 case SpvOpGroupDecorate: {
462 struct vtn_value *group =
463 vtn_value(b, target, vtn_value_type_decoration_group);
464
465 for (; w < w_end; w++) {
466 struct vtn_value *val = vtn_untyped_value(b, *w);
467 struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
468
469 dec->group = group;
470 if (opcode == SpvOpGroupDecorate) {
471 dec->scope = VTN_DEC_DECORATION;
472 } else {
473 dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
474 }
475
476 /* Link into the list */
477 dec->next = val->decoration;
478 val->decoration = dec;
479 }
480 break;
481 }
482
483 default:
484 unreachable("Unhandled opcode");
485 }
486 }
487
488 struct member_decoration_ctx {
489 unsigned num_fields;
490 struct glsl_struct_field *fields;
491 struct vtn_type *type;
492 };
493
494 /* does a shallow copy of a vtn_type */
495
496 static struct vtn_type *
497 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
498 {
499 struct vtn_type *dest = ralloc(b, struct vtn_type);
500 *dest = *src;
501
502 switch (src->base_type) {
503 case vtn_base_type_void:
504 case vtn_base_type_scalar:
505 case vtn_base_type_vector:
506 case vtn_base_type_matrix:
507 case vtn_base_type_array:
508 case vtn_base_type_pointer:
509 case vtn_base_type_image:
510 case vtn_base_type_sampler:
511 /* Nothing more to do */
512 break;
513
514 case vtn_base_type_struct:
515 dest->members = ralloc_array(b, struct vtn_type *, src->length);
516 memcpy(dest->members, src->members,
517 src->length * sizeof(src->members[0]));
518
519 dest->offsets = ralloc_array(b, unsigned, src->length);
520 memcpy(dest->offsets, src->offsets,
521 src->length * sizeof(src->offsets[0]));
522 break;
523
524 case vtn_base_type_function:
525 dest->params = ralloc_array(b, struct vtn_type *, src->length);
526 memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
527 break;
528 }
529
530 return dest;
531 }
532
533 static struct vtn_type *
534 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
535 {
536 type->members[member] = vtn_type_copy(b, type->members[member]);
537 type = type->members[member];
538
539 /* We may have an array of matrices.... Oh, joy! */
540 while (glsl_type_is_array(type->type)) {
541 type->array_element = vtn_type_copy(b, type->array_element);
542 type = type->array_element;
543 }
544
545 vtn_assert(glsl_type_is_matrix(type->type));
546
547 return type;
548 }
549
550 static void
551 struct_member_decoration_cb(struct vtn_builder *b,
552 struct vtn_value *val, int member,
553 const struct vtn_decoration *dec, void *void_ctx)
554 {
555 struct member_decoration_ctx *ctx = void_ctx;
556
557 if (member < 0)
558 return;
559
560 vtn_assert(member < ctx->num_fields);
561
562 switch (dec->decoration) {
563 case SpvDecorationNonWritable:
564 case SpvDecorationNonReadable:
565 case SpvDecorationRelaxedPrecision:
566 case SpvDecorationVolatile:
567 case SpvDecorationCoherent:
568 case SpvDecorationUniform:
569 break; /* FIXME: Do nothing with this for now. */
570 case SpvDecorationNoPerspective:
571 ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
572 break;
573 case SpvDecorationFlat:
574 ctx->fields[member].interpolation = INTERP_MODE_FLAT;
575 break;
576 case SpvDecorationCentroid:
577 ctx->fields[member].centroid = true;
578 break;
579 case SpvDecorationSample:
580 ctx->fields[member].sample = true;
581 break;
582 case SpvDecorationStream:
583 /* Vulkan only allows one GS stream */
584 vtn_assert(dec->literals[0] == 0);
585 break;
586 case SpvDecorationLocation:
587 ctx->fields[member].location = dec->literals[0];
588 break;
589 case SpvDecorationComponent:
590 break; /* FIXME: What should we do with these? */
591 case SpvDecorationBuiltIn:
592 ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
593 ctx->type->members[member]->is_builtin = true;
594 ctx->type->members[member]->builtin = dec->literals[0];
595 ctx->type->builtin_block = true;
596 break;
597 case SpvDecorationOffset:
598 ctx->type->offsets[member] = dec->literals[0];
599 break;
600 case SpvDecorationMatrixStride:
601 /* Handled as a second pass */
602 break;
603 case SpvDecorationColMajor:
604 break; /* Nothing to do here. Column-major is the default. */
605 case SpvDecorationRowMajor:
606 mutable_matrix_member(b, ctx->type, member)->row_major = true;
607 break;
608
609 case SpvDecorationPatch:
610 break;
611
612 case SpvDecorationSpecId:
613 case SpvDecorationBlock:
614 case SpvDecorationBufferBlock:
615 case SpvDecorationArrayStride:
616 case SpvDecorationGLSLShared:
617 case SpvDecorationGLSLPacked:
618 case SpvDecorationInvariant:
619 case SpvDecorationRestrict:
620 case SpvDecorationAliased:
621 case SpvDecorationConstant:
622 case SpvDecorationIndex:
623 case SpvDecorationBinding:
624 case SpvDecorationDescriptorSet:
625 case SpvDecorationLinkageAttributes:
626 case SpvDecorationNoContraction:
627 case SpvDecorationInputAttachmentIndex:
628 vtn_warn("Decoration not allowed on struct members: %s",
629 spirv_decoration_to_string(dec->decoration));
630 break;
631
632 case SpvDecorationXfbBuffer:
633 case SpvDecorationXfbStride:
634 vtn_warn("Vulkan does not have transform feedback");
635 break;
636
637 case SpvDecorationCPacked:
638 case SpvDecorationSaturatedConversion:
639 case SpvDecorationFuncParamAttr:
640 case SpvDecorationFPRoundingMode:
641 case SpvDecorationFPFastMathMode:
642 case SpvDecorationAlignment:
643 vtn_warn("Decoration only allowed for CL-style kernels: %s",
644 spirv_decoration_to_string(dec->decoration));
645 break;
646
647 default:
648 unreachable("Unhandled decoration");
649 }
650 }
651
652 /* Matrix strides are handled as a separate pass because we need to know
653 * whether the matrix is row-major or not first.
654 */
655 static void
656 struct_member_matrix_stride_cb(struct vtn_builder *b,
657 struct vtn_value *val, int member,
658 const struct vtn_decoration *dec,
659 void *void_ctx)
660 {
661 if (dec->decoration != SpvDecorationMatrixStride)
662 return;
663 vtn_assert(member >= 0);
664
665 struct member_decoration_ctx *ctx = void_ctx;
666
667 struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
668 if (mat_type->row_major) {
669 mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
670 mat_type->stride = mat_type->array_element->stride;
671 mat_type->array_element->stride = dec->literals[0];
672 } else {
673 vtn_assert(mat_type->array_element->stride > 0);
674 mat_type->stride = dec->literals[0];
675 }
676 }
677
678 static void
679 type_decoration_cb(struct vtn_builder *b,
680 struct vtn_value *val, int member,
681 const struct vtn_decoration *dec, void *ctx)
682 {
683 struct vtn_type *type = val->type;
684
685 if (member != -1)
686 return;
687
688 switch (dec->decoration) {
689 case SpvDecorationArrayStride:
690 vtn_assert(type->base_type == vtn_base_type_matrix ||
691 type->base_type == vtn_base_type_array ||
692 type->base_type == vtn_base_type_pointer);
693 type->stride = dec->literals[0];
694 break;
695 case SpvDecorationBlock:
696 vtn_assert(type->base_type == vtn_base_type_struct);
697 type->block = true;
698 break;
699 case SpvDecorationBufferBlock:
700 vtn_assert(type->base_type == vtn_base_type_struct);
701 type->buffer_block = true;
702 break;
703 case SpvDecorationGLSLShared:
704 case SpvDecorationGLSLPacked:
705 /* Ignore these, since we get explicit offsets anyways */
706 break;
707
708 case SpvDecorationRowMajor:
709 case SpvDecorationColMajor:
710 case SpvDecorationMatrixStride:
711 case SpvDecorationBuiltIn:
712 case SpvDecorationNoPerspective:
713 case SpvDecorationFlat:
714 case SpvDecorationPatch:
715 case SpvDecorationCentroid:
716 case SpvDecorationSample:
717 case SpvDecorationVolatile:
718 case SpvDecorationCoherent:
719 case SpvDecorationNonWritable:
720 case SpvDecorationNonReadable:
721 case SpvDecorationUniform:
722 case SpvDecorationStream:
723 case SpvDecorationLocation:
724 case SpvDecorationComponent:
725 case SpvDecorationOffset:
726 case SpvDecorationXfbBuffer:
727 case SpvDecorationXfbStride:
728 vtn_warn("Decoration only allowed for struct members: %s",
729 spirv_decoration_to_string(dec->decoration));
730 break;
731
732 case SpvDecorationRelaxedPrecision:
733 case SpvDecorationSpecId:
734 case SpvDecorationInvariant:
735 case SpvDecorationRestrict:
736 case SpvDecorationAliased:
737 case SpvDecorationConstant:
738 case SpvDecorationIndex:
739 case SpvDecorationBinding:
740 case SpvDecorationDescriptorSet:
741 case SpvDecorationLinkageAttributes:
742 case SpvDecorationNoContraction:
743 case SpvDecorationInputAttachmentIndex:
744 vtn_warn("Decoration not allowed on types: %s",
745 spirv_decoration_to_string(dec->decoration));
746 break;
747
748 case SpvDecorationCPacked:
749 case SpvDecorationSaturatedConversion:
750 case SpvDecorationFuncParamAttr:
751 case SpvDecorationFPRoundingMode:
752 case SpvDecorationFPFastMathMode:
753 case SpvDecorationAlignment:
754 vtn_warn("Decoration only allowed for CL-style kernels: %s",
755 spirv_decoration_to_string(dec->decoration));
756 break;
757
758 default:
759 unreachable("Unhandled decoration");
760 }
761 }
762
763 static unsigned
764 translate_image_format(SpvImageFormat format)
765 {
766 switch (format) {
767 case SpvImageFormatUnknown: return 0; /* GL_NONE */
768 case SpvImageFormatRgba32f: return 0x8814; /* GL_RGBA32F */
769 case SpvImageFormatRgba16f: return 0x881A; /* GL_RGBA16F */
770 case SpvImageFormatR32f: return 0x822E; /* GL_R32F */
771 case SpvImageFormatRgba8: return 0x8058; /* GL_RGBA8 */
772 case SpvImageFormatRgba8Snorm: return 0x8F97; /* GL_RGBA8_SNORM */
773 case SpvImageFormatRg32f: return 0x8230; /* GL_RG32F */
774 case SpvImageFormatRg16f: return 0x822F; /* GL_RG16F */
775 case SpvImageFormatR11fG11fB10f: return 0x8C3A; /* GL_R11F_G11F_B10F */
776 case SpvImageFormatR16f: return 0x822D; /* GL_R16F */
777 case SpvImageFormatRgba16: return 0x805B; /* GL_RGBA16 */
778 case SpvImageFormatRgb10A2: return 0x8059; /* GL_RGB10_A2 */
779 case SpvImageFormatRg16: return 0x822C; /* GL_RG16 */
780 case SpvImageFormatRg8: return 0x822B; /* GL_RG8 */
781 case SpvImageFormatR16: return 0x822A; /* GL_R16 */
782 case SpvImageFormatR8: return 0x8229; /* GL_R8 */
783 case SpvImageFormatRgba16Snorm: return 0x8F9B; /* GL_RGBA16_SNORM */
784 case SpvImageFormatRg16Snorm: return 0x8F99; /* GL_RG16_SNORM */
785 case SpvImageFormatRg8Snorm: return 0x8F95; /* GL_RG8_SNORM */
786 case SpvImageFormatR16Snorm: return 0x8F98; /* GL_R16_SNORM */
787 case SpvImageFormatR8Snorm: return 0x8F94; /* GL_R8_SNORM */
788 case SpvImageFormatRgba32i: return 0x8D82; /* GL_RGBA32I */
789 case SpvImageFormatRgba16i: return 0x8D88; /* GL_RGBA16I */
790 case SpvImageFormatRgba8i: return 0x8D8E; /* GL_RGBA8I */
791 case SpvImageFormatR32i: return 0x8235; /* GL_R32I */
792 case SpvImageFormatRg32i: return 0x823B; /* GL_RG32I */
793 case SpvImageFormatRg16i: return 0x8239; /* GL_RG16I */
794 case SpvImageFormatRg8i: return 0x8237; /* GL_RG8I */
795 case SpvImageFormatR16i: return 0x8233; /* GL_R16I */
796 case SpvImageFormatR8i: return 0x8231; /* GL_R8I */
797 case SpvImageFormatRgba32ui: return 0x8D70; /* GL_RGBA32UI */
798 case SpvImageFormatRgba16ui: return 0x8D76; /* GL_RGBA16UI */
799 case SpvImageFormatRgba8ui: return 0x8D7C; /* GL_RGBA8UI */
800 case SpvImageFormatR32ui: return 0x8236; /* GL_R32UI */
801 case SpvImageFormatRgb10a2ui: return 0x906F; /* GL_RGB10_A2UI */
802 case SpvImageFormatRg32ui: return 0x823C; /* GL_RG32UI */
803 case SpvImageFormatRg16ui: return 0x823A; /* GL_RG16UI */
804 case SpvImageFormatRg8ui: return 0x8238; /* GL_RG8UI */
805 case SpvImageFormatR16ui: return 0x8234; /* GL_R16UI */
806 case SpvImageFormatR8ui: return 0x8232; /* GL_R8UI */
807 default:
808 unreachable("Invalid image format");
809 return 0;
810 }
811 }
812
813 static void
814 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
815 const uint32_t *w, unsigned count)
816 {
817 struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_type);
818
819 val->type = rzalloc(b, struct vtn_type);
820 val->type->val = val;
821
822 switch (opcode) {
823 case SpvOpTypeVoid:
824 val->type->base_type = vtn_base_type_void;
825 val->type->type = glsl_void_type();
826 break;
827 case SpvOpTypeBool:
828 val->type->base_type = vtn_base_type_scalar;
829 val->type->type = glsl_bool_type();
830 break;
831 case SpvOpTypeInt: {
832 int bit_size = w[2];
833 const bool signedness = w[3];
834 val->type->base_type = vtn_base_type_scalar;
835 if (bit_size == 64)
836 val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
837 else
838 val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
839 break;
840 }
841 case SpvOpTypeFloat: {
842 int bit_size = w[2];
843 val->type->base_type = vtn_base_type_scalar;
844 val->type->type = bit_size == 64 ? glsl_double_type() : glsl_float_type();
845 break;
846 }
847
848 case SpvOpTypeVector: {
849 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
850 unsigned elems = w[3];
851
852 vtn_assert(glsl_type_is_scalar(base->type));
853 val->type->base_type = vtn_base_type_vector;
854 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
855 val->type->stride = glsl_get_bit_size(base->type) / 8;
856 val->type->array_element = base;
857 break;
858 }
859
860 case SpvOpTypeMatrix: {
861 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
862 unsigned columns = w[3];
863
864 vtn_assert(glsl_type_is_vector(base->type));
865 val->type->base_type = vtn_base_type_matrix;
866 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
867 glsl_get_vector_elements(base->type),
868 columns);
869 vtn_assert(!glsl_type_is_error(val->type->type));
870 val->type->length = columns;
871 val->type->array_element = base;
872 val->type->row_major = false;
873 val->type->stride = 0;
874 break;
875 }
876
877 case SpvOpTypeRuntimeArray:
878 case SpvOpTypeArray: {
879 struct vtn_type *array_element =
880 vtn_value(b, w[2], vtn_value_type_type)->type;
881
882 if (opcode == SpvOpTypeRuntimeArray) {
883 /* A length of 0 is used to denote unsized arrays */
884 val->type->length = 0;
885 } else {
886 val->type->length =
887 vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
888 }
889
890 val->type->base_type = vtn_base_type_array;
891 val->type->type = glsl_array_type(array_element->type, val->type->length);
892 val->type->array_element = array_element;
893 val->type->stride = 0;
894 break;
895 }
896
897 case SpvOpTypeStruct: {
898 unsigned num_fields = count - 2;
899 val->type->base_type = vtn_base_type_struct;
900 val->type->length = num_fields;
901 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
902 val->type->offsets = ralloc_array(b, unsigned, num_fields);
903
904 NIR_VLA(struct glsl_struct_field, fields, count);
905 for (unsigned i = 0; i < num_fields; i++) {
906 val->type->members[i] =
907 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
908 fields[i] = (struct glsl_struct_field) {
909 .type = val->type->members[i]->type,
910 .name = ralloc_asprintf(b, "field%d", i),
911 .location = -1,
912 };
913 }
914
915 struct member_decoration_ctx ctx = {
916 .num_fields = num_fields,
917 .fields = fields,
918 .type = val->type
919 };
920
921 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
922 vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
923
924 const char *name = val->name ? val->name : "struct";
925
926 val->type->type = glsl_struct_type(fields, num_fields, name);
927 break;
928 }
929
930 case SpvOpTypeFunction: {
931 val->type->base_type = vtn_base_type_function;
932 val->type->type = NULL;
933
934 val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
935
936 const unsigned num_params = count - 3;
937 val->type->length = num_params;
938 val->type->params = ralloc_array(b, struct vtn_type *, num_params);
939 for (unsigned i = 0; i < count - 3; i++) {
940 val->type->params[i] =
941 vtn_value(b, w[i + 3], vtn_value_type_type)->type;
942 }
943 break;
944 }
945
946 case SpvOpTypePointer: {
947 SpvStorageClass storage_class = w[2];
948 struct vtn_type *deref_type =
949 vtn_value(b, w[3], vtn_value_type_type)->type;
950
951 val->type->base_type = vtn_base_type_pointer;
952 val->type->storage_class = storage_class;
953 val->type->deref = deref_type;
954
955 if (storage_class == SpvStorageClassUniform ||
956 storage_class == SpvStorageClassStorageBuffer) {
957 /* These can actually be stored to nir_variables and used as SSA
958 * values so they need a real glsl_type.
959 */
960 val->type->type = glsl_vector_type(GLSL_TYPE_UINT, 2);
961 }
962 break;
963 }
964
965 case SpvOpTypeImage: {
966 val->type->base_type = vtn_base_type_image;
967
968 const struct glsl_type *sampled_type =
969 vtn_value(b, w[2], vtn_value_type_type)->type->type;
970
971 vtn_assert(glsl_type_is_vector_or_scalar(sampled_type));
972
973 enum glsl_sampler_dim dim;
974 switch ((SpvDim)w[3]) {
975 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
976 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
977 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
978 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
979 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
980 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
981 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
982 default:
983 unreachable("Invalid SPIR-V Sampler dimension");
984 }
985
986 bool is_shadow = w[4];
987 bool is_array = w[5];
988 bool multisampled = w[6];
989 unsigned sampled = w[7];
990 SpvImageFormat format = w[8];
991
992 if (count > 9)
993 val->type->access_qualifier = w[9];
994 else
995 val->type->access_qualifier = SpvAccessQualifierReadWrite;
996
997 if (multisampled) {
998 if (dim == GLSL_SAMPLER_DIM_2D)
999 dim = GLSL_SAMPLER_DIM_MS;
1000 else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1001 dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1002 else
1003 unreachable("Unsupported multisampled image type");
1004 }
1005
1006 val->type->image_format = translate_image_format(format);
1007
1008 if (sampled == 1) {
1009 val->type->sampled = true;
1010 val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
1011 glsl_get_base_type(sampled_type));
1012 } else if (sampled == 2) {
1013 vtn_assert(!is_shadow);
1014 val->type->sampled = false;
1015 val->type->type = glsl_image_type(dim, is_array,
1016 glsl_get_base_type(sampled_type));
1017 } else {
1018 unreachable("We need to know if the image will be sampled");
1019 }
1020 break;
1021 }
1022
1023 case SpvOpTypeSampledImage:
1024 val->type = vtn_value(b, w[2], vtn_value_type_type)->type;
1025 break;
1026
1027 case SpvOpTypeSampler:
1028 /* The actual sampler type here doesn't really matter. It gets
1029 * thrown away the moment you combine it with an image. What really
1030 * matters is that it's a sampler type as opposed to an integer type
1031 * so the backend knows what to do.
1032 */
1033 val->type->base_type = vtn_base_type_sampler;
1034 val->type->type = glsl_bare_sampler_type();
1035 break;
1036
1037 case SpvOpTypeOpaque:
1038 case SpvOpTypeEvent:
1039 case SpvOpTypeDeviceEvent:
1040 case SpvOpTypeReserveId:
1041 case SpvOpTypeQueue:
1042 case SpvOpTypePipe:
1043 default:
1044 unreachable("Unhandled opcode");
1045 }
1046
1047 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1048 }
1049
1050 static nir_constant *
1051 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
1052 {
1053 nir_constant *c = rzalloc(b, nir_constant);
1054
1055 /* For pointers and other typeless things, we have to return something but
1056 * it doesn't matter what.
1057 */
1058 if (!type)
1059 return c;
1060
1061 switch (glsl_get_base_type(type)) {
1062 case GLSL_TYPE_INT:
1063 case GLSL_TYPE_UINT:
1064 case GLSL_TYPE_INT64:
1065 case GLSL_TYPE_UINT64:
1066 case GLSL_TYPE_BOOL:
1067 case GLSL_TYPE_FLOAT:
1068 case GLSL_TYPE_DOUBLE:
1069 /* Nothing to do here. It's already initialized to zero */
1070 break;
1071
1072 case GLSL_TYPE_ARRAY:
1073 vtn_assert(glsl_get_length(type) > 0);
1074 c->num_elements = glsl_get_length(type);
1075 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1076
1077 c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
1078 for (unsigned i = 1; i < c->num_elements; i++)
1079 c->elements[i] = c->elements[0];
1080 break;
1081
1082 case GLSL_TYPE_STRUCT:
1083 c->num_elements = glsl_get_length(type);
1084 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1085
1086 for (unsigned i = 0; i < c->num_elements; i++) {
1087 c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
1088 }
1089 break;
1090
1091 default:
1092 unreachable("Invalid type for null constant");
1093 }
1094
1095 return c;
1096 }
1097
1098 static void
1099 spec_constant_decoration_cb(struct vtn_builder *b, struct vtn_value *v,
1100 int member, const struct vtn_decoration *dec,
1101 void *data)
1102 {
1103 vtn_assert(member == -1);
1104 if (dec->decoration != SpvDecorationSpecId)
1105 return;
1106
1107 struct spec_constant_value *const_value = data;
1108
1109 for (unsigned i = 0; i < b->num_specializations; i++) {
1110 if (b->specializations[i].id == dec->literals[0]) {
1111 if (const_value->is_double)
1112 const_value->data64 = b->specializations[i].data64;
1113 else
1114 const_value->data32 = b->specializations[i].data32;
1115 return;
1116 }
1117 }
1118 }
1119
1120 static uint32_t
1121 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1122 uint32_t const_value)
1123 {
1124 struct spec_constant_value data;
1125 data.is_double = false;
1126 data.data32 = const_value;
1127 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1128 return data.data32;
1129 }
1130
1131 static uint64_t
1132 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1133 uint64_t const_value)
1134 {
1135 struct spec_constant_value data;
1136 data.is_double = true;
1137 data.data64 = const_value;
1138 vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1139 return data.data64;
1140 }
1141
1142 static void
1143 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1144 struct vtn_value *val,
1145 int member,
1146 const struct vtn_decoration *dec,
1147 void *data)
1148 {
1149 vtn_assert(member == -1);
1150 if (dec->decoration != SpvDecorationBuiltIn ||
1151 dec->literals[0] != SpvBuiltInWorkgroupSize)
1152 return;
1153
1154 vtn_assert(val->const_type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1155
1156 b->shader->info.cs.local_size[0] = val->constant->values[0].u32[0];
1157 b->shader->info.cs.local_size[1] = val->constant->values[0].u32[1];
1158 b->shader->info.cs.local_size[2] = val->constant->values[0].u32[2];
1159 }
1160
1161 static void
1162 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1163 const uint32_t *w, unsigned count)
1164 {
1165 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1166 val->const_type = vtn_value(b, w[1], vtn_value_type_type)->type->type;
1167 val->constant = rzalloc(b, nir_constant);
1168 switch (opcode) {
1169 case SpvOpConstantTrue:
1170 vtn_assert(val->const_type == glsl_bool_type());
1171 val->constant->values[0].u32[0] = NIR_TRUE;
1172 break;
1173 case SpvOpConstantFalse:
1174 vtn_assert(val->const_type == glsl_bool_type());
1175 val->constant->values[0].u32[0] = NIR_FALSE;
1176 break;
1177
1178 case SpvOpSpecConstantTrue:
1179 case SpvOpSpecConstantFalse: {
1180 vtn_assert(val->const_type == glsl_bool_type());
1181 uint32_t int_val =
1182 get_specialization(b, val, (opcode == SpvOpSpecConstantTrue));
1183 val->constant->values[0].u32[0] = int_val ? NIR_TRUE : NIR_FALSE;
1184 break;
1185 }
1186
1187 case SpvOpConstant: {
1188 vtn_assert(glsl_type_is_scalar(val->const_type));
1189 int bit_size = glsl_get_bit_size(val->const_type);
1190 if (bit_size == 64) {
1191 val->constant->values->u32[0] = w[3];
1192 val->constant->values->u32[1] = w[4];
1193 } else {
1194 vtn_assert(bit_size == 32);
1195 val->constant->values->u32[0] = w[3];
1196 }
1197 break;
1198 }
1199 case SpvOpSpecConstant: {
1200 vtn_assert(glsl_type_is_scalar(val->const_type));
1201 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1202 int bit_size = glsl_get_bit_size(val->const_type);
1203 if (bit_size == 64)
1204 val->constant->values[0].u64[0] =
1205 get_specialization64(b, val, vtn_u64_literal(&w[3]));
1206 else
1207 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1208 break;
1209 }
1210 case SpvOpSpecConstantComposite:
1211 case SpvOpConstantComposite: {
1212 unsigned elem_count = count - 3;
1213 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1214 for (unsigned i = 0; i < elem_count; i++)
1215 elems[i] = vtn_value(b, w[i + 3], vtn_value_type_constant)->constant;
1216
1217 switch (glsl_get_base_type(val->const_type)) {
1218 case GLSL_TYPE_UINT:
1219 case GLSL_TYPE_INT:
1220 case GLSL_TYPE_UINT64:
1221 case GLSL_TYPE_INT64:
1222 case GLSL_TYPE_FLOAT:
1223 case GLSL_TYPE_BOOL:
1224 case GLSL_TYPE_DOUBLE: {
1225 int bit_size = glsl_get_bit_size(val->const_type);
1226 if (glsl_type_is_matrix(val->const_type)) {
1227 vtn_assert(glsl_get_matrix_columns(val->const_type) == elem_count);
1228 for (unsigned i = 0; i < elem_count; i++)
1229 val->constant->values[i] = elems[i]->values[0];
1230 } else {
1231 vtn_assert(glsl_type_is_vector(val->const_type));
1232 vtn_assert(glsl_get_vector_elements(val->const_type) == elem_count);
1233 for (unsigned i = 0; i < elem_count; i++) {
1234 if (bit_size == 64) {
1235 val->constant->values[0].u64[i] = elems[i]->values[0].u64[0];
1236 } else {
1237 vtn_assert(bit_size == 32);
1238 val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1239 }
1240 }
1241 }
1242 ralloc_free(elems);
1243 break;
1244 }
1245 case GLSL_TYPE_STRUCT:
1246 case GLSL_TYPE_ARRAY:
1247 ralloc_steal(val->constant, elems);
1248 val->constant->num_elements = elem_count;
1249 val->constant->elements = elems;
1250 break;
1251
1252 default:
1253 unreachable("Unsupported type for constants");
1254 }
1255 break;
1256 }
1257
1258 case SpvOpSpecConstantOp: {
1259 SpvOp opcode = get_specialization(b, val, w[3]);
1260 switch (opcode) {
1261 case SpvOpVectorShuffle: {
1262 struct vtn_value *v0 = &b->values[w[4]];
1263 struct vtn_value *v1 = &b->values[w[5]];
1264
1265 vtn_assert(v0->value_type == vtn_value_type_constant ||
1266 v0->value_type == vtn_value_type_undef);
1267 vtn_assert(v1->value_type == vtn_value_type_constant ||
1268 v1->value_type == vtn_value_type_undef);
1269
1270 unsigned len0 = v0->value_type == vtn_value_type_constant ?
1271 glsl_get_vector_elements(v0->const_type) :
1272 glsl_get_vector_elements(v0->type->type);
1273 unsigned len1 = v1->value_type == vtn_value_type_constant ?
1274 glsl_get_vector_elements(v1->const_type) :
1275 glsl_get_vector_elements(v1->type->type);
1276
1277 vtn_assert(len0 + len1 < 16);
1278
1279 unsigned bit_size = glsl_get_bit_size(val->const_type);
1280 unsigned bit_size0 = v0->value_type == vtn_value_type_constant ?
1281 glsl_get_bit_size(v0->const_type) :
1282 glsl_get_bit_size(v0->type->type);
1283 unsigned bit_size1 = v1->value_type == vtn_value_type_constant ?
1284 glsl_get_bit_size(v1->const_type) :
1285 glsl_get_bit_size(v1->type->type);
1286
1287 vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1288 (void)bit_size0; (void)bit_size1;
1289
1290 if (bit_size == 64) {
1291 uint64_t u64[8];
1292 if (v0->value_type == vtn_value_type_constant) {
1293 for (unsigned i = 0; i < len0; i++)
1294 u64[i] = v0->constant->values[0].u64[i];
1295 }
1296 if (v1->value_type == vtn_value_type_constant) {
1297 for (unsigned i = 0; i < len1; i++)
1298 u64[len0 + i] = v1->constant->values[0].u64[i];
1299 }
1300
1301 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1302 uint32_t comp = w[i + 6];
1303 /* If component is not used, set the value to a known constant
1304 * to detect if it is wrongly used.
1305 */
1306 if (comp == (uint32_t)-1)
1307 val->constant->values[0].u64[j] = 0xdeadbeefdeadbeef;
1308 else
1309 val->constant->values[0].u64[j] = u64[comp];
1310 }
1311 } else {
1312 uint32_t u32[8];
1313 if (v0->value_type == vtn_value_type_constant) {
1314 for (unsigned i = 0; i < len0; i++)
1315 u32[i] = v0->constant->values[0].u32[i];
1316 }
1317 if (v1->value_type == vtn_value_type_constant) {
1318 for (unsigned i = 0; i < len1; i++)
1319 u32[len0 + i] = v1->constant->values[0].u32[i];
1320 }
1321
1322 for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1323 uint32_t comp = w[i + 6];
1324 /* If component is not used, set the value to a known constant
1325 * to detect if it is wrongly used.
1326 */
1327 if (comp == (uint32_t)-1)
1328 val->constant->values[0].u32[j] = 0xdeadbeef;
1329 else
1330 val->constant->values[0].u32[j] = u32[comp];
1331 }
1332 }
1333 break;
1334 }
1335
1336 case SpvOpCompositeExtract:
1337 case SpvOpCompositeInsert: {
1338 struct vtn_value *comp;
1339 unsigned deref_start;
1340 struct nir_constant **c;
1341 if (opcode == SpvOpCompositeExtract) {
1342 comp = vtn_value(b, w[4], vtn_value_type_constant);
1343 deref_start = 5;
1344 c = &comp->constant;
1345 } else {
1346 comp = vtn_value(b, w[5], vtn_value_type_constant);
1347 deref_start = 6;
1348 val->constant = nir_constant_clone(comp->constant,
1349 (nir_variable *)b);
1350 c = &val->constant;
1351 }
1352
1353 int elem = -1;
1354 int col = 0;
1355 const struct glsl_type *type = comp->const_type;
1356 for (unsigned i = deref_start; i < count; i++) {
1357 switch (glsl_get_base_type(type)) {
1358 case GLSL_TYPE_UINT:
1359 case GLSL_TYPE_INT:
1360 case GLSL_TYPE_UINT64:
1361 case GLSL_TYPE_INT64:
1362 case GLSL_TYPE_FLOAT:
1363 case GLSL_TYPE_DOUBLE:
1364 case GLSL_TYPE_BOOL:
1365 /* If we hit this granularity, we're picking off an element */
1366 if (glsl_type_is_matrix(type)) {
1367 vtn_assert(col == 0 && elem == -1);
1368 col = w[i];
1369 elem = 0;
1370 type = glsl_get_column_type(type);
1371 } else {
1372 vtn_assert(elem <= 0 && glsl_type_is_vector(type));
1373 elem = w[i];
1374 type = glsl_scalar_type(glsl_get_base_type(type));
1375 }
1376 continue;
1377
1378 case GLSL_TYPE_ARRAY:
1379 c = &(*c)->elements[w[i]];
1380 type = glsl_get_array_element(type);
1381 continue;
1382
1383 case GLSL_TYPE_STRUCT:
1384 c = &(*c)->elements[w[i]];
1385 type = glsl_get_struct_field(type, w[i]);
1386 continue;
1387
1388 default:
1389 unreachable("Invalid constant type");
1390 }
1391 }
1392
1393 if (opcode == SpvOpCompositeExtract) {
1394 if (elem == -1) {
1395 val->constant = *c;
1396 } else {
1397 unsigned num_components = glsl_get_vector_elements(type);
1398 unsigned bit_size = glsl_get_bit_size(type);
1399 for (unsigned i = 0; i < num_components; i++)
1400 if (bit_size == 64) {
1401 val->constant->values[0].u64[i] = (*c)->values[col].u64[elem + i];
1402 } else {
1403 vtn_assert(bit_size == 32);
1404 val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1405 }
1406 }
1407 } else {
1408 struct vtn_value *insert =
1409 vtn_value(b, w[4], vtn_value_type_constant);
1410 vtn_assert(insert->const_type == type);
1411 if (elem == -1) {
1412 *c = insert->constant;
1413 } else {
1414 unsigned num_components = glsl_get_vector_elements(type);
1415 unsigned bit_size = glsl_get_bit_size(type);
1416 for (unsigned i = 0; i < num_components; i++)
1417 if (bit_size == 64) {
1418 (*c)->values[col].u64[elem + i] = insert->constant->values[0].u64[i];
1419 } else {
1420 vtn_assert(bit_size == 32);
1421 (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1422 }
1423 }
1424 }
1425 break;
1426 }
1427
1428 default: {
1429 bool swap;
1430 nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->const_type);
1431 nir_alu_type src_alu_type = dst_alu_type;
1432 nir_op op = vtn_nir_alu_op_for_spirv_opcode(opcode, &swap, src_alu_type, dst_alu_type);
1433
1434 unsigned num_components = glsl_get_vector_elements(val->const_type);
1435 unsigned bit_size =
1436 glsl_get_bit_size(val->const_type);
1437
1438 nir_const_value src[4];
1439 vtn_assert(count <= 7);
1440 for (unsigned i = 0; i < count - 4; i++) {
1441 nir_constant *c =
1442 vtn_value(b, w[4 + i], vtn_value_type_constant)->constant;
1443
1444 unsigned j = swap ? 1 - i : i;
1445 vtn_assert(bit_size == 32);
1446 src[j] = c->values[0];
1447 }
1448
1449 val->constant->values[0] =
1450 nir_eval_const_opcode(op, num_components, bit_size, src);
1451 break;
1452 } /* default */
1453 }
1454 break;
1455 }
1456
1457 case SpvOpConstantNull:
1458 val->constant = vtn_null_constant(b, val->const_type);
1459 break;
1460
1461 case SpvOpConstantSampler:
1462 unreachable("OpConstantSampler requires Kernel Capability");
1463 break;
1464
1465 default:
1466 unreachable("Unhandled opcode");
1467 }
1468
1469 /* Now that we have the value, update the workgroup size if needed */
1470 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1471 }
1472
1473 static void
1474 vtn_handle_function_call(struct vtn_builder *b, SpvOp opcode,
1475 const uint32_t *w, unsigned count)
1476 {
1477 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1478 struct vtn_function *vtn_callee =
1479 vtn_value(b, w[3], vtn_value_type_function)->func;
1480 struct nir_function *callee = vtn_callee->impl->function;
1481
1482 vtn_callee->referenced = true;
1483
1484 nir_call_instr *call = nir_call_instr_create(b->nb.shader, callee);
1485 for (unsigned i = 0; i < call->num_params; i++) {
1486 unsigned arg_id = w[4 + i];
1487 struct vtn_value *arg = vtn_untyped_value(b, arg_id);
1488 if (arg->value_type == vtn_value_type_pointer &&
1489 arg->pointer->ptr_type->type == NULL) {
1490 nir_deref_var *d = vtn_pointer_to_deref(b, arg->pointer);
1491 call->params[i] = nir_deref_var_clone(d, call);
1492 } else {
1493 struct vtn_ssa_value *arg_ssa = vtn_ssa_value(b, arg_id);
1494
1495 /* Make a temporary to store the argument in */
1496 nir_variable *tmp =
1497 nir_local_variable_create(b->nb.impl, arg_ssa->type, "arg_tmp");
1498 call->params[i] = nir_deref_var_create(call, tmp);
1499
1500 vtn_local_store(b, arg_ssa, call->params[i]);
1501 }
1502 }
1503
1504 nir_variable *out_tmp = NULL;
1505 vtn_assert(res_type->type == callee->return_type);
1506 if (!glsl_type_is_void(callee->return_type)) {
1507 out_tmp = nir_local_variable_create(b->nb.impl, callee->return_type,
1508 "out_tmp");
1509 call->return_deref = nir_deref_var_create(call, out_tmp);
1510 }
1511
1512 nir_builder_instr_insert(&b->nb, &call->instr);
1513
1514 if (glsl_type_is_void(callee->return_type)) {
1515 vtn_push_value(b, w[2], vtn_value_type_undef);
1516 } else {
1517 vtn_push_ssa(b, w[2], res_type, vtn_local_load(b, call->return_deref));
1518 }
1519 }
1520
1521 struct vtn_ssa_value *
1522 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1523 {
1524 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1525 val->type = type;
1526
1527 if (!glsl_type_is_vector_or_scalar(type)) {
1528 unsigned elems = glsl_get_length(type);
1529 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1530 for (unsigned i = 0; i < elems; i++) {
1531 const struct glsl_type *child_type;
1532
1533 switch (glsl_get_base_type(type)) {
1534 case GLSL_TYPE_INT:
1535 case GLSL_TYPE_UINT:
1536 case GLSL_TYPE_INT64:
1537 case GLSL_TYPE_UINT64:
1538 case GLSL_TYPE_BOOL:
1539 case GLSL_TYPE_FLOAT:
1540 case GLSL_TYPE_DOUBLE:
1541 child_type = glsl_get_column_type(type);
1542 break;
1543 case GLSL_TYPE_ARRAY:
1544 child_type = glsl_get_array_element(type);
1545 break;
1546 case GLSL_TYPE_STRUCT:
1547 child_type = glsl_get_struct_field(type, i);
1548 break;
1549 default:
1550 unreachable("unkown base type");
1551 }
1552
1553 val->elems[i] = vtn_create_ssa_value(b, child_type);
1554 }
1555 }
1556
1557 return val;
1558 }
1559
1560 static nir_tex_src
1561 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1562 {
1563 nir_tex_src src;
1564 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
1565 src.src_type = type;
1566 return src;
1567 }
1568
1569 static void
1570 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
1571 const uint32_t *w, unsigned count)
1572 {
1573 if (opcode == SpvOpSampledImage) {
1574 struct vtn_value *val =
1575 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
1576 val->sampled_image = ralloc(b, struct vtn_sampled_image);
1577 val->sampled_image->type =
1578 vtn_value(b, w[1], vtn_value_type_type)->type;
1579 val->sampled_image->image =
1580 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
1581 val->sampled_image->sampler =
1582 vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
1583 return;
1584 } else if (opcode == SpvOpImage) {
1585 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
1586 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
1587 if (src_val->value_type == vtn_value_type_sampled_image) {
1588 val->pointer = src_val->sampled_image->image;
1589 } else {
1590 vtn_assert(src_val->value_type == vtn_value_type_pointer);
1591 val->pointer = src_val->pointer;
1592 }
1593 return;
1594 }
1595
1596 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1597 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1598
1599 struct vtn_sampled_image sampled;
1600 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
1601 if (sampled_val->value_type == vtn_value_type_sampled_image) {
1602 sampled = *sampled_val->sampled_image;
1603 } else {
1604 vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
1605 sampled.type = sampled_val->pointer->type;
1606 sampled.image = NULL;
1607 sampled.sampler = sampled_val->pointer;
1608 }
1609
1610 const struct glsl_type *image_type = sampled.type->type;
1611 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
1612 const bool is_array = glsl_sampler_type_is_array(image_type);
1613 const bool is_shadow = glsl_sampler_type_is_shadow(image_type);
1614
1615 /* Figure out the base texture operation */
1616 nir_texop texop;
1617 switch (opcode) {
1618 case SpvOpImageSampleImplicitLod:
1619 case SpvOpImageSampleDrefImplicitLod:
1620 case SpvOpImageSampleProjImplicitLod:
1621 case SpvOpImageSampleProjDrefImplicitLod:
1622 texop = nir_texop_tex;
1623 break;
1624
1625 case SpvOpImageSampleExplicitLod:
1626 case SpvOpImageSampleDrefExplicitLod:
1627 case SpvOpImageSampleProjExplicitLod:
1628 case SpvOpImageSampleProjDrefExplicitLod:
1629 texop = nir_texop_txl;
1630 break;
1631
1632 case SpvOpImageFetch:
1633 if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
1634 texop = nir_texop_txf_ms;
1635 } else {
1636 texop = nir_texop_txf;
1637 }
1638 break;
1639
1640 case SpvOpImageGather:
1641 case SpvOpImageDrefGather:
1642 texop = nir_texop_tg4;
1643 break;
1644
1645 case SpvOpImageQuerySizeLod:
1646 case SpvOpImageQuerySize:
1647 texop = nir_texop_txs;
1648 break;
1649
1650 case SpvOpImageQueryLod:
1651 texop = nir_texop_lod;
1652 break;
1653
1654 case SpvOpImageQueryLevels:
1655 texop = nir_texop_query_levels;
1656 break;
1657
1658 case SpvOpImageQuerySamples:
1659 texop = nir_texop_texture_samples;
1660 break;
1661
1662 default:
1663 unreachable("Unhandled opcode");
1664 }
1665
1666 nir_tex_src srcs[8]; /* 8 should be enough */
1667 nir_tex_src *p = srcs;
1668
1669 unsigned idx = 4;
1670
1671 struct nir_ssa_def *coord;
1672 unsigned coord_components;
1673 switch (opcode) {
1674 case SpvOpImageSampleImplicitLod:
1675 case SpvOpImageSampleExplicitLod:
1676 case SpvOpImageSampleDrefImplicitLod:
1677 case SpvOpImageSampleDrefExplicitLod:
1678 case SpvOpImageSampleProjImplicitLod:
1679 case SpvOpImageSampleProjExplicitLod:
1680 case SpvOpImageSampleProjDrefImplicitLod:
1681 case SpvOpImageSampleProjDrefExplicitLod:
1682 case SpvOpImageFetch:
1683 case SpvOpImageGather:
1684 case SpvOpImageDrefGather:
1685 case SpvOpImageQueryLod: {
1686 /* All these types have the coordinate as their first real argument */
1687 switch (sampler_dim) {
1688 case GLSL_SAMPLER_DIM_1D:
1689 case GLSL_SAMPLER_DIM_BUF:
1690 coord_components = 1;
1691 break;
1692 case GLSL_SAMPLER_DIM_2D:
1693 case GLSL_SAMPLER_DIM_RECT:
1694 case GLSL_SAMPLER_DIM_MS:
1695 coord_components = 2;
1696 break;
1697 case GLSL_SAMPLER_DIM_3D:
1698 case GLSL_SAMPLER_DIM_CUBE:
1699 coord_components = 3;
1700 break;
1701 default:
1702 unreachable("Invalid sampler type");
1703 }
1704
1705 if (is_array && texop != nir_texop_lod)
1706 coord_components++;
1707
1708 coord = vtn_ssa_value(b, w[idx++])->def;
1709 p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
1710 (1 << coord_components) - 1));
1711 p->src_type = nir_tex_src_coord;
1712 p++;
1713 break;
1714 }
1715
1716 default:
1717 coord = NULL;
1718 coord_components = 0;
1719 break;
1720 }
1721
1722 switch (opcode) {
1723 case SpvOpImageSampleProjImplicitLod:
1724 case SpvOpImageSampleProjExplicitLod:
1725 case SpvOpImageSampleProjDrefImplicitLod:
1726 case SpvOpImageSampleProjDrefExplicitLod:
1727 /* These have the projector as the last coordinate component */
1728 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
1729 p->src_type = nir_tex_src_projector;
1730 p++;
1731 break;
1732
1733 default:
1734 break;
1735 }
1736
1737 unsigned gather_component = 0;
1738 switch (opcode) {
1739 case SpvOpImageSampleDrefImplicitLod:
1740 case SpvOpImageSampleDrefExplicitLod:
1741 case SpvOpImageSampleProjDrefImplicitLod:
1742 case SpvOpImageSampleProjDrefExplicitLod:
1743 case SpvOpImageDrefGather:
1744 /* These all have an explicit depth value as their next source */
1745 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
1746 break;
1747
1748 case SpvOpImageGather:
1749 /* This has a component as its next source */
1750 gather_component =
1751 vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
1752 break;
1753
1754 default:
1755 break;
1756 }
1757
1758 /* For OpImageQuerySizeLod, we always have an LOD */
1759 if (opcode == SpvOpImageQuerySizeLod)
1760 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
1761
1762 /* Now we need to handle some number of optional arguments */
1763 const struct vtn_ssa_value *gather_offsets = NULL;
1764 if (idx < count) {
1765 uint32_t operands = w[idx++];
1766
1767 if (operands & SpvImageOperandsBiasMask) {
1768 vtn_assert(texop == nir_texop_tex);
1769 texop = nir_texop_txb;
1770 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
1771 }
1772
1773 if (operands & SpvImageOperandsLodMask) {
1774 vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
1775 texop == nir_texop_txs);
1776 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
1777 }
1778
1779 if (operands & SpvImageOperandsGradMask) {
1780 vtn_assert(texop == nir_texop_txl);
1781 texop = nir_texop_txd;
1782 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
1783 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
1784 }
1785
1786 if (operands & SpvImageOperandsOffsetMask ||
1787 operands & SpvImageOperandsConstOffsetMask)
1788 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
1789
1790 if (operands & SpvImageOperandsConstOffsetsMask) {
1791 gather_offsets = vtn_ssa_value(b, w[idx++]);
1792 (*p++) = (nir_tex_src){};
1793 }
1794
1795 if (operands & SpvImageOperandsSampleMask) {
1796 vtn_assert(texop == nir_texop_txf_ms);
1797 texop = nir_texop_txf_ms;
1798 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
1799 }
1800 }
1801 /* We should have now consumed exactly all of the arguments */
1802 vtn_assert(idx == count);
1803
1804 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
1805 instr->op = texop;
1806
1807 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
1808
1809 instr->coord_components = coord_components;
1810 instr->sampler_dim = sampler_dim;
1811 instr->is_array = is_array;
1812 instr->is_shadow = is_shadow;
1813 instr->is_new_style_shadow =
1814 is_shadow && glsl_get_components(ret_type->type) == 1;
1815 instr->component = gather_component;
1816
1817 switch (glsl_get_sampler_result_type(image_type)) {
1818 case GLSL_TYPE_FLOAT: instr->dest_type = nir_type_float; break;
1819 case GLSL_TYPE_INT: instr->dest_type = nir_type_int; break;
1820 case GLSL_TYPE_UINT: instr->dest_type = nir_type_uint; break;
1821 case GLSL_TYPE_BOOL: instr->dest_type = nir_type_bool; break;
1822 default:
1823 unreachable("Invalid base type for sampler result");
1824 }
1825
1826 nir_deref_var *sampler = vtn_pointer_to_deref(b, sampled.sampler);
1827 nir_deref_var *texture;
1828 if (sampled.image) {
1829 nir_deref_var *image = vtn_pointer_to_deref(b, sampled.image);
1830 texture = image;
1831 } else {
1832 texture = sampler;
1833 }
1834
1835 instr->texture = nir_deref_var_clone(texture, instr);
1836
1837 switch (instr->op) {
1838 case nir_texop_tex:
1839 case nir_texop_txb:
1840 case nir_texop_txl:
1841 case nir_texop_txd:
1842 case nir_texop_tg4:
1843 /* These operations require a sampler */
1844 instr->sampler = nir_deref_var_clone(sampler, instr);
1845 break;
1846 case nir_texop_txf:
1847 case nir_texop_txf_ms:
1848 case nir_texop_txs:
1849 case nir_texop_lod:
1850 case nir_texop_query_levels:
1851 case nir_texop_texture_samples:
1852 case nir_texop_samples_identical:
1853 /* These don't */
1854 instr->sampler = NULL;
1855 break;
1856 case nir_texop_txf_ms_mcs:
1857 unreachable("unexpected nir_texop_txf_ms_mcs");
1858 }
1859
1860 nir_ssa_dest_init(&instr->instr, &instr->dest,
1861 nir_tex_instr_dest_size(instr), 32, NULL);
1862
1863 vtn_assert(glsl_get_vector_elements(ret_type->type) ==
1864 nir_tex_instr_dest_size(instr));
1865
1866 nir_ssa_def *def;
1867 nir_instr *instruction;
1868 if (gather_offsets) {
1869 vtn_assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
1870 vtn_assert(glsl_get_length(gather_offsets->type) == 4);
1871 nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
1872
1873 /* Copy the current instruction 4x */
1874 for (uint32_t i = 1; i < 4; i++) {
1875 instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
1876 instrs[i]->op = instr->op;
1877 instrs[i]->coord_components = instr->coord_components;
1878 instrs[i]->sampler_dim = instr->sampler_dim;
1879 instrs[i]->is_array = instr->is_array;
1880 instrs[i]->is_shadow = instr->is_shadow;
1881 instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
1882 instrs[i]->component = instr->component;
1883 instrs[i]->dest_type = instr->dest_type;
1884 instrs[i]->texture = nir_deref_var_clone(texture, instrs[i]);
1885 instrs[i]->sampler = NULL;
1886
1887 memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
1888
1889 nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
1890 nir_tex_instr_dest_size(instr), 32, NULL);
1891 }
1892
1893 /* Fill in the last argument with the offset from the passed in offsets
1894 * and insert the instruction into the stream.
1895 */
1896 for (uint32_t i = 0; i < 4; i++) {
1897 nir_tex_src src;
1898 src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
1899 src.src_type = nir_tex_src_offset;
1900 instrs[i]->src[instrs[i]->num_srcs - 1] = src;
1901 nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
1902 }
1903
1904 /* Combine the results of the 4 instructions by taking their .w
1905 * components
1906 */
1907 nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
1908 nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
1909 vec4->dest.write_mask = 0xf;
1910 for (uint32_t i = 0; i < 4; i++) {
1911 vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
1912 vec4->src[i].swizzle[0] = 3;
1913 }
1914 def = &vec4->dest.dest.ssa;
1915 instruction = &vec4->instr;
1916 } else {
1917 def = &instr->dest.ssa;
1918 instruction = &instr->instr;
1919 }
1920
1921 val->ssa = vtn_create_ssa_value(b, ret_type->type);
1922 val->ssa->def = def;
1923
1924 nir_builder_instr_insert(&b->nb, instruction);
1925 }
1926
1927 static void
1928 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
1929 const uint32_t *w, nir_src *src)
1930 {
1931 switch (opcode) {
1932 case SpvOpAtomicIIncrement:
1933 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
1934 break;
1935
1936 case SpvOpAtomicIDecrement:
1937 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
1938 break;
1939
1940 case SpvOpAtomicISub:
1941 src[0] =
1942 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
1943 break;
1944
1945 case SpvOpAtomicCompareExchange:
1946 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
1947 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
1948 break;
1949
1950 case SpvOpAtomicExchange:
1951 case SpvOpAtomicIAdd:
1952 case SpvOpAtomicSMin:
1953 case SpvOpAtomicUMin:
1954 case SpvOpAtomicSMax:
1955 case SpvOpAtomicUMax:
1956 case SpvOpAtomicAnd:
1957 case SpvOpAtomicOr:
1958 case SpvOpAtomicXor:
1959 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
1960 break;
1961
1962 default:
1963 unreachable("Invalid SPIR-V atomic");
1964 }
1965 }
1966
1967 static nir_ssa_def *
1968 get_image_coord(struct vtn_builder *b, uint32_t value)
1969 {
1970 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
1971
1972 /* The image_load_store intrinsics assume a 4-dim coordinate */
1973 unsigned dim = glsl_get_vector_elements(coord->type);
1974 unsigned swizzle[4];
1975 for (unsigned i = 0; i < 4; i++)
1976 swizzle[i] = MIN2(i, dim - 1);
1977
1978 return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
1979 }
1980
1981 static void
1982 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
1983 const uint32_t *w, unsigned count)
1984 {
1985 /* Just get this one out of the way */
1986 if (opcode == SpvOpImageTexelPointer) {
1987 struct vtn_value *val =
1988 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
1989 val->image = ralloc(b, struct vtn_image_pointer);
1990
1991 val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
1992 val->image->coord = get_image_coord(b, w[4]);
1993 val->image->sample = vtn_ssa_value(b, w[5])->def;
1994 return;
1995 }
1996
1997 struct vtn_image_pointer image;
1998
1999 switch (opcode) {
2000 case SpvOpAtomicExchange:
2001 case SpvOpAtomicCompareExchange:
2002 case SpvOpAtomicCompareExchangeWeak:
2003 case SpvOpAtomicIIncrement:
2004 case SpvOpAtomicIDecrement:
2005 case SpvOpAtomicIAdd:
2006 case SpvOpAtomicISub:
2007 case SpvOpAtomicLoad:
2008 case SpvOpAtomicSMin:
2009 case SpvOpAtomicUMin:
2010 case SpvOpAtomicSMax:
2011 case SpvOpAtomicUMax:
2012 case SpvOpAtomicAnd:
2013 case SpvOpAtomicOr:
2014 case SpvOpAtomicXor:
2015 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2016 break;
2017
2018 case SpvOpAtomicStore:
2019 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2020 break;
2021
2022 case SpvOpImageQuerySize:
2023 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2024 image.coord = NULL;
2025 image.sample = NULL;
2026 break;
2027
2028 case SpvOpImageRead:
2029 image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2030 image.coord = get_image_coord(b, w[4]);
2031
2032 if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
2033 vtn_assert(w[5] == SpvImageOperandsSampleMask);
2034 image.sample = vtn_ssa_value(b, w[6])->def;
2035 } else {
2036 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2037 }
2038 break;
2039
2040 case SpvOpImageWrite:
2041 image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2042 image.coord = get_image_coord(b, w[2]);
2043
2044 /* texel = w[3] */
2045
2046 if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
2047 vtn_assert(w[4] == SpvImageOperandsSampleMask);
2048 image.sample = vtn_ssa_value(b, w[5])->def;
2049 } else {
2050 image.sample = nir_ssa_undef(&b->nb, 1, 32);
2051 }
2052 break;
2053
2054 default:
2055 unreachable("Invalid image opcode");
2056 }
2057
2058 nir_intrinsic_op op;
2059 switch (opcode) {
2060 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_##N; break;
2061 OP(ImageQuerySize, size)
2062 OP(ImageRead, load)
2063 OP(ImageWrite, store)
2064 OP(AtomicLoad, load)
2065 OP(AtomicStore, store)
2066 OP(AtomicExchange, atomic_exchange)
2067 OP(AtomicCompareExchange, atomic_comp_swap)
2068 OP(AtomicIIncrement, atomic_add)
2069 OP(AtomicIDecrement, atomic_add)
2070 OP(AtomicIAdd, atomic_add)
2071 OP(AtomicISub, atomic_add)
2072 OP(AtomicSMin, atomic_min)
2073 OP(AtomicUMin, atomic_min)
2074 OP(AtomicSMax, atomic_max)
2075 OP(AtomicUMax, atomic_max)
2076 OP(AtomicAnd, atomic_and)
2077 OP(AtomicOr, atomic_or)
2078 OP(AtomicXor, atomic_xor)
2079 #undef OP
2080 default:
2081 unreachable("Invalid image opcode");
2082 }
2083
2084 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2085
2086 nir_deref_var *image_deref = vtn_pointer_to_deref(b, image.image);
2087 intrin->variables[0] = nir_deref_var_clone(image_deref, intrin);
2088
2089 /* ImageQuerySize doesn't take any extra parameters */
2090 if (opcode != SpvOpImageQuerySize) {
2091 /* The image coordinate is always 4 components but we may not have that
2092 * many. Swizzle to compensate.
2093 */
2094 unsigned swiz[4];
2095 for (unsigned i = 0; i < 4; i++)
2096 swiz[i] = i < image.coord->num_components ? i : 0;
2097 intrin->src[0] = nir_src_for_ssa(nir_swizzle(&b->nb, image.coord,
2098 swiz, 4, false));
2099 intrin->src[1] = nir_src_for_ssa(image.sample);
2100 }
2101
2102 switch (opcode) {
2103 case SpvOpAtomicLoad:
2104 case SpvOpImageQuerySize:
2105 case SpvOpImageRead:
2106 break;
2107 case SpvOpAtomicStore:
2108 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2109 break;
2110 case SpvOpImageWrite:
2111 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[3])->def);
2112 break;
2113
2114 case SpvOpAtomicCompareExchange:
2115 case SpvOpAtomicIIncrement:
2116 case SpvOpAtomicIDecrement:
2117 case SpvOpAtomicExchange:
2118 case SpvOpAtomicIAdd:
2119 case SpvOpAtomicISub:
2120 case SpvOpAtomicSMin:
2121 case SpvOpAtomicUMin:
2122 case SpvOpAtomicSMax:
2123 case SpvOpAtomicUMax:
2124 case SpvOpAtomicAnd:
2125 case SpvOpAtomicOr:
2126 case SpvOpAtomicXor:
2127 fill_common_atomic_sources(b, opcode, w, &intrin->src[2]);
2128 break;
2129
2130 default:
2131 unreachable("Invalid image opcode");
2132 }
2133
2134 if (opcode != SpvOpImageWrite) {
2135 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2136 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2137
2138 unsigned dest_components =
2139 nir_intrinsic_infos[intrin->intrinsic].dest_components;
2140 if (intrin->intrinsic == nir_intrinsic_image_size) {
2141 dest_components = intrin->num_components =
2142 glsl_get_vector_elements(type->type);
2143 }
2144
2145 nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2146 dest_components, 32, NULL);
2147
2148 nir_builder_instr_insert(&b->nb, &intrin->instr);
2149
2150 val->ssa = vtn_create_ssa_value(b, type->type);
2151 val->ssa->def = &intrin->dest.ssa;
2152 } else {
2153 nir_builder_instr_insert(&b->nb, &intrin->instr);
2154 }
2155 }
2156
2157 static nir_intrinsic_op
2158 get_ssbo_nir_atomic_op(SpvOp opcode)
2159 {
2160 switch (opcode) {
2161 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
2162 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
2163 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2164 OP(AtomicExchange, atomic_exchange)
2165 OP(AtomicCompareExchange, atomic_comp_swap)
2166 OP(AtomicIIncrement, atomic_add)
2167 OP(AtomicIDecrement, atomic_add)
2168 OP(AtomicIAdd, atomic_add)
2169 OP(AtomicISub, atomic_add)
2170 OP(AtomicSMin, atomic_imin)
2171 OP(AtomicUMin, atomic_umin)
2172 OP(AtomicSMax, atomic_imax)
2173 OP(AtomicUMax, atomic_umax)
2174 OP(AtomicAnd, atomic_and)
2175 OP(AtomicOr, atomic_or)
2176 OP(AtomicXor, atomic_xor)
2177 #undef OP
2178 default:
2179 unreachable("Invalid SSBO atomic");
2180 }
2181 }
2182
2183 static nir_intrinsic_op
2184 get_shared_nir_atomic_op(SpvOp opcode)
2185 {
2186 switch (opcode) {
2187 case SpvOpAtomicLoad: return nir_intrinsic_load_var;
2188 case SpvOpAtomicStore: return nir_intrinsic_store_var;
2189 #define OP(S, N) case SpvOp##S: return nir_intrinsic_var_##N;
2190 OP(AtomicExchange, atomic_exchange)
2191 OP(AtomicCompareExchange, atomic_comp_swap)
2192 OP(AtomicIIncrement, atomic_add)
2193 OP(AtomicIDecrement, atomic_add)
2194 OP(AtomicIAdd, atomic_add)
2195 OP(AtomicISub, atomic_add)
2196 OP(AtomicSMin, atomic_imin)
2197 OP(AtomicUMin, atomic_umin)
2198 OP(AtomicSMax, atomic_imax)
2199 OP(AtomicUMax, atomic_umax)
2200 OP(AtomicAnd, atomic_and)
2201 OP(AtomicOr, atomic_or)
2202 OP(AtomicXor, atomic_xor)
2203 #undef OP
2204 default:
2205 unreachable("Invalid shared atomic");
2206 }
2207 }
2208
2209 static void
2210 vtn_handle_ssbo_or_shared_atomic(struct vtn_builder *b, SpvOp opcode,
2211 const uint32_t *w, unsigned count)
2212 {
2213 struct vtn_pointer *ptr;
2214 nir_intrinsic_instr *atomic;
2215
2216 switch (opcode) {
2217 case SpvOpAtomicLoad:
2218 case SpvOpAtomicExchange:
2219 case SpvOpAtomicCompareExchange:
2220 case SpvOpAtomicCompareExchangeWeak:
2221 case SpvOpAtomicIIncrement:
2222 case SpvOpAtomicIDecrement:
2223 case SpvOpAtomicIAdd:
2224 case SpvOpAtomicISub:
2225 case SpvOpAtomicSMin:
2226 case SpvOpAtomicUMin:
2227 case SpvOpAtomicSMax:
2228 case SpvOpAtomicUMax:
2229 case SpvOpAtomicAnd:
2230 case SpvOpAtomicOr:
2231 case SpvOpAtomicXor:
2232 ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2233 break;
2234
2235 case SpvOpAtomicStore:
2236 ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2237 break;
2238
2239 default:
2240 unreachable("Invalid SPIR-V atomic");
2241 }
2242
2243 /*
2244 SpvScope scope = w[4];
2245 SpvMemorySemanticsMask semantics = w[5];
2246 */
2247
2248 if (ptr->mode == vtn_variable_mode_workgroup) {
2249 nir_deref_var *deref = vtn_pointer_to_deref(b, ptr);
2250 const struct glsl_type *deref_type = nir_deref_tail(&deref->deref)->type;
2251 nir_intrinsic_op op = get_shared_nir_atomic_op(opcode);
2252 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2253 atomic->variables[0] = nir_deref_var_clone(deref, atomic);
2254
2255 switch (opcode) {
2256 case SpvOpAtomicLoad:
2257 atomic->num_components = glsl_get_vector_elements(deref_type);
2258 break;
2259
2260 case SpvOpAtomicStore:
2261 atomic->num_components = glsl_get_vector_elements(deref_type);
2262 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2263 atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2264 break;
2265
2266 case SpvOpAtomicExchange:
2267 case SpvOpAtomicCompareExchange:
2268 case SpvOpAtomicCompareExchangeWeak:
2269 case SpvOpAtomicIIncrement:
2270 case SpvOpAtomicIDecrement:
2271 case SpvOpAtomicIAdd:
2272 case SpvOpAtomicISub:
2273 case SpvOpAtomicSMin:
2274 case SpvOpAtomicUMin:
2275 case SpvOpAtomicSMax:
2276 case SpvOpAtomicUMax:
2277 case SpvOpAtomicAnd:
2278 case SpvOpAtomicOr:
2279 case SpvOpAtomicXor:
2280 fill_common_atomic_sources(b, opcode, w, &atomic->src[0]);
2281 break;
2282
2283 default:
2284 unreachable("Invalid SPIR-V atomic");
2285
2286 }
2287 } else {
2288 vtn_assert(ptr->mode == vtn_variable_mode_ssbo);
2289 nir_ssa_def *offset, *index;
2290 offset = vtn_pointer_to_offset(b, ptr, &index, NULL);
2291
2292 nir_intrinsic_op op = get_ssbo_nir_atomic_op(opcode);
2293
2294 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2295
2296 switch (opcode) {
2297 case SpvOpAtomicLoad:
2298 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2299 atomic->src[0] = nir_src_for_ssa(index);
2300 atomic->src[1] = nir_src_for_ssa(offset);
2301 break;
2302
2303 case SpvOpAtomicStore:
2304 atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2305 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2306 atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2307 atomic->src[1] = nir_src_for_ssa(index);
2308 atomic->src[2] = nir_src_for_ssa(offset);
2309 break;
2310
2311 case SpvOpAtomicExchange:
2312 case SpvOpAtomicCompareExchange:
2313 case SpvOpAtomicCompareExchangeWeak:
2314 case SpvOpAtomicIIncrement:
2315 case SpvOpAtomicIDecrement:
2316 case SpvOpAtomicIAdd:
2317 case SpvOpAtomicISub:
2318 case SpvOpAtomicSMin:
2319 case SpvOpAtomicUMin:
2320 case SpvOpAtomicSMax:
2321 case SpvOpAtomicUMax:
2322 case SpvOpAtomicAnd:
2323 case SpvOpAtomicOr:
2324 case SpvOpAtomicXor:
2325 atomic->src[0] = nir_src_for_ssa(index);
2326 atomic->src[1] = nir_src_for_ssa(offset);
2327 fill_common_atomic_sources(b, opcode, w, &atomic->src[2]);
2328 break;
2329
2330 default:
2331 unreachable("Invalid SPIR-V atomic");
2332 }
2333 }
2334
2335 if (opcode != SpvOpAtomicStore) {
2336 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2337
2338 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2339 glsl_get_vector_elements(type->type),
2340 glsl_get_bit_size(type->type), NULL);
2341
2342 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2343 val->ssa = rzalloc(b, struct vtn_ssa_value);
2344 val->ssa->def = &atomic->dest.ssa;
2345 val->ssa->type = type->type;
2346 }
2347
2348 nir_builder_instr_insert(&b->nb, &atomic->instr);
2349 }
2350
2351 static nir_alu_instr *
2352 create_vec(nir_shader *shader, unsigned num_components, unsigned bit_size)
2353 {
2354 nir_op op;
2355 switch (num_components) {
2356 case 1: op = nir_op_fmov; break;
2357 case 2: op = nir_op_vec2; break;
2358 case 3: op = nir_op_vec3; break;
2359 case 4: op = nir_op_vec4; break;
2360 default: unreachable("bad vector size");
2361 }
2362
2363 nir_alu_instr *vec = nir_alu_instr_create(shader, op);
2364 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2365 bit_size, NULL);
2366 vec->dest.write_mask = (1 << num_components) - 1;
2367
2368 return vec;
2369 }
2370
2371 struct vtn_ssa_value *
2372 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2373 {
2374 if (src->transposed)
2375 return src->transposed;
2376
2377 struct vtn_ssa_value *dest =
2378 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2379
2380 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2381 nir_alu_instr *vec = create_vec(b->shader,
2382 glsl_get_matrix_columns(src->type),
2383 glsl_get_bit_size(src->type));
2384 if (glsl_type_is_vector_or_scalar(src->type)) {
2385 vec->src[0].src = nir_src_for_ssa(src->def);
2386 vec->src[0].swizzle[0] = i;
2387 } else {
2388 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2389 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2390 vec->src[j].swizzle[0] = i;
2391 }
2392 }
2393 nir_builder_instr_insert(&b->nb, &vec->instr);
2394 dest->elems[i]->def = &vec->dest.dest.ssa;
2395 }
2396
2397 dest->transposed = src;
2398
2399 return dest;
2400 }
2401
2402 nir_ssa_def *
2403 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2404 {
2405 unsigned swiz[4] = { index };
2406 return nir_swizzle(&b->nb, src, swiz, 1, true);
2407 }
2408
2409 nir_ssa_def *
2410 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2411 unsigned index)
2412 {
2413 nir_alu_instr *vec = create_vec(b->shader, src->num_components,
2414 src->bit_size);
2415
2416 for (unsigned i = 0; i < src->num_components; i++) {
2417 if (i == index) {
2418 vec->src[i].src = nir_src_for_ssa(insert);
2419 } else {
2420 vec->src[i].src = nir_src_for_ssa(src);
2421 vec->src[i].swizzle[0] = i;
2422 }
2423 }
2424
2425 nir_builder_instr_insert(&b->nb, &vec->instr);
2426
2427 return &vec->dest.dest.ssa;
2428 }
2429
2430 nir_ssa_def *
2431 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2432 nir_ssa_def *index)
2433 {
2434 nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
2435 for (unsigned i = 1; i < src->num_components; i++)
2436 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2437 vtn_vector_extract(b, src, i), dest);
2438
2439 return dest;
2440 }
2441
2442 nir_ssa_def *
2443 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2444 nir_ssa_def *insert, nir_ssa_def *index)
2445 {
2446 nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
2447 for (unsigned i = 1; i < src->num_components; i++)
2448 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2449 vtn_vector_insert(b, src, insert, i), dest);
2450
2451 return dest;
2452 }
2453
2454 static nir_ssa_def *
2455 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
2456 nir_ssa_def *src0, nir_ssa_def *src1,
2457 const uint32_t *indices)
2458 {
2459 nir_alu_instr *vec = create_vec(b->shader, num_components, src0->bit_size);
2460
2461 for (unsigned i = 0; i < num_components; i++) {
2462 uint32_t index = indices[i];
2463 if (index == 0xffffffff) {
2464 vec->src[i].src =
2465 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
2466 } else if (index < src0->num_components) {
2467 vec->src[i].src = nir_src_for_ssa(src0);
2468 vec->src[i].swizzle[0] = index;
2469 } else {
2470 vec->src[i].src = nir_src_for_ssa(src1);
2471 vec->src[i].swizzle[0] = index - src0->num_components;
2472 }
2473 }
2474
2475 nir_builder_instr_insert(&b->nb, &vec->instr);
2476
2477 return &vec->dest.dest.ssa;
2478 }
2479
2480 /*
2481 * Concatentates a number of vectors/scalars together to produce a vector
2482 */
2483 static nir_ssa_def *
2484 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
2485 unsigned num_srcs, nir_ssa_def **srcs)
2486 {
2487 nir_alu_instr *vec = create_vec(b->shader, num_components,
2488 srcs[0]->bit_size);
2489
2490 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2491 *
2492 * "When constructing a vector, there must be at least two Constituent
2493 * operands."
2494 */
2495 vtn_assert(num_srcs >= 2);
2496
2497 unsigned dest_idx = 0;
2498 for (unsigned i = 0; i < num_srcs; i++) {
2499 nir_ssa_def *src = srcs[i];
2500 vtn_assert(dest_idx + src->num_components <= num_components);
2501 for (unsigned j = 0; j < src->num_components; j++) {
2502 vec->src[dest_idx].src = nir_src_for_ssa(src);
2503 vec->src[dest_idx].swizzle[0] = j;
2504 dest_idx++;
2505 }
2506 }
2507
2508 /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2509 *
2510 * "When constructing a vector, the total number of components in all
2511 * the operands must equal the number of components in Result Type."
2512 */
2513 vtn_assert(dest_idx == num_components);
2514
2515 nir_builder_instr_insert(&b->nb, &vec->instr);
2516
2517 return &vec->dest.dest.ssa;
2518 }
2519
2520 static struct vtn_ssa_value *
2521 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
2522 {
2523 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
2524 dest->type = src->type;
2525
2526 if (glsl_type_is_vector_or_scalar(src->type)) {
2527 dest->def = src->def;
2528 } else {
2529 unsigned elems = glsl_get_length(src->type);
2530
2531 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
2532 for (unsigned i = 0; i < elems; i++)
2533 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
2534 }
2535
2536 return dest;
2537 }
2538
2539 static struct vtn_ssa_value *
2540 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
2541 struct vtn_ssa_value *insert, const uint32_t *indices,
2542 unsigned num_indices)
2543 {
2544 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
2545
2546 struct vtn_ssa_value *cur = dest;
2547 unsigned i;
2548 for (i = 0; i < num_indices - 1; i++) {
2549 cur = cur->elems[indices[i]];
2550 }
2551
2552 if (glsl_type_is_vector_or_scalar(cur->type)) {
2553 /* According to the SPIR-V spec, OpCompositeInsert may work down to
2554 * the component granularity. In that case, the last index will be
2555 * the index to insert the scalar into the vector.
2556 */
2557
2558 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
2559 } else {
2560 cur->elems[indices[i]] = insert;
2561 }
2562
2563 return dest;
2564 }
2565
2566 static struct vtn_ssa_value *
2567 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
2568 const uint32_t *indices, unsigned num_indices)
2569 {
2570 struct vtn_ssa_value *cur = src;
2571 for (unsigned i = 0; i < num_indices; i++) {
2572 if (glsl_type_is_vector_or_scalar(cur->type)) {
2573 vtn_assert(i == num_indices - 1);
2574 /* According to the SPIR-V spec, OpCompositeExtract may work down to
2575 * the component granularity. The last index will be the index of the
2576 * vector to extract.
2577 */
2578
2579 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
2580 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
2581 ret->def = vtn_vector_extract(b, cur->def, indices[i]);
2582 return ret;
2583 } else {
2584 cur = cur->elems[indices[i]];
2585 }
2586 }
2587
2588 return cur;
2589 }
2590
2591 static void
2592 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
2593 const uint32_t *w, unsigned count)
2594 {
2595 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2596 const struct glsl_type *type =
2597 vtn_value(b, w[1], vtn_value_type_type)->type->type;
2598 val->ssa = vtn_create_ssa_value(b, type);
2599
2600 switch (opcode) {
2601 case SpvOpVectorExtractDynamic:
2602 val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
2603 vtn_ssa_value(b, w[4])->def);
2604 break;
2605
2606 case SpvOpVectorInsertDynamic:
2607 val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
2608 vtn_ssa_value(b, w[4])->def,
2609 vtn_ssa_value(b, w[5])->def);
2610 break;
2611
2612 case SpvOpVectorShuffle:
2613 val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
2614 vtn_ssa_value(b, w[3])->def,
2615 vtn_ssa_value(b, w[4])->def,
2616 w + 5);
2617 break;
2618
2619 case SpvOpCompositeConstruct: {
2620 unsigned elems = count - 3;
2621 if (glsl_type_is_vector_or_scalar(type)) {
2622 nir_ssa_def *srcs[4];
2623 for (unsigned i = 0; i < elems; i++)
2624 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
2625 val->ssa->def =
2626 vtn_vector_construct(b, glsl_get_vector_elements(type),
2627 elems, srcs);
2628 } else {
2629 val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2630 for (unsigned i = 0; i < elems; i++)
2631 val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
2632 }
2633 break;
2634 }
2635 case SpvOpCompositeExtract:
2636 val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
2637 w + 4, count - 4);
2638 break;
2639
2640 case SpvOpCompositeInsert:
2641 val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
2642 vtn_ssa_value(b, w[3]),
2643 w + 5, count - 5);
2644 break;
2645
2646 case SpvOpCopyObject:
2647 val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
2648 break;
2649
2650 default:
2651 unreachable("unknown composite operation");
2652 }
2653 }
2654
2655 static void
2656 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
2657 const uint32_t *w, unsigned count)
2658 {
2659 nir_intrinsic_op intrinsic_op;
2660 switch (opcode) {
2661 case SpvOpEmitVertex:
2662 case SpvOpEmitStreamVertex:
2663 intrinsic_op = nir_intrinsic_emit_vertex;
2664 break;
2665 case SpvOpEndPrimitive:
2666 case SpvOpEndStreamPrimitive:
2667 intrinsic_op = nir_intrinsic_end_primitive;
2668 break;
2669 case SpvOpMemoryBarrier:
2670 intrinsic_op = nir_intrinsic_memory_barrier;
2671 break;
2672 case SpvOpControlBarrier:
2673 intrinsic_op = nir_intrinsic_barrier;
2674 break;
2675 default:
2676 unreachable("unknown barrier instruction");
2677 }
2678
2679 nir_intrinsic_instr *intrin =
2680 nir_intrinsic_instr_create(b->shader, intrinsic_op);
2681
2682 if (opcode == SpvOpEmitStreamVertex || opcode == SpvOpEndStreamPrimitive)
2683 nir_intrinsic_set_stream_id(intrin, w[1]);
2684
2685 nir_builder_instr_insert(&b->nb, &intrin->instr);
2686 }
2687
2688 static unsigned
2689 gl_primitive_from_spv_execution_mode(SpvExecutionMode mode)
2690 {
2691 switch (mode) {
2692 case SpvExecutionModeInputPoints:
2693 case SpvExecutionModeOutputPoints:
2694 return 0; /* GL_POINTS */
2695 case SpvExecutionModeInputLines:
2696 return 1; /* GL_LINES */
2697 case SpvExecutionModeInputLinesAdjacency:
2698 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
2699 case SpvExecutionModeTriangles:
2700 return 4; /* GL_TRIANGLES */
2701 case SpvExecutionModeInputTrianglesAdjacency:
2702 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
2703 case SpvExecutionModeQuads:
2704 return 7; /* GL_QUADS */
2705 case SpvExecutionModeIsolines:
2706 return 0x8E7A; /* GL_ISOLINES */
2707 case SpvExecutionModeOutputLineStrip:
2708 return 3; /* GL_LINE_STRIP */
2709 case SpvExecutionModeOutputTriangleStrip:
2710 return 5; /* GL_TRIANGLE_STRIP */
2711 default:
2712 unreachable("Invalid primitive type");
2713 return 4;
2714 }
2715 }
2716
2717 static unsigned
2718 vertices_in_from_spv_execution_mode(SpvExecutionMode mode)
2719 {
2720 switch (mode) {
2721 case SpvExecutionModeInputPoints:
2722 return 1;
2723 case SpvExecutionModeInputLines:
2724 return 2;
2725 case SpvExecutionModeInputLinesAdjacency:
2726 return 4;
2727 case SpvExecutionModeTriangles:
2728 return 3;
2729 case SpvExecutionModeInputTrianglesAdjacency:
2730 return 6;
2731 default:
2732 unreachable("Invalid GS input mode");
2733 return 0;
2734 }
2735 }
2736
2737 static gl_shader_stage
2738 stage_for_execution_model(SpvExecutionModel model)
2739 {
2740 switch (model) {
2741 case SpvExecutionModelVertex:
2742 return MESA_SHADER_VERTEX;
2743 case SpvExecutionModelTessellationControl:
2744 return MESA_SHADER_TESS_CTRL;
2745 case SpvExecutionModelTessellationEvaluation:
2746 return MESA_SHADER_TESS_EVAL;
2747 case SpvExecutionModelGeometry:
2748 return MESA_SHADER_GEOMETRY;
2749 case SpvExecutionModelFragment:
2750 return MESA_SHADER_FRAGMENT;
2751 case SpvExecutionModelGLCompute:
2752 return MESA_SHADER_COMPUTE;
2753 default:
2754 unreachable("Unsupported execution model");
2755 }
2756 }
2757
2758 #define spv_check_supported(name, cap) do { \
2759 if (!(b->options && b->options->caps.name)) \
2760 vtn_warn("Unsupported SPIR-V capability: %s", \
2761 spirv_capability_to_string(cap)); \
2762 } while(0)
2763
2764 static bool
2765 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
2766 const uint32_t *w, unsigned count)
2767 {
2768 switch (opcode) {
2769 case SpvOpSource: {
2770 const char *lang;
2771 switch (w[1]) {
2772 default:
2773 case SpvSourceLanguageUnknown: lang = "unknown"; break;
2774 case SpvSourceLanguageESSL: lang = "ESSL"; break;
2775 case SpvSourceLanguageGLSL: lang = "GLSL"; break;
2776 case SpvSourceLanguageOpenCL_C: lang = "OpenCL C"; break;
2777 case SpvSourceLanguageOpenCL_CPP: lang = "OpenCL C++"; break;
2778 case SpvSourceLanguageHLSL: lang = "HLSL"; break;
2779 }
2780
2781 uint32_t version = w[2];
2782
2783 const char *file =
2784 (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
2785
2786 vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
2787 break;
2788 }
2789
2790 case SpvOpSourceExtension:
2791 case SpvOpSourceContinued:
2792 case SpvOpExtension:
2793 /* Unhandled, but these are for debug so that's ok. */
2794 break;
2795
2796 case SpvOpCapability: {
2797 SpvCapability cap = w[1];
2798 switch (cap) {
2799 case SpvCapabilityMatrix:
2800 case SpvCapabilityShader:
2801 case SpvCapabilityGeometry:
2802 case SpvCapabilityGeometryPointSize:
2803 case SpvCapabilityUniformBufferArrayDynamicIndexing:
2804 case SpvCapabilitySampledImageArrayDynamicIndexing:
2805 case SpvCapabilityStorageBufferArrayDynamicIndexing:
2806 case SpvCapabilityStorageImageArrayDynamicIndexing:
2807 case SpvCapabilityImageRect:
2808 case SpvCapabilitySampledRect:
2809 case SpvCapabilitySampled1D:
2810 case SpvCapabilityImage1D:
2811 case SpvCapabilitySampledCubeArray:
2812 case SpvCapabilityImageCubeArray:
2813 case SpvCapabilitySampledBuffer:
2814 case SpvCapabilityImageBuffer:
2815 case SpvCapabilityImageQuery:
2816 case SpvCapabilityDerivativeControl:
2817 case SpvCapabilityInterpolationFunction:
2818 case SpvCapabilityMultiViewport:
2819 case SpvCapabilitySampleRateShading:
2820 case SpvCapabilityClipDistance:
2821 case SpvCapabilityCullDistance:
2822 case SpvCapabilityInputAttachment:
2823 case SpvCapabilityImageGatherExtended:
2824 case SpvCapabilityStorageImageExtendedFormats:
2825 break;
2826
2827 case SpvCapabilityGeometryStreams:
2828 case SpvCapabilityLinkage:
2829 case SpvCapabilityVector16:
2830 case SpvCapabilityFloat16Buffer:
2831 case SpvCapabilityFloat16:
2832 case SpvCapabilityInt64Atomics:
2833 case SpvCapabilityAtomicStorage:
2834 case SpvCapabilityInt16:
2835 case SpvCapabilityStorageImageMultisample:
2836 case SpvCapabilityInt8:
2837 case SpvCapabilitySparseResidency:
2838 case SpvCapabilityMinLod:
2839 case SpvCapabilityTransformFeedback:
2840 vtn_warn("Unsupported SPIR-V capability: %s",
2841 spirv_capability_to_string(cap));
2842 break;
2843
2844 case SpvCapabilityFloat64:
2845 spv_check_supported(float64, cap);
2846 break;
2847 case SpvCapabilityInt64:
2848 spv_check_supported(int64, cap);
2849 break;
2850
2851 case SpvCapabilityAddresses:
2852 case SpvCapabilityKernel:
2853 case SpvCapabilityImageBasic:
2854 case SpvCapabilityImageReadWrite:
2855 case SpvCapabilityImageMipmap:
2856 case SpvCapabilityPipes:
2857 case SpvCapabilityGroups:
2858 case SpvCapabilityDeviceEnqueue:
2859 case SpvCapabilityLiteralSampler:
2860 case SpvCapabilityGenericPointer:
2861 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
2862 spirv_capability_to_string(cap));
2863 break;
2864
2865 case SpvCapabilityImageMSArray:
2866 spv_check_supported(image_ms_array, cap);
2867 break;
2868
2869 case SpvCapabilityTessellation:
2870 case SpvCapabilityTessellationPointSize:
2871 spv_check_supported(tessellation, cap);
2872 break;
2873
2874 case SpvCapabilityDrawParameters:
2875 spv_check_supported(draw_parameters, cap);
2876 break;
2877
2878 case SpvCapabilityStorageImageReadWithoutFormat:
2879 spv_check_supported(image_read_without_format, cap);
2880 break;
2881
2882 case SpvCapabilityStorageImageWriteWithoutFormat:
2883 spv_check_supported(image_write_without_format, cap);
2884 break;
2885
2886 case SpvCapabilityMultiView:
2887 spv_check_supported(multiview, cap);
2888 break;
2889
2890 case SpvCapabilityVariablePointersStorageBuffer:
2891 case SpvCapabilityVariablePointers:
2892 spv_check_supported(variable_pointers, cap);
2893 break;
2894
2895 default:
2896 unreachable("Unhandled capability");
2897 }
2898 break;
2899 }
2900
2901 case SpvOpExtInstImport:
2902 vtn_handle_extension(b, opcode, w, count);
2903 break;
2904
2905 case SpvOpMemoryModel:
2906 vtn_assert(w[1] == SpvAddressingModelLogical);
2907 vtn_assert(w[2] == SpvMemoryModelSimple ||
2908 w[2] == SpvMemoryModelGLSL450);
2909 break;
2910
2911 case SpvOpEntryPoint: {
2912 struct vtn_value *entry_point = &b->values[w[2]];
2913 /* Let this be a name label regardless */
2914 unsigned name_words;
2915 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
2916
2917 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
2918 stage_for_execution_model(w[1]) != b->entry_point_stage)
2919 break;
2920
2921 vtn_assert(b->entry_point == NULL);
2922 b->entry_point = entry_point;
2923 break;
2924 }
2925
2926 case SpvOpString:
2927 vtn_push_value(b, w[1], vtn_value_type_string)->str =
2928 vtn_string_literal(b, &w[2], count - 2, NULL);
2929 break;
2930
2931 case SpvOpName:
2932 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
2933 break;
2934
2935 case SpvOpMemberName:
2936 /* TODO */
2937 break;
2938
2939 case SpvOpExecutionMode:
2940 case SpvOpDecorationGroup:
2941 case SpvOpDecorate:
2942 case SpvOpMemberDecorate:
2943 case SpvOpGroupDecorate:
2944 case SpvOpGroupMemberDecorate:
2945 vtn_handle_decoration(b, opcode, w, count);
2946 break;
2947
2948 default:
2949 return false; /* End of preamble */
2950 }
2951
2952 return true;
2953 }
2954
2955 static void
2956 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
2957 const struct vtn_decoration *mode, void *data)
2958 {
2959 vtn_assert(b->entry_point == entry_point);
2960
2961 switch(mode->exec_mode) {
2962 case SpvExecutionModeOriginUpperLeft:
2963 case SpvExecutionModeOriginLowerLeft:
2964 b->origin_upper_left =
2965 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
2966 break;
2967
2968 case SpvExecutionModeEarlyFragmentTests:
2969 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
2970 b->shader->info.fs.early_fragment_tests = true;
2971 break;
2972
2973 case SpvExecutionModeInvocations:
2974 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
2975 b->shader->info.gs.invocations = MAX2(1, mode->literals[0]);
2976 break;
2977
2978 case SpvExecutionModeDepthReplacing:
2979 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
2980 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
2981 break;
2982 case SpvExecutionModeDepthGreater:
2983 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
2984 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
2985 break;
2986 case SpvExecutionModeDepthLess:
2987 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
2988 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
2989 break;
2990 case SpvExecutionModeDepthUnchanged:
2991 vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
2992 b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2993 break;
2994
2995 case SpvExecutionModeLocalSize:
2996 vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
2997 b->shader->info.cs.local_size[0] = mode->literals[0];
2998 b->shader->info.cs.local_size[1] = mode->literals[1];
2999 b->shader->info.cs.local_size[2] = mode->literals[2];
3000 break;
3001 case SpvExecutionModeLocalSizeHint:
3002 break; /* Nothing to do with this */
3003
3004 case SpvExecutionModeOutputVertices:
3005 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3006 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3007 b->shader->info.tess.tcs_vertices_out = mode->literals[0];
3008 } else {
3009 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3010 b->shader->info.gs.vertices_out = mode->literals[0];
3011 }
3012 break;
3013
3014 case SpvExecutionModeInputPoints:
3015 case SpvExecutionModeInputLines:
3016 case SpvExecutionModeInputLinesAdjacency:
3017 case SpvExecutionModeTriangles:
3018 case SpvExecutionModeInputTrianglesAdjacency:
3019 case SpvExecutionModeQuads:
3020 case SpvExecutionModeIsolines:
3021 if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3022 b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3023 b->shader->info.tess.primitive_mode =
3024 gl_primitive_from_spv_execution_mode(mode->exec_mode);
3025 } else {
3026 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3027 b->shader->info.gs.vertices_in =
3028 vertices_in_from_spv_execution_mode(mode->exec_mode);
3029 }
3030 break;
3031
3032 case SpvExecutionModeOutputPoints:
3033 case SpvExecutionModeOutputLineStrip:
3034 case SpvExecutionModeOutputTriangleStrip:
3035 vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3036 b->shader->info.gs.output_primitive =
3037 gl_primitive_from_spv_execution_mode(mode->exec_mode);
3038 break;
3039
3040 case SpvExecutionModeSpacingEqual:
3041 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3042 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3043 b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
3044 break;
3045 case SpvExecutionModeSpacingFractionalEven:
3046 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3047 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3048 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
3049 break;
3050 case SpvExecutionModeSpacingFractionalOdd:
3051 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3052 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3053 b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
3054 break;
3055 case SpvExecutionModeVertexOrderCw:
3056 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3057 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3058 b->shader->info.tess.ccw = false;
3059 break;
3060 case SpvExecutionModeVertexOrderCcw:
3061 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3062 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3063 b->shader->info.tess.ccw = true;
3064 break;
3065 case SpvExecutionModePointMode:
3066 vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3067 b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3068 b->shader->info.tess.point_mode = true;
3069 break;
3070
3071 case SpvExecutionModePixelCenterInteger:
3072 b->pixel_center_integer = true;
3073 break;
3074
3075 case SpvExecutionModeXfb:
3076 unreachable("Unhandled execution mode");
3077 break;
3078
3079 case SpvExecutionModeVecTypeHint:
3080 case SpvExecutionModeContractionOff:
3081 break; /* OpenCL */
3082
3083 default:
3084 unreachable("Unhandled execution mode");
3085 }
3086 }
3087
3088 static bool
3089 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
3090 const uint32_t *w, unsigned count)
3091 {
3092 switch (opcode) {
3093 case SpvOpSource:
3094 case SpvOpSourceContinued:
3095 case SpvOpSourceExtension:
3096 case SpvOpExtension:
3097 case SpvOpCapability:
3098 case SpvOpExtInstImport:
3099 case SpvOpMemoryModel:
3100 case SpvOpEntryPoint:
3101 case SpvOpExecutionMode:
3102 case SpvOpString:
3103 case SpvOpName:
3104 case SpvOpMemberName:
3105 case SpvOpDecorationGroup:
3106 case SpvOpDecorate:
3107 case SpvOpMemberDecorate:
3108 case SpvOpGroupDecorate:
3109 case SpvOpGroupMemberDecorate:
3110 unreachable("Invalid opcode types and variables section");
3111 break;
3112
3113 case SpvOpTypeVoid:
3114 case SpvOpTypeBool:
3115 case SpvOpTypeInt:
3116 case SpvOpTypeFloat:
3117 case SpvOpTypeVector:
3118 case SpvOpTypeMatrix:
3119 case SpvOpTypeImage:
3120 case SpvOpTypeSampler:
3121 case SpvOpTypeSampledImage:
3122 case SpvOpTypeArray:
3123 case SpvOpTypeRuntimeArray:
3124 case SpvOpTypeStruct:
3125 case SpvOpTypeOpaque:
3126 case SpvOpTypePointer:
3127 case SpvOpTypeFunction:
3128 case SpvOpTypeEvent:
3129 case SpvOpTypeDeviceEvent:
3130 case SpvOpTypeReserveId:
3131 case SpvOpTypeQueue:
3132 case SpvOpTypePipe:
3133 vtn_handle_type(b, opcode, w, count);
3134 break;
3135
3136 case SpvOpConstantTrue:
3137 case SpvOpConstantFalse:
3138 case SpvOpConstant:
3139 case SpvOpConstantComposite:
3140 case SpvOpConstantSampler:
3141 case SpvOpConstantNull:
3142 case SpvOpSpecConstantTrue:
3143 case SpvOpSpecConstantFalse:
3144 case SpvOpSpecConstant:
3145 case SpvOpSpecConstantComposite:
3146 case SpvOpSpecConstantOp:
3147 vtn_handle_constant(b, opcode, w, count);
3148 break;
3149
3150 case SpvOpUndef:
3151 case SpvOpVariable:
3152 vtn_handle_variables(b, opcode, w, count);
3153 break;
3154
3155 default:
3156 return false; /* End of preamble */
3157 }
3158
3159 return true;
3160 }
3161
3162 static bool
3163 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
3164 const uint32_t *w, unsigned count)
3165 {
3166 switch (opcode) {
3167 case SpvOpLabel:
3168 break;
3169
3170 case SpvOpLoopMerge:
3171 case SpvOpSelectionMerge:
3172 /* This is handled by cfg pre-pass and walk_blocks */
3173 break;
3174
3175 case SpvOpUndef: {
3176 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
3177 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
3178 break;
3179 }
3180
3181 case SpvOpExtInst:
3182 vtn_handle_extension(b, opcode, w, count);
3183 break;
3184
3185 case SpvOpVariable:
3186 case SpvOpLoad:
3187 case SpvOpStore:
3188 case SpvOpCopyMemory:
3189 case SpvOpCopyMemorySized:
3190 case SpvOpAccessChain:
3191 case SpvOpPtrAccessChain:
3192 case SpvOpInBoundsAccessChain:
3193 case SpvOpArrayLength:
3194 vtn_handle_variables(b, opcode, w, count);
3195 break;
3196
3197 case SpvOpFunctionCall:
3198 vtn_handle_function_call(b, opcode, w, count);
3199 break;
3200
3201 case SpvOpSampledImage:
3202 case SpvOpImage:
3203 case SpvOpImageSampleImplicitLod:
3204 case SpvOpImageSampleExplicitLod:
3205 case SpvOpImageSampleDrefImplicitLod:
3206 case SpvOpImageSampleDrefExplicitLod:
3207 case SpvOpImageSampleProjImplicitLod:
3208 case SpvOpImageSampleProjExplicitLod:
3209 case SpvOpImageSampleProjDrefImplicitLod:
3210 case SpvOpImageSampleProjDrefExplicitLod:
3211 case SpvOpImageFetch:
3212 case SpvOpImageGather:
3213 case SpvOpImageDrefGather:
3214 case SpvOpImageQuerySizeLod:
3215 case SpvOpImageQueryLod:
3216 case SpvOpImageQueryLevels:
3217 case SpvOpImageQuerySamples:
3218 vtn_handle_texture(b, opcode, w, count);
3219 break;
3220
3221 case SpvOpImageRead:
3222 case SpvOpImageWrite:
3223 case SpvOpImageTexelPointer:
3224 vtn_handle_image(b, opcode, w, count);
3225 break;
3226
3227 case SpvOpImageQuerySize: {
3228 struct vtn_pointer *image =
3229 vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3230 if (image->mode == vtn_variable_mode_image) {
3231 vtn_handle_image(b, opcode, w, count);
3232 } else {
3233 vtn_assert(image->mode == vtn_variable_mode_sampler);
3234 vtn_handle_texture(b, opcode, w, count);
3235 }
3236 break;
3237 }
3238
3239 case SpvOpAtomicLoad:
3240 case SpvOpAtomicExchange:
3241 case SpvOpAtomicCompareExchange:
3242 case SpvOpAtomicCompareExchangeWeak:
3243 case SpvOpAtomicIIncrement:
3244 case SpvOpAtomicIDecrement:
3245 case SpvOpAtomicIAdd:
3246 case SpvOpAtomicISub:
3247 case SpvOpAtomicSMin:
3248 case SpvOpAtomicUMin:
3249 case SpvOpAtomicSMax:
3250 case SpvOpAtomicUMax:
3251 case SpvOpAtomicAnd:
3252 case SpvOpAtomicOr:
3253 case SpvOpAtomicXor: {
3254 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
3255 if (pointer->value_type == vtn_value_type_image_pointer) {
3256 vtn_handle_image(b, opcode, w, count);
3257 } else {
3258 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3259 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3260 }
3261 break;
3262 }
3263
3264 case SpvOpAtomicStore: {
3265 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
3266 if (pointer->value_type == vtn_value_type_image_pointer) {
3267 vtn_handle_image(b, opcode, w, count);
3268 } else {
3269 vtn_assert(pointer->value_type == vtn_value_type_pointer);
3270 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3271 }
3272 break;
3273 }
3274
3275 case SpvOpSelect: {
3276 /* Handle OpSelect up-front here because it needs to be able to handle
3277 * pointers and not just regular vectors and scalars.
3278 */
3279 struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
3280 struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, res_type->type);
3281 ssa->def = nir_bcsel(&b->nb, vtn_ssa_value(b, w[3])->def,
3282 vtn_ssa_value(b, w[4])->def,
3283 vtn_ssa_value(b, w[5])->def);
3284 vtn_push_ssa(b, w[2], res_type, ssa);
3285 break;
3286 }
3287
3288 case SpvOpSNegate:
3289 case SpvOpFNegate:
3290 case SpvOpNot:
3291 case SpvOpAny:
3292 case SpvOpAll:
3293 case SpvOpConvertFToU:
3294 case SpvOpConvertFToS:
3295 case SpvOpConvertSToF:
3296 case SpvOpConvertUToF:
3297 case SpvOpUConvert:
3298 case SpvOpSConvert:
3299 case SpvOpFConvert:
3300 case SpvOpQuantizeToF16:
3301 case SpvOpConvertPtrToU:
3302 case SpvOpConvertUToPtr:
3303 case SpvOpPtrCastToGeneric:
3304 case SpvOpGenericCastToPtr:
3305 case SpvOpBitcast:
3306 case SpvOpIsNan:
3307 case SpvOpIsInf:
3308 case SpvOpIsFinite:
3309 case SpvOpIsNormal:
3310 case SpvOpSignBitSet:
3311 case SpvOpLessOrGreater:
3312 case SpvOpOrdered:
3313 case SpvOpUnordered:
3314 case SpvOpIAdd:
3315 case SpvOpFAdd:
3316 case SpvOpISub:
3317 case SpvOpFSub:
3318 case SpvOpIMul:
3319 case SpvOpFMul:
3320 case SpvOpUDiv:
3321 case SpvOpSDiv:
3322 case SpvOpFDiv:
3323 case SpvOpUMod:
3324 case SpvOpSRem:
3325 case SpvOpSMod:
3326 case SpvOpFRem:
3327 case SpvOpFMod:
3328 case SpvOpVectorTimesScalar:
3329 case SpvOpDot:
3330 case SpvOpIAddCarry:
3331 case SpvOpISubBorrow:
3332 case SpvOpUMulExtended:
3333 case SpvOpSMulExtended:
3334 case SpvOpShiftRightLogical:
3335 case SpvOpShiftRightArithmetic:
3336 case SpvOpShiftLeftLogical:
3337 case SpvOpLogicalEqual:
3338 case SpvOpLogicalNotEqual:
3339 case SpvOpLogicalOr:
3340 case SpvOpLogicalAnd:
3341 case SpvOpLogicalNot:
3342 case SpvOpBitwiseOr:
3343 case SpvOpBitwiseXor:
3344 case SpvOpBitwiseAnd:
3345 case SpvOpIEqual:
3346 case SpvOpFOrdEqual:
3347 case SpvOpFUnordEqual:
3348 case SpvOpINotEqual:
3349 case SpvOpFOrdNotEqual:
3350 case SpvOpFUnordNotEqual:
3351 case SpvOpULessThan:
3352 case SpvOpSLessThan:
3353 case SpvOpFOrdLessThan:
3354 case SpvOpFUnordLessThan:
3355 case SpvOpUGreaterThan:
3356 case SpvOpSGreaterThan:
3357 case SpvOpFOrdGreaterThan:
3358 case SpvOpFUnordGreaterThan:
3359 case SpvOpULessThanEqual:
3360 case SpvOpSLessThanEqual:
3361 case SpvOpFOrdLessThanEqual:
3362 case SpvOpFUnordLessThanEqual:
3363 case SpvOpUGreaterThanEqual:
3364 case SpvOpSGreaterThanEqual:
3365 case SpvOpFOrdGreaterThanEqual:
3366 case SpvOpFUnordGreaterThanEqual:
3367 case SpvOpDPdx:
3368 case SpvOpDPdy:
3369 case SpvOpFwidth:
3370 case SpvOpDPdxFine:
3371 case SpvOpDPdyFine:
3372 case SpvOpFwidthFine:
3373 case SpvOpDPdxCoarse:
3374 case SpvOpDPdyCoarse:
3375 case SpvOpFwidthCoarse:
3376 case SpvOpBitFieldInsert:
3377 case SpvOpBitFieldSExtract:
3378 case SpvOpBitFieldUExtract:
3379 case SpvOpBitReverse:
3380 case SpvOpBitCount:
3381 case SpvOpTranspose:
3382 case SpvOpOuterProduct:
3383 case SpvOpMatrixTimesScalar:
3384 case SpvOpVectorTimesMatrix:
3385 case SpvOpMatrixTimesVector:
3386 case SpvOpMatrixTimesMatrix:
3387 vtn_handle_alu(b, opcode, w, count);
3388 break;
3389
3390 case SpvOpVectorExtractDynamic:
3391 case SpvOpVectorInsertDynamic:
3392 case SpvOpVectorShuffle:
3393 case SpvOpCompositeConstruct:
3394 case SpvOpCompositeExtract:
3395 case SpvOpCompositeInsert:
3396 case SpvOpCopyObject:
3397 vtn_handle_composite(b, opcode, w, count);
3398 break;
3399
3400 case SpvOpEmitVertex:
3401 case SpvOpEndPrimitive:
3402 case SpvOpEmitStreamVertex:
3403 case SpvOpEndStreamPrimitive:
3404 case SpvOpControlBarrier:
3405 case SpvOpMemoryBarrier:
3406 vtn_handle_barrier(b, opcode, w, count);
3407 break;
3408
3409 default:
3410 unreachable("Unhandled opcode");
3411 }
3412
3413 return true;
3414 }
3415
3416 nir_function *
3417 spirv_to_nir(const uint32_t *words, size_t word_count,
3418 struct nir_spirv_specialization *spec, unsigned num_spec,
3419 gl_shader_stage stage, const char *entry_point_name,
3420 const struct spirv_to_nir_options *options,
3421 const nir_shader_compiler_options *nir_options)
3422 {
3423 /* Initialize the stn_builder object */
3424 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
3425 b->spirv = words;
3426 b->file = NULL;
3427 b->line = -1;
3428 b->col = -1;
3429 exec_list_make_empty(&b->functions);
3430 b->entry_point_stage = stage;
3431 b->entry_point_name = entry_point_name;
3432 b->options = options;
3433
3434 /* See also _vtn_fail() */
3435 if (setjmp(b->fail_jump)) {
3436 ralloc_free(b);
3437 return NULL;
3438 }
3439
3440 const uint32_t *word_end = words + word_count;
3441
3442 /* Handle the SPIR-V header (first 4 dwords) */
3443 vtn_assert(word_count > 5);
3444
3445 vtn_assert(words[0] == SpvMagicNumber);
3446 vtn_assert(words[1] >= 0x10000);
3447 /* words[2] == generator magic */
3448 unsigned value_id_bound = words[3];
3449 vtn_assert(words[4] == 0);
3450
3451 words+= 5;
3452
3453 b->value_id_bound = value_id_bound;
3454 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
3455
3456 /* Handle all the preamble instructions */
3457 words = vtn_foreach_instruction(b, words, word_end,
3458 vtn_handle_preamble_instruction);
3459
3460 if (b->entry_point == NULL) {
3461 assert(!"Entry point not found");
3462 ralloc_free(b);
3463 return NULL;
3464 }
3465
3466 b->shader = nir_shader_create(b, stage, nir_options, NULL);
3467
3468 /* Set shader info defaults */
3469 b->shader->info.gs.invocations = 1;
3470
3471 /* Parse execution modes */
3472 vtn_foreach_execution_mode(b, b->entry_point,
3473 vtn_handle_execution_mode, NULL);
3474
3475 b->specializations = spec;
3476 b->num_specializations = num_spec;
3477
3478 /* Handle all variable, type, and constant instructions */
3479 words = vtn_foreach_instruction(b, words, word_end,
3480 vtn_handle_variable_or_type_instruction);
3481
3482 vtn_build_cfg(b, words, word_end);
3483
3484 assert(b->entry_point->value_type == vtn_value_type_function);
3485 b->entry_point->func->referenced = true;
3486
3487 bool progress;
3488 do {
3489 progress = false;
3490 foreach_list_typed(struct vtn_function, func, node, &b->functions) {
3491 if (func->referenced && !func->emitted) {
3492 b->const_table = _mesa_hash_table_create(b, _mesa_hash_pointer,
3493 _mesa_key_pointer_equal);
3494
3495 vtn_function_emit(b, func, vtn_handle_body_instruction);
3496 progress = true;
3497 }
3498 }
3499 } while (progress);
3500
3501 vtn_assert(b->entry_point->value_type == vtn_value_type_function);
3502 nir_function *entry_point = b->entry_point->func->impl->function;
3503 vtn_assert(entry_point);
3504
3505 /* Unparent the shader from the vtn_builder before we delete the builder */
3506 ralloc_steal(NULL, b->shader);
3507
3508 ralloc_free(b);
3509
3510 return entry_point;
3511 }