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