nir: Make nir_copy_deref follow the "clone" pattern
[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 val->type->type = glsl_float_type();
709 break;
710
711 case SpvOpTypeVector: {
712 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
713 unsigned elems = w[3];
714
715 assert(glsl_type_is_scalar(base->type));
716 val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
717
718 /* Vectors implicitly have sizeof(base_type) stride. For now, this
719 * is always 4 bytes. This will have to change if we want to start
720 * supporting doubles or half-floats.
721 */
722 val->type->stride = 4;
723 val->type->array_element = base;
724 break;
725 }
726
727 case SpvOpTypeMatrix: {
728 struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
729 unsigned columns = w[3];
730
731 assert(glsl_type_is_vector(base->type));
732 val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
733 glsl_get_vector_elements(base->type),
734 columns);
735 assert(!glsl_type_is_error(val->type->type));
736 val->type->array_element = base;
737 val->type->row_major = false;
738 val->type->stride = 0;
739 break;
740 }
741
742 case SpvOpTypeRuntimeArray:
743 case SpvOpTypeArray: {
744 struct vtn_type *array_element =
745 vtn_value(b, w[2], vtn_value_type_type)->type;
746
747 unsigned length;
748 if (opcode == SpvOpTypeRuntimeArray) {
749 /* A length of 0 is used to denote unsized arrays */
750 length = 0;
751 } else {
752 length =
753 vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
754 }
755
756 val->type->type = glsl_array_type(array_element->type, length);
757 val->type->array_element = array_element;
758 val->type->stride = 0;
759 break;
760 }
761
762 case SpvOpTypeStruct: {
763 unsigned num_fields = count - 2;
764 val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
765 val->type->offsets = ralloc_array(b, unsigned, num_fields);
766
767 NIR_VLA(struct glsl_struct_field, fields, count);
768 for (unsigned i = 0; i < num_fields; i++) {
769 val->type->members[i] =
770 vtn_value(b, w[i + 2], vtn_value_type_type)->type;
771 fields[i] = (struct glsl_struct_field) {
772 .type = val->type->members[i]->type,
773 .name = ralloc_asprintf(b, "field%d", i),
774 .location = -1,
775 };
776 }
777
778 struct member_decoration_ctx ctx = {
779 .num_fields = num_fields,
780 .fields = fields,
781 .type = val->type
782 };
783
784 vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
785
786 const char *name = val->name ? val->name : "struct";
787
788 val->type->type = glsl_struct_type(fields, num_fields, name);
789 break;
790 }
791
792 case SpvOpTypeFunction: {
793 const struct glsl_type *return_type =
794 vtn_value(b, w[2], vtn_value_type_type)->type->type;
795 NIR_VLA(struct glsl_function_param, params, count - 3);
796 for (unsigned i = 0; i < count - 3; i++) {
797 params[i].type = vtn_value(b, w[i + 3], vtn_value_type_type)->type->type;
798
799 /* FIXME: */
800 params[i].in = true;
801 params[i].out = true;
802 }
803 val->type->type = glsl_function_type(return_type, params, count - 3);
804 break;
805 }
806
807 case SpvOpTypePointer:
808 /* FIXME: For now, we'll just do the really lame thing and return
809 * the same type. The validator should ensure that the proper number
810 * of dereferences happen
811 */
812 val->type = vtn_value(b, w[3], vtn_value_type_type)->type;
813 break;
814
815 case SpvOpTypeImage: {
816 const struct glsl_type *sampled_type =
817 vtn_value(b, w[2], vtn_value_type_type)->type->type;
818
819 assert(glsl_type_is_vector_or_scalar(sampled_type));
820
821 enum glsl_sampler_dim dim;
822 switch ((SpvDim)w[3]) {
823 case SpvDim1D: dim = GLSL_SAMPLER_DIM_1D; break;
824 case SpvDim2D: dim = GLSL_SAMPLER_DIM_2D; break;
825 case SpvDim3D: dim = GLSL_SAMPLER_DIM_3D; break;
826 case SpvDimCube: dim = GLSL_SAMPLER_DIM_CUBE; break;
827 case SpvDimRect: dim = GLSL_SAMPLER_DIM_RECT; break;
828 case SpvDimBuffer: dim = GLSL_SAMPLER_DIM_BUF; break;
829 case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
830 default:
831 unreachable("Invalid SPIR-V Sampler dimension");
832 }
833
834 bool is_shadow = w[4];
835 bool is_array = w[5];
836 bool multisampled = w[6];
837 unsigned sampled = w[7];
838 SpvImageFormat format = w[8];
839
840 if (count > 9)
841 val->type->access_qualifier = w[9];
842 else
843 val->type->access_qualifier = SpvAccessQualifierReadWrite;
844
845 if (multisampled) {
846 assert(dim == GLSL_SAMPLER_DIM_2D);
847 dim = GLSL_SAMPLER_DIM_MS;
848 }
849
850 val->type->image_format = translate_image_format(format);
851
852 if (sampled == 1) {
853 val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
854 glsl_get_base_type(sampled_type));
855 } else if (sampled == 2) {
856 assert((dim == GLSL_SAMPLER_DIM_SUBPASS) || format);
857 assert(!is_shadow);
858 val->type->type = glsl_image_type(dim, is_array,
859 glsl_get_base_type(sampled_type));
860 } else {
861 assert(!"We need to know if the image will be sampled");
862 }
863 break;
864 }
865
866 case SpvOpTypeSampledImage:
867 val->type = vtn_value(b, w[2], vtn_value_type_type)->type;
868 break;
869
870 case SpvOpTypeSampler:
871 /* The actual sampler type here doesn't really matter. It gets
872 * thrown away the moment you combine it with an image. What really
873 * matters is that it's a sampler type as opposed to an integer type
874 * so the backend knows what to do.
875 */
876 val->type->type = glsl_bare_sampler_type();
877 break;
878
879 case SpvOpTypeOpaque:
880 case SpvOpTypeEvent:
881 case SpvOpTypeDeviceEvent:
882 case SpvOpTypeReserveId:
883 case SpvOpTypeQueue:
884 case SpvOpTypePipe:
885 default:
886 unreachable("Unhandled opcode");
887 }
888
889 vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
890 }
891
892 static nir_constant *
893 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
894 {
895 nir_constant *c = rzalloc(b, nir_constant);
896
897 switch (glsl_get_base_type(type)) {
898 case GLSL_TYPE_INT:
899 case GLSL_TYPE_UINT:
900 case GLSL_TYPE_BOOL:
901 case GLSL_TYPE_FLOAT:
902 case GLSL_TYPE_DOUBLE:
903 /* Nothing to do here. It's already initialized to zero */
904 break;
905
906 case GLSL_TYPE_ARRAY:
907 assert(glsl_get_length(type) > 0);
908 c->num_elements = glsl_get_length(type);
909 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
910
911 c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
912 for (unsigned i = 1; i < c->num_elements; i++)
913 c->elements[i] = c->elements[0];
914 break;
915
916 case GLSL_TYPE_STRUCT:
917 c->num_elements = glsl_get_length(type);
918 c->elements = ralloc_array(b, nir_constant *, c->num_elements);
919
920 for (unsigned i = 0; i < c->num_elements; i++) {
921 c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
922 }
923 break;
924
925 default:
926 unreachable("Invalid type for null constant");
927 }
928
929 return c;
930 }
931
932 static void
933 spec_constant_deocoration_cb(struct vtn_builder *b, struct vtn_value *v,
934 int member, const struct vtn_decoration *dec,
935 void *data)
936 {
937 assert(member == -1);
938 if (dec->decoration != SpvDecorationSpecId)
939 return;
940
941 uint32_t *const_value = data;
942
943 for (unsigned i = 0; i < b->num_specializations; i++) {
944 if (b->specializations[i].id == dec->literals[0]) {
945 *const_value = b->specializations[i].data;
946 return;
947 }
948 }
949 }
950
951 static uint32_t
952 get_specialization(struct vtn_builder *b, struct vtn_value *val,
953 uint32_t const_value)
954 {
955 vtn_foreach_decoration(b, val, spec_constant_deocoration_cb, &const_value);
956 return const_value;
957 }
958
959 static void
960 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
961 struct vtn_value *val,
962 int member,
963 const struct vtn_decoration *dec,
964 void *data)
965 {
966 assert(member == -1);
967 if (dec->decoration != SpvDecorationBuiltIn ||
968 dec->literals[0] != SpvBuiltInWorkgroupSize)
969 return;
970
971 assert(val->const_type == glsl_vector_type(GLSL_TYPE_UINT, 3));
972
973 b->shader->info->cs.local_size[0] = val->constant->values[0].u32[0];
974 b->shader->info->cs.local_size[1] = val->constant->values[0].u32[1];
975 b->shader->info->cs.local_size[2] = val->constant->values[0].u32[2];
976 }
977
978 static void
979 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
980 const uint32_t *w, unsigned count)
981 {
982 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
983 val->const_type = vtn_value(b, w[1], vtn_value_type_type)->type->type;
984 val->constant = rzalloc(b, nir_constant);
985 switch (opcode) {
986 case SpvOpConstantTrue:
987 assert(val->const_type == glsl_bool_type());
988 val->constant->values[0].u32[0] = NIR_TRUE;
989 break;
990 case SpvOpConstantFalse:
991 assert(val->const_type == glsl_bool_type());
992 val->constant->values[0].u32[0] = NIR_FALSE;
993 break;
994
995 case SpvOpSpecConstantTrue:
996 case SpvOpSpecConstantFalse: {
997 assert(val->const_type == glsl_bool_type());
998 uint32_t int_val =
999 get_specialization(b, val, (opcode == SpvOpSpecConstantTrue));
1000 val->constant->values[0].u32[0] = int_val ? NIR_TRUE : NIR_FALSE;
1001 break;
1002 }
1003
1004 case SpvOpConstant:
1005 assert(glsl_type_is_scalar(val->const_type));
1006 val->constant->values[0].u32[0] = w[3];
1007 break;
1008 case SpvOpSpecConstant:
1009 assert(glsl_type_is_scalar(val->const_type));
1010 val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1011 break;
1012 case SpvOpSpecConstantComposite:
1013 case SpvOpConstantComposite: {
1014 unsigned elem_count = count - 3;
1015 nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1016 for (unsigned i = 0; i < elem_count; i++)
1017 elems[i] = vtn_value(b, w[i + 3], vtn_value_type_constant)->constant;
1018
1019 switch (glsl_get_base_type(val->const_type)) {
1020 case GLSL_TYPE_UINT:
1021 case GLSL_TYPE_INT:
1022 case GLSL_TYPE_FLOAT:
1023 case GLSL_TYPE_BOOL:
1024 if (glsl_type_is_matrix(val->const_type)) {
1025 assert(glsl_get_matrix_columns(val->const_type) == elem_count);
1026 for (unsigned i = 0; i < elem_count; i++)
1027 val->constant->values[i] = elems[i]->values[0];
1028 } else {
1029 assert(glsl_type_is_vector(val->const_type));
1030 assert(glsl_get_vector_elements(val->const_type) == elem_count);
1031 for (unsigned i = 0; i < elem_count; i++)
1032 val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1033 }
1034 ralloc_free(elems);
1035 break;
1036
1037 case GLSL_TYPE_STRUCT:
1038 case GLSL_TYPE_ARRAY:
1039 ralloc_steal(val->constant, elems);
1040 val->constant->num_elements = elem_count;
1041 val->constant->elements = elems;
1042 break;
1043
1044 default:
1045 unreachable("Unsupported type for constants");
1046 }
1047 break;
1048 }
1049
1050 case SpvOpSpecConstantOp: {
1051 SpvOp opcode = get_specialization(b, val, w[3]);
1052 switch (opcode) {
1053 case SpvOpVectorShuffle: {
1054 struct vtn_value *v0 = vtn_value(b, w[4], vtn_value_type_constant);
1055 struct vtn_value *v1 = vtn_value(b, w[5], vtn_value_type_constant);
1056 unsigned len0 = glsl_get_vector_elements(v0->const_type);
1057 unsigned len1 = glsl_get_vector_elements(v1->const_type);
1058
1059 uint32_t u[8];
1060 for (unsigned i = 0; i < len0; i++)
1061 u[i] = v0->constant->values[0].u32[i];
1062 for (unsigned i = 0; i < len1; i++)
1063 u[len0 + i] = v1->constant->values[0].u32[i];
1064
1065 for (unsigned i = 0; i < count - 6; i++) {
1066 uint32_t comp = w[i + 6];
1067 if (comp == (uint32_t)-1) {
1068 val->constant->values[0].u32[i] = 0xdeadbeef;
1069 } else {
1070 val->constant->values[0].u32[i] = u[comp];
1071 }
1072 }
1073 break;
1074 }
1075
1076 case SpvOpCompositeExtract:
1077 case SpvOpCompositeInsert: {
1078 struct vtn_value *comp;
1079 unsigned deref_start;
1080 struct nir_constant **c;
1081 if (opcode == SpvOpCompositeExtract) {
1082 comp = vtn_value(b, w[4], vtn_value_type_constant);
1083 deref_start = 5;
1084 c = &comp->constant;
1085 } else {
1086 comp = vtn_value(b, w[5], vtn_value_type_constant);
1087 deref_start = 6;
1088 val->constant = nir_constant_clone(comp->constant,
1089 (nir_variable *)b);
1090 c = &val->constant;
1091 }
1092
1093 int elem = -1;
1094 int col = 0;
1095 const struct glsl_type *type = comp->const_type;
1096 for (unsigned i = deref_start; i < count; i++) {
1097 switch (glsl_get_base_type(type)) {
1098 case GLSL_TYPE_UINT:
1099 case GLSL_TYPE_INT:
1100 case GLSL_TYPE_FLOAT:
1101 case GLSL_TYPE_BOOL:
1102 /* If we hit this granularity, we're picking off an element */
1103 if (glsl_type_is_matrix(type)) {
1104 assert(col == 0 && elem == -1);
1105 col = w[i];
1106 elem = 0;
1107 type = glsl_get_column_type(type);
1108 } else {
1109 assert(elem <= 0 && glsl_type_is_vector(type));
1110 elem = w[i];
1111 type = glsl_scalar_type(glsl_get_base_type(type));
1112 }
1113 continue;
1114
1115 case GLSL_TYPE_ARRAY:
1116 c = &(*c)->elements[w[i]];
1117 type = glsl_get_array_element(type);
1118 continue;
1119
1120 case GLSL_TYPE_STRUCT:
1121 c = &(*c)->elements[w[i]];
1122 type = glsl_get_struct_field(type, w[i]);
1123 continue;
1124
1125 default:
1126 unreachable("Invalid constant type");
1127 }
1128 }
1129
1130 if (opcode == SpvOpCompositeExtract) {
1131 if (elem == -1) {
1132 val->constant = *c;
1133 } else {
1134 unsigned num_components = glsl_get_vector_elements(type);
1135 for (unsigned i = 0; i < num_components; i++)
1136 val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1137 }
1138 } else {
1139 struct vtn_value *insert =
1140 vtn_value(b, w[4], vtn_value_type_constant);
1141 assert(insert->const_type == type);
1142 if (elem == -1) {
1143 *c = insert->constant;
1144 } else {
1145 unsigned num_components = glsl_get_vector_elements(type);
1146 for (unsigned i = 0; i < num_components; i++)
1147 (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1148 }
1149 }
1150 break;
1151 }
1152
1153 default: {
1154 bool swap;
1155 nir_op op = vtn_nir_alu_op_for_spirv_opcode(opcode, &swap);
1156
1157 unsigned num_components = glsl_get_vector_elements(val->const_type);
1158 unsigned bit_size =
1159 glsl_get_bit_size(val->const_type);
1160
1161 nir_const_value src[4];
1162 assert(count <= 7);
1163 for (unsigned i = 0; i < count - 4; i++) {
1164 nir_constant *c =
1165 vtn_value(b, w[4 + i], vtn_value_type_constant)->constant;
1166
1167 unsigned j = swap ? 1 - i : i;
1168 assert(bit_size == 32);
1169 src[j] = c->values[0];
1170 }
1171
1172 val->constant->values[0] =
1173 nir_eval_const_opcode(op, num_components, bit_size, src);
1174 break;
1175 } /* default */
1176 }
1177 break;
1178 }
1179
1180 case SpvOpConstantNull:
1181 val->constant = vtn_null_constant(b, val->const_type);
1182 break;
1183
1184 case SpvOpConstantSampler:
1185 assert(!"OpConstantSampler requires Kernel Capability");
1186 break;
1187
1188 default:
1189 unreachable("Unhandled opcode");
1190 }
1191
1192 /* Now that we have the value, update the workgroup size if needed */
1193 vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1194 }
1195
1196 static void
1197 vtn_handle_function_call(struct vtn_builder *b, SpvOp opcode,
1198 const uint32_t *w, unsigned count)
1199 {
1200 struct nir_function *callee =
1201 vtn_value(b, w[3], vtn_value_type_function)->func->impl->function;
1202
1203 nir_call_instr *call = nir_call_instr_create(b->nb.shader, callee);
1204 for (unsigned i = 0; i < call->num_params; i++) {
1205 unsigned arg_id = w[4 + i];
1206 struct vtn_value *arg = vtn_untyped_value(b, arg_id);
1207 if (arg->value_type == vtn_value_type_access_chain) {
1208 nir_deref_var *d = vtn_access_chain_to_deref(b, arg->access_chain);
1209 call->params[i] = nir_deref_var_clone(d, call);
1210 } else {
1211 struct vtn_ssa_value *arg_ssa = vtn_ssa_value(b, arg_id);
1212
1213 /* Make a temporary to store the argument in */
1214 nir_variable *tmp =
1215 nir_local_variable_create(b->impl, arg_ssa->type, "arg_tmp");
1216 call->params[i] = nir_deref_var_create(call, tmp);
1217
1218 vtn_local_store(b, arg_ssa, call->params[i]);
1219 }
1220 }
1221
1222 nir_variable *out_tmp = NULL;
1223 if (!glsl_type_is_void(callee->return_type)) {
1224 out_tmp = nir_local_variable_create(b->impl, callee->return_type,
1225 "out_tmp");
1226 call->return_deref = nir_deref_var_create(call, out_tmp);
1227 }
1228
1229 nir_builder_instr_insert(&b->nb, &call->instr);
1230
1231 if (glsl_type_is_void(callee->return_type)) {
1232 vtn_push_value(b, w[2], vtn_value_type_undef);
1233 } else {
1234 struct vtn_value *retval = vtn_push_value(b, w[2], vtn_value_type_ssa);
1235 retval->ssa = vtn_local_load(b, call->return_deref);
1236 }
1237 }
1238
1239 struct vtn_ssa_value *
1240 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1241 {
1242 struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1243 val->type = type;
1244
1245 if (!glsl_type_is_vector_or_scalar(type)) {
1246 unsigned elems = glsl_get_length(type);
1247 val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1248 for (unsigned i = 0; i < elems; i++) {
1249 const struct glsl_type *child_type;
1250
1251 switch (glsl_get_base_type(type)) {
1252 case GLSL_TYPE_INT:
1253 case GLSL_TYPE_UINT:
1254 case GLSL_TYPE_BOOL:
1255 case GLSL_TYPE_FLOAT:
1256 case GLSL_TYPE_DOUBLE:
1257 child_type = glsl_get_column_type(type);
1258 break;
1259 case GLSL_TYPE_ARRAY:
1260 child_type = glsl_get_array_element(type);
1261 break;
1262 case GLSL_TYPE_STRUCT:
1263 child_type = glsl_get_struct_field(type, i);
1264 break;
1265 default:
1266 unreachable("unkown base type");
1267 }
1268
1269 val->elems[i] = vtn_create_ssa_value(b, child_type);
1270 }
1271 }
1272
1273 return val;
1274 }
1275
1276 static nir_tex_src
1277 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1278 {
1279 nir_tex_src src;
1280 src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
1281 src.src_type = type;
1282 return src;
1283 }
1284
1285 static void
1286 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
1287 const uint32_t *w, unsigned count)
1288 {
1289 if (opcode == SpvOpSampledImage) {
1290 struct vtn_value *val =
1291 vtn_push_value(b, w[2], vtn_value_type_sampled_image);
1292 val->sampled_image = ralloc(b, struct vtn_sampled_image);
1293 val->sampled_image->image =
1294 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
1295 val->sampled_image->sampler =
1296 vtn_value(b, w[4], vtn_value_type_access_chain)->access_chain;
1297 return;
1298 } else if (opcode == SpvOpImage) {
1299 struct vtn_value *val =
1300 vtn_push_value(b, w[2], vtn_value_type_access_chain);
1301 struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
1302 if (src_val->value_type == vtn_value_type_sampled_image) {
1303 val->access_chain = src_val->sampled_image->image;
1304 } else {
1305 assert(src_val->value_type == vtn_value_type_access_chain);
1306 val->access_chain = src_val->access_chain;
1307 }
1308 return;
1309 }
1310
1311 struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1312 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1313
1314 struct vtn_sampled_image sampled;
1315 struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
1316 if (sampled_val->value_type == vtn_value_type_sampled_image) {
1317 sampled = *sampled_val->sampled_image;
1318 } else {
1319 assert(sampled_val->value_type == vtn_value_type_access_chain);
1320 sampled.image = NULL;
1321 sampled.sampler = sampled_val->access_chain;
1322 }
1323
1324 const struct glsl_type *image_type;
1325 if (sampled.image) {
1326 image_type = sampled.image->var->var->interface_type;
1327 } else {
1328 image_type = sampled.sampler->var->var->interface_type;
1329 }
1330 const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
1331 const bool is_array = glsl_sampler_type_is_array(image_type);
1332 const bool is_shadow = glsl_sampler_type_is_shadow(image_type);
1333
1334 /* Figure out the base texture operation */
1335 nir_texop texop;
1336 switch (opcode) {
1337 case SpvOpImageSampleImplicitLod:
1338 case SpvOpImageSampleDrefImplicitLod:
1339 case SpvOpImageSampleProjImplicitLod:
1340 case SpvOpImageSampleProjDrefImplicitLod:
1341 texop = nir_texop_tex;
1342 break;
1343
1344 case SpvOpImageSampleExplicitLod:
1345 case SpvOpImageSampleDrefExplicitLod:
1346 case SpvOpImageSampleProjExplicitLod:
1347 case SpvOpImageSampleProjDrefExplicitLod:
1348 texop = nir_texop_txl;
1349 break;
1350
1351 case SpvOpImageFetch:
1352 if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
1353 texop = nir_texop_txf_ms;
1354 } else {
1355 texop = nir_texop_txf;
1356 }
1357 break;
1358
1359 case SpvOpImageGather:
1360 case SpvOpImageDrefGather:
1361 texop = nir_texop_tg4;
1362 break;
1363
1364 case SpvOpImageQuerySizeLod:
1365 case SpvOpImageQuerySize:
1366 texop = nir_texop_txs;
1367 break;
1368
1369 case SpvOpImageQueryLod:
1370 texop = nir_texop_lod;
1371 break;
1372
1373 case SpvOpImageQueryLevels:
1374 texop = nir_texop_query_levels;
1375 break;
1376
1377 case SpvOpImageQuerySamples:
1378 texop = nir_texop_texture_samples;
1379 break;
1380
1381 default:
1382 unreachable("Unhandled opcode");
1383 }
1384
1385 nir_tex_src srcs[8]; /* 8 should be enough */
1386 nir_tex_src *p = srcs;
1387
1388 unsigned idx = 4;
1389
1390 struct nir_ssa_def *coord;
1391 unsigned coord_components;
1392 switch (opcode) {
1393 case SpvOpImageSampleImplicitLod:
1394 case SpvOpImageSampleExplicitLod:
1395 case SpvOpImageSampleDrefImplicitLod:
1396 case SpvOpImageSampleDrefExplicitLod:
1397 case SpvOpImageSampleProjImplicitLod:
1398 case SpvOpImageSampleProjExplicitLod:
1399 case SpvOpImageSampleProjDrefImplicitLod:
1400 case SpvOpImageSampleProjDrefExplicitLod:
1401 case SpvOpImageFetch:
1402 case SpvOpImageGather:
1403 case SpvOpImageDrefGather:
1404 case SpvOpImageQueryLod: {
1405 /* All these types have the coordinate as their first real argument */
1406 switch (sampler_dim) {
1407 case GLSL_SAMPLER_DIM_1D:
1408 case GLSL_SAMPLER_DIM_BUF:
1409 coord_components = 1;
1410 break;
1411 case GLSL_SAMPLER_DIM_2D:
1412 case GLSL_SAMPLER_DIM_RECT:
1413 case GLSL_SAMPLER_DIM_MS:
1414 coord_components = 2;
1415 break;
1416 case GLSL_SAMPLER_DIM_3D:
1417 case GLSL_SAMPLER_DIM_CUBE:
1418 coord_components = 3;
1419 break;
1420 default:
1421 unreachable("Invalid sampler type");
1422 }
1423
1424 if (is_array && texop != nir_texop_lod)
1425 coord_components++;
1426
1427 coord = vtn_ssa_value(b, w[idx++])->def;
1428 p->src = nir_src_for_ssa(coord);
1429 p->src_type = nir_tex_src_coord;
1430 p++;
1431 break;
1432 }
1433
1434 default:
1435 coord = NULL;
1436 coord_components = 0;
1437 break;
1438 }
1439
1440 switch (opcode) {
1441 case SpvOpImageSampleProjImplicitLod:
1442 case SpvOpImageSampleProjExplicitLod:
1443 case SpvOpImageSampleProjDrefImplicitLod:
1444 case SpvOpImageSampleProjDrefExplicitLod:
1445 /* These have the projector as the last coordinate component */
1446 p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
1447 p->src_type = nir_tex_src_projector;
1448 p++;
1449 break;
1450
1451 default:
1452 break;
1453 }
1454
1455 unsigned gather_component = 0;
1456 switch (opcode) {
1457 case SpvOpImageSampleDrefImplicitLod:
1458 case SpvOpImageSampleDrefExplicitLod:
1459 case SpvOpImageSampleProjDrefImplicitLod:
1460 case SpvOpImageSampleProjDrefExplicitLod:
1461 case SpvOpImageDrefGather:
1462 /* These all have an explicit depth value as their next source */
1463 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
1464 break;
1465
1466 case SpvOpImageGather:
1467 /* This has a component as its next source */
1468 gather_component =
1469 vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
1470 break;
1471
1472 default:
1473 break;
1474 }
1475
1476 /* For OpImageQuerySizeLod, we always have an LOD */
1477 if (opcode == SpvOpImageQuerySizeLod)
1478 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
1479
1480 /* Now we need to handle some number of optional arguments */
1481 const struct vtn_ssa_value *gather_offsets = NULL;
1482 if (idx < count) {
1483 uint32_t operands = w[idx++];
1484
1485 if (operands & SpvImageOperandsBiasMask) {
1486 assert(texop == nir_texop_tex);
1487 texop = nir_texop_txb;
1488 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
1489 }
1490
1491 if (operands & SpvImageOperandsLodMask) {
1492 assert(texop == nir_texop_txl || texop == nir_texop_txf ||
1493 texop == nir_texop_txs);
1494 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
1495 }
1496
1497 if (operands & SpvImageOperandsGradMask) {
1498 assert(texop == nir_texop_txl);
1499 texop = nir_texop_txd;
1500 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
1501 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
1502 }
1503
1504 if (operands & SpvImageOperandsOffsetMask ||
1505 operands & SpvImageOperandsConstOffsetMask)
1506 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
1507
1508 if (operands & SpvImageOperandsConstOffsetsMask) {
1509 gather_offsets = vtn_ssa_value(b, w[idx++]);
1510 (*p++) = (nir_tex_src){};
1511 }
1512
1513 if (operands & SpvImageOperandsSampleMask) {
1514 assert(texop == nir_texop_txf_ms);
1515 texop = nir_texop_txf_ms;
1516 (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
1517 }
1518 }
1519 /* We should have now consumed exactly all of the arguments */
1520 assert(idx == count);
1521
1522 nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
1523 instr->op = texop;
1524
1525 memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
1526
1527 instr->coord_components = coord_components;
1528 instr->sampler_dim = sampler_dim;
1529 instr->is_array = is_array;
1530 instr->is_shadow = is_shadow;
1531 instr->is_new_style_shadow =
1532 is_shadow && glsl_get_components(ret_type->type) == 1;
1533 instr->component = gather_component;
1534
1535 switch (glsl_get_sampler_result_type(image_type)) {
1536 case GLSL_TYPE_FLOAT: instr->dest_type = nir_type_float; break;
1537 case GLSL_TYPE_INT: instr->dest_type = nir_type_int; break;
1538 case GLSL_TYPE_UINT: instr->dest_type = nir_type_uint; break;
1539 case GLSL_TYPE_BOOL: instr->dest_type = nir_type_bool; break;
1540 default:
1541 unreachable("Invalid base type for sampler result");
1542 }
1543
1544 nir_deref_var *sampler = vtn_access_chain_to_deref(b, sampled.sampler);
1545 nir_deref_var *texture;
1546 if (sampled.image) {
1547 nir_deref_var *image = vtn_access_chain_to_deref(b, sampled.image);
1548 texture = image;
1549 } else {
1550 texture = sampler;
1551 }
1552
1553 instr->texture = nir_deref_var_clone(texture, instr);
1554
1555 switch (instr->op) {
1556 case nir_texop_tex:
1557 case nir_texop_txb:
1558 case nir_texop_txl:
1559 case nir_texop_txd:
1560 /* These operations require a sampler */
1561 instr->sampler = nir_deref_var_clone(sampler, instr);
1562 break;
1563 case nir_texop_txf:
1564 case nir_texop_txf_ms:
1565 case nir_texop_txs:
1566 case nir_texop_lod:
1567 case nir_texop_tg4:
1568 case nir_texop_query_levels:
1569 case nir_texop_texture_samples:
1570 case nir_texop_samples_identical:
1571 /* These don't */
1572 instr->sampler = NULL;
1573 break;
1574 case nir_texop_txf_ms_mcs:
1575 unreachable("unexpected nir_texop_txf_ms_mcs");
1576 }
1577
1578 nir_ssa_dest_init(&instr->instr, &instr->dest,
1579 nir_tex_instr_dest_size(instr), 32, NULL);
1580
1581 assert(glsl_get_vector_elements(ret_type->type) ==
1582 nir_tex_instr_dest_size(instr));
1583
1584 nir_ssa_def *def;
1585 nir_instr *instruction;
1586 if (gather_offsets) {
1587 assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
1588 assert(glsl_get_length(gather_offsets->type) == 4);
1589 nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
1590
1591 /* Copy the current instruction 4x */
1592 for (uint32_t i = 1; i < 4; i++) {
1593 instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
1594 instrs[i]->op = instr->op;
1595 instrs[i]->coord_components = instr->coord_components;
1596 instrs[i]->sampler_dim = instr->sampler_dim;
1597 instrs[i]->is_array = instr->is_array;
1598 instrs[i]->is_shadow = instr->is_shadow;
1599 instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
1600 instrs[i]->component = instr->component;
1601 instrs[i]->dest_type = instr->dest_type;
1602 instrs[i]->texture = nir_deref_var_clone(texture, instrs[i]);
1603 instrs[i]->sampler = NULL;
1604
1605 memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
1606
1607 nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
1608 nir_tex_instr_dest_size(instr), 32, NULL);
1609 }
1610
1611 /* Fill in the last argument with the offset from the passed in offsets
1612 * and insert the instruction into the stream.
1613 */
1614 for (uint32_t i = 0; i < 4; i++) {
1615 nir_tex_src src;
1616 src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
1617 src.src_type = nir_tex_src_offset;
1618 instrs[i]->src[instrs[i]->num_srcs - 1] = src;
1619 nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
1620 }
1621
1622 /* Combine the results of the 4 instructions by taking their .w
1623 * components
1624 */
1625 nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
1626 nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
1627 vec4->dest.write_mask = 0xf;
1628 for (uint32_t i = 0; i < 4; i++) {
1629 vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
1630 vec4->src[i].swizzle[0] = 3;
1631 }
1632 def = &vec4->dest.dest.ssa;
1633 instruction = &vec4->instr;
1634 } else {
1635 def = &instr->dest.ssa;
1636 instruction = &instr->instr;
1637 }
1638
1639 val->ssa = vtn_create_ssa_value(b, ret_type->type);
1640 val->ssa->def = def;
1641
1642 nir_builder_instr_insert(&b->nb, instruction);
1643 }
1644
1645 static void
1646 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
1647 const uint32_t *w, nir_src *src)
1648 {
1649 switch (opcode) {
1650 case SpvOpAtomicIIncrement:
1651 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
1652 break;
1653
1654 case SpvOpAtomicIDecrement:
1655 src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
1656 break;
1657
1658 case SpvOpAtomicISub:
1659 src[0] =
1660 nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
1661 break;
1662
1663 case SpvOpAtomicCompareExchange:
1664 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
1665 src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
1666 break;
1667
1668 case SpvOpAtomicExchange:
1669 case SpvOpAtomicIAdd:
1670 case SpvOpAtomicSMin:
1671 case SpvOpAtomicUMin:
1672 case SpvOpAtomicSMax:
1673 case SpvOpAtomicUMax:
1674 case SpvOpAtomicAnd:
1675 case SpvOpAtomicOr:
1676 case SpvOpAtomicXor:
1677 src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
1678 break;
1679
1680 default:
1681 unreachable("Invalid SPIR-V atomic");
1682 }
1683 }
1684
1685 static nir_ssa_def *
1686 get_image_coord(struct vtn_builder *b, uint32_t value)
1687 {
1688 struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
1689
1690 /* The image_load_store intrinsics assume a 4-dim coordinate */
1691 unsigned dim = glsl_get_vector_elements(coord->type);
1692 unsigned swizzle[4];
1693 for (unsigned i = 0; i < 4; i++)
1694 swizzle[i] = MIN2(i, dim - 1);
1695
1696 return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
1697 }
1698
1699 static void
1700 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
1701 const uint32_t *w, unsigned count)
1702 {
1703 /* Just get this one out of the way */
1704 if (opcode == SpvOpImageTexelPointer) {
1705 struct vtn_value *val =
1706 vtn_push_value(b, w[2], vtn_value_type_image_pointer);
1707 val->image = ralloc(b, struct vtn_image_pointer);
1708
1709 val->image->image =
1710 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
1711 val->image->coord = get_image_coord(b, w[4]);
1712 val->image->sample = vtn_ssa_value(b, w[5])->def;
1713 return;
1714 }
1715
1716 struct vtn_image_pointer image;
1717
1718 switch (opcode) {
1719 case SpvOpAtomicExchange:
1720 case SpvOpAtomicCompareExchange:
1721 case SpvOpAtomicCompareExchangeWeak:
1722 case SpvOpAtomicIIncrement:
1723 case SpvOpAtomicIDecrement:
1724 case SpvOpAtomicIAdd:
1725 case SpvOpAtomicISub:
1726 case SpvOpAtomicLoad:
1727 case SpvOpAtomicSMin:
1728 case SpvOpAtomicUMin:
1729 case SpvOpAtomicSMax:
1730 case SpvOpAtomicUMax:
1731 case SpvOpAtomicAnd:
1732 case SpvOpAtomicOr:
1733 case SpvOpAtomicXor:
1734 image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
1735 break;
1736
1737 case SpvOpAtomicStore:
1738 image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
1739 break;
1740
1741 case SpvOpImageQuerySize:
1742 image.image =
1743 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
1744 image.coord = NULL;
1745 image.sample = NULL;
1746 break;
1747
1748 case SpvOpImageRead:
1749 image.image =
1750 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
1751 image.coord = get_image_coord(b, w[4]);
1752
1753 if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
1754 assert(w[5] == SpvImageOperandsSampleMask);
1755 image.sample = vtn_ssa_value(b, w[6])->def;
1756 } else {
1757 image.sample = nir_ssa_undef(&b->nb, 1, 32);
1758 }
1759 break;
1760
1761 case SpvOpImageWrite:
1762 image.image =
1763 vtn_value(b, w[1], vtn_value_type_access_chain)->access_chain;
1764 image.coord = get_image_coord(b, w[2]);
1765
1766 /* texel = w[3] */
1767
1768 if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
1769 assert(w[4] == SpvImageOperandsSampleMask);
1770 image.sample = vtn_ssa_value(b, w[5])->def;
1771 } else {
1772 image.sample = nir_ssa_undef(&b->nb, 1, 32);
1773 }
1774 break;
1775
1776 default:
1777 unreachable("Invalid image opcode");
1778 }
1779
1780 nir_intrinsic_op op;
1781 switch (opcode) {
1782 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_##N; break;
1783 OP(ImageQuerySize, size)
1784 OP(ImageRead, load)
1785 OP(ImageWrite, store)
1786 OP(AtomicLoad, load)
1787 OP(AtomicStore, store)
1788 OP(AtomicExchange, atomic_exchange)
1789 OP(AtomicCompareExchange, atomic_comp_swap)
1790 OP(AtomicIIncrement, atomic_add)
1791 OP(AtomicIDecrement, atomic_add)
1792 OP(AtomicIAdd, atomic_add)
1793 OP(AtomicISub, atomic_add)
1794 OP(AtomicSMin, atomic_min)
1795 OP(AtomicUMin, atomic_min)
1796 OP(AtomicSMax, atomic_max)
1797 OP(AtomicUMax, atomic_max)
1798 OP(AtomicAnd, atomic_and)
1799 OP(AtomicOr, atomic_or)
1800 OP(AtomicXor, atomic_xor)
1801 #undef OP
1802 default:
1803 unreachable("Invalid image opcode");
1804 }
1805
1806 nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
1807
1808 nir_deref_var *image_deref = vtn_access_chain_to_deref(b, image.image);
1809 intrin->variables[0] = nir_deref_var_clone(image_deref, intrin);
1810
1811 /* ImageQuerySize doesn't take any extra parameters */
1812 if (opcode != SpvOpImageQuerySize) {
1813 /* The image coordinate is always 4 components but we may not have that
1814 * many. Swizzle to compensate.
1815 */
1816 unsigned swiz[4];
1817 for (unsigned i = 0; i < 4; i++)
1818 swiz[i] = i < image.coord->num_components ? i : 0;
1819 intrin->src[0] = nir_src_for_ssa(nir_swizzle(&b->nb, image.coord,
1820 swiz, 4, false));
1821 intrin->src[1] = nir_src_for_ssa(image.sample);
1822 }
1823
1824 switch (opcode) {
1825 case SpvOpAtomicLoad:
1826 case SpvOpImageQuerySize:
1827 case SpvOpImageRead:
1828 break;
1829 case SpvOpAtomicStore:
1830 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
1831 break;
1832 case SpvOpImageWrite:
1833 intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[3])->def);
1834 break;
1835
1836 case SpvOpAtomicIIncrement:
1837 case SpvOpAtomicIDecrement:
1838 case SpvOpAtomicExchange:
1839 case SpvOpAtomicIAdd:
1840 case SpvOpAtomicSMin:
1841 case SpvOpAtomicUMin:
1842 case SpvOpAtomicSMax:
1843 case SpvOpAtomicUMax:
1844 case SpvOpAtomicAnd:
1845 case SpvOpAtomicOr:
1846 case SpvOpAtomicXor:
1847 fill_common_atomic_sources(b, opcode, w, &intrin->src[2]);
1848 break;
1849
1850 default:
1851 unreachable("Invalid image opcode");
1852 }
1853
1854 if (opcode != SpvOpImageWrite) {
1855 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1856 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
1857 nir_ssa_dest_init(&intrin->instr, &intrin->dest, 4, 32, NULL);
1858
1859 nir_builder_instr_insert(&b->nb, &intrin->instr);
1860
1861 /* The image intrinsics always return 4 channels but we may not want
1862 * that many. Emit a mov to trim it down.
1863 */
1864 unsigned swiz[4] = {0, 1, 2, 3};
1865 val->ssa = vtn_create_ssa_value(b, type->type);
1866 val->ssa->def = nir_swizzle(&b->nb, &intrin->dest.ssa, swiz,
1867 glsl_get_vector_elements(type->type), false);
1868 } else {
1869 nir_builder_instr_insert(&b->nb, &intrin->instr);
1870 }
1871 }
1872
1873 static nir_intrinsic_op
1874 get_ssbo_nir_atomic_op(SpvOp opcode)
1875 {
1876 switch (opcode) {
1877 case SpvOpAtomicLoad: return nir_intrinsic_load_ssbo;
1878 case SpvOpAtomicStore: return nir_intrinsic_store_ssbo;
1879 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
1880 OP(AtomicExchange, atomic_exchange)
1881 OP(AtomicCompareExchange, atomic_comp_swap)
1882 OP(AtomicIIncrement, atomic_add)
1883 OP(AtomicIDecrement, atomic_add)
1884 OP(AtomicIAdd, atomic_add)
1885 OP(AtomicISub, atomic_add)
1886 OP(AtomicSMin, atomic_imin)
1887 OP(AtomicUMin, atomic_umin)
1888 OP(AtomicSMax, atomic_imax)
1889 OP(AtomicUMax, atomic_umax)
1890 OP(AtomicAnd, atomic_and)
1891 OP(AtomicOr, atomic_or)
1892 OP(AtomicXor, atomic_xor)
1893 #undef OP
1894 default:
1895 unreachable("Invalid SSBO atomic");
1896 }
1897 }
1898
1899 static nir_intrinsic_op
1900 get_shared_nir_atomic_op(SpvOp opcode)
1901 {
1902 switch (opcode) {
1903 case SpvOpAtomicLoad: return nir_intrinsic_load_var;
1904 case SpvOpAtomicStore: return nir_intrinsic_store_var;
1905 #define OP(S, N) case SpvOp##S: return nir_intrinsic_var_##N;
1906 OP(AtomicExchange, atomic_exchange)
1907 OP(AtomicCompareExchange, atomic_comp_swap)
1908 OP(AtomicIIncrement, atomic_add)
1909 OP(AtomicIDecrement, atomic_add)
1910 OP(AtomicIAdd, atomic_add)
1911 OP(AtomicISub, atomic_add)
1912 OP(AtomicSMin, atomic_imin)
1913 OP(AtomicUMin, atomic_umin)
1914 OP(AtomicSMax, atomic_imax)
1915 OP(AtomicUMax, atomic_umax)
1916 OP(AtomicAnd, atomic_and)
1917 OP(AtomicOr, atomic_or)
1918 OP(AtomicXor, atomic_xor)
1919 #undef OP
1920 default:
1921 unreachable("Invalid shared atomic");
1922 }
1923 }
1924
1925 static void
1926 vtn_handle_ssbo_or_shared_atomic(struct vtn_builder *b, SpvOp opcode,
1927 const uint32_t *w, unsigned count)
1928 {
1929 struct vtn_access_chain *chain;
1930 nir_intrinsic_instr *atomic;
1931
1932 switch (opcode) {
1933 case SpvOpAtomicLoad:
1934 case SpvOpAtomicExchange:
1935 case SpvOpAtomicCompareExchange:
1936 case SpvOpAtomicCompareExchangeWeak:
1937 case SpvOpAtomicIIncrement:
1938 case SpvOpAtomicIDecrement:
1939 case SpvOpAtomicIAdd:
1940 case SpvOpAtomicISub:
1941 case SpvOpAtomicSMin:
1942 case SpvOpAtomicUMin:
1943 case SpvOpAtomicSMax:
1944 case SpvOpAtomicUMax:
1945 case SpvOpAtomicAnd:
1946 case SpvOpAtomicOr:
1947 case SpvOpAtomicXor:
1948 chain =
1949 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
1950 break;
1951
1952 case SpvOpAtomicStore:
1953 chain =
1954 vtn_value(b, w[1], vtn_value_type_access_chain)->access_chain;
1955 break;
1956
1957 default:
1958 unreachable("Invalid SPIR-V atomic");
1959 }
1960
1961 /*
1962 SpvScope scope = w[4];
1963 SpvMemorySemanticsMask semantics = w[5];
1964 */
1965
1966 if (chain->var->mode == vtn_variable_mode_workgroup) {
1967 struct vtn_type *type = chain->var->type;
1968 nir_deref_var *deref = vtn_access_chain_to_deref(b, chain);
1969 nir_intrinsic_op op = get_shared_nir_atomic_op(opcode);
1970 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
1971 atomic->variables[0] = nir_deref_var_clone(deref, atomic);
1972
1973 switch (opcode) {
1974 case SpvOpAtomicLoad:
1975 atomic->num_components = glsl_get_vector_elements(type->type);
1976 break;
1977
1978 case SpvOpAtomicStore:
1979 atomic->num_components = glsl_get_vector_elements(type->type);
1980 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
1981 atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
1982 break;
1983
1984 case SpvOpAtomicExchange:
1985 case SpvOpAtomicCompareExchange:
1986 case SpvOpAtomicCompareExchangeWeak:
1987 case SpvOpAtomicIIncrement:
1988 case SpvOpAtomicIDecrement:
1989 case SpvOpAtomicIAdd:
1990 case SpvOpAtomicISub:
1991 case SpvOpAtomicSMin:
1992 case SpvOpAtomicUMin:
1993 case SpvOpAtomicSMax:
1994 case SpvOpAtomicUMax:
1995 case SpvOpAtomicAnd:
1996 case SpvOpAtomicOr:
1997 case SpvOpAtomicXor:
1998 fill_common_atomic_sources(b, opcode, w, &atomic->src[0]);
1999 break;
2000
2001 default:
2002 unreachable("Invalid SPIR-V atomic");
2003
2004 }
2005 } else {
2006 assert(chain->var->mode == vtn_variable_mode_ssbo);
2007 struct vtn_type *type;
2008 nir_ssa_def *offset, *index;
2009 offset = vtn_access_chain_to_offset(b, chain, &index, &type, NULL, false);
2010
2011 nir_intrinsic_op op = get_ssbo_nir_atomic_op(opcode);
2012
2013 atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2014
2015 switch (opcode) {
2016 case SpvOpAtomicLoad:
2017 atomic->num_components = glsl_get_vector_elements(type->type);
2018 atomic->src[0] = nir_src_for_ssa(index);
2019 atomic->src[1] = nir_src_for_ssa(offset);
2020 break;
2021
2022 case SpvOpAtomicStore:
2023 atomic->num_components = glsl_get_vector_elements(type->type);
2024 nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2025 atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2026 atomic->src[1] = nir_src_for_ssa(index);
2027 atomic->src[2] = nir_src_for_ssa(offset);
2028 break;
2029
2030 case SpvOpAtomicExchange:
2031 case SpvOpAtomicCompareExchange:
2032 case SpvOpAtomicCompareExchangeWeak:
2033 case SpvOpAtomicIIncrement:
2034 case SpvOpAtomicIDecrement:
2035 case SpvOpAtomicIAdd:
2036 case SpvOpAtomicISub:
2037 case SpvOpAtomicSMin:
2038 case SpvOpAtomicUMin:
2039 case SpvOpAtomicSMax:
2040 case SpvOpAtomicUMax:
2041 case SpvOpAtomicAnd:
2042 case SpvOpAtomicOr:
2043 case SpvOpAtomicXor:
2044 atomic->src[0] = nir_src_for_ssa(index);
2045 atomic->src[1] = nir_src_for_ssa(offset);
2046 fill_common_atomic_sources(b, opcode, w, &atomic->src[2]);
2047 break;
2048
2049 default:
2050 unreachable("Invalid SPIR-V atomic");
2051 }
2052 }
2053
2054 if (opcode != SpvOpAtomicStore) {
2055 struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2056
2057 nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2058 glsl_get_vector_elements(type->type),
2059 glsl_get_bit_size(type->type), NULL);
2060
2061 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2062 val->ssa = rzalloc(b, struct vtn_ssa_value);
2063 val->ssa->def = &atomic->dest.ssa;
2064 val->ssa->type = type->type;
2065 }
2066
2067 nir_builder_instr_insert(&b->nb, &atomic->instr);
2068 }
2069
2070 static nir_alu_instr *
2071 create_vec(nir_shader *shader, unsigned num_components, unsigned bit_size)
2072 {
2073 nir_op op;
2074 switch (num_components) {
2075 case 1: op = nir_op_fmov; break;
2076 case 2: op = nir_op_vec2; break;
2077 case 3: op = nir_op_vec3; break;
2078 case 4: op = nir_op_vec4; break;
2079 default: unreachable("bad vector size");
2080 }
2081
2082 nir_alu_instr *vec = nir_alu_instr_create(shader, op);
2083 nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2084 bit_size, NULL);
2085 vec->dest.write_mask = (1 << num_components) - 1;
2086
2087 return vec;
2088 }
2089
2090 struct vtn_ssa_value *
2091 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2092 {
2093 if (src->transposed)
2094 return src->transposed;
2095
2096 struct vtn_ssa_value *dest =
2097 vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2098
2099 for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2100 nir_alu_instr *vec = create_vec(b->shader,
2101 glsl_get_matrix_columns(src->type),
2102 glsl_get_bit_size(src->type));
2103 if (glsl_type_is_vector_or_scalar(src->type)) {
2104 vec->src[0].src = nir_src_for_ssa(src->def);
2105 vec->src[0].swizzle[0] = i;
2106 } else {
2107 for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2108 vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2109 vec->src[j].swizzle[0] = i;
2110 }
2111 }
2112 nir_builder_instr_insert(&b->nb, &vec->instr);
2113 dest->elems[i]->def = &vec->dest.dest.ssa;
2114 }
2115
2116 dest->transposed = src;
2117
2118 return dest;
2119 }
2120
2121 nir_ssa_def *
2122 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2123 {
2124 unsigned swiz[4] = { index };
2125 return nir_swizzle(&b->nb, src, swiz, 1, true);
2126 }
2127
2128 nir_ssa_def *
2129 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2130 unsigned index)
2131 {
2132 nir_alu_instr *vec = create_vec(b->shader, src->num_components,
2133 src->bit_size);
2134
2135 for (unsigned i = 0; i < src->num_components; i++) {
2136 if (i == index) {
2137 vec->src[i].src = nir_src_for_ssa(insert);
2138 } else {
2139 vec->src[i].src = nir_src_for_ssa(src);
2140 vec->src[i].swizzle[0] = i;
2141 }
2142 }
2143
2144 nir_builder_instr_insert(&b->nb, &vec->instr);
2145
2146 return &vec->dest.dest.ssa;
2147 }
2148
2149 nir_ssa_def *
2150 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2151 nir_ssa_def *index)
2152 {
2153 nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
2154 for (unsigned i = 1; i < src->num_components; i++)
2155 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2156 vtn_vector_extract(b, src, i), dest);
2157
2158 return dest;
2159 }
2160
2161 nir_ssa_def *
2162 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2163 nir_ssa_def *insert, nir_ssa_def *index)
2164 {
2165 nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
2166 for (unsigned i = 1; i < src->num_components; i++)
2167 dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2168 vtn_vector_insert(b, src, insert, i), dest);
2169
2170 return dest;
2171 }
2172
2173 static nir_ssa_def *
2174 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
2175 nir_ssa_def *src0, nir_ssa_def *src1,
2176 const uint32_t *indices)
2177 {
2178 nir_alu_instr *vec = create_vec(b->shader, num_components, src0->bit_size);
2179
2180 for (unsigned i = 0; i < num_components; i++) {
2181 uint32_t index = indices[i];
2182 if (index == 0xffffffff) {
2183 vec->src[i].src =
2184 nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
2185 } else if (index < src0->num_components) {
2186 vec->src[i].src = nir_src_for_ssa(src0);
2187 vec->src[i].swizzle[0] = index;
2188 } else {
2189 vec->src[i].src = nir_src_for_ssa(src1);
2190 vec->src[i].swizzle[0] = index - src0->num_components;
2191 }
2192 }
2193
2194 nir_builder_instr_insert(&b->nb, &vec->instr);
2195
2196 return &vec->dest.dest.ssa;
2197 }
2198
2199 /*
2200 * Concatentates a number of vectors/scalars together to produce a vector
2201 */
2202 static nir_ssa_def *
2203 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
2204 unsigned num_srcs, nir_ssa_def **srcs)
2205 {
2206 nir_alu_instr *vec = create_vec(b->shader, num_components,
2207 srcs[0]->bit_size);
2208
2209 unsigned dest_idx = 0;
2210 for (unsigned i = 0; i < num_srcs; i++) {
2211 nir_ssa_def *src = srcs[i];
2212 for (unsigned j = 0; j < src->num_components; j++) {
2213 vec->src[dest_idx].src = nir_src_for_ssa(src);
2214 vec->src[dest_idx].swizzle[0] = j;
2215 dest_idx++;
2216 }
2217 }
2218
2219 nir_builder_instr_insert(&b->nb, &vec->instr);
2220
2221 return &vec->dest.dest.ssa;
2222 }
2223
2224 static struct vtn_ssa_value *
2225 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
2226 {
2227 struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
2228 dest->type = src->type;
2229
2230 if (glsl_type_is_vector_or_scalar(src->type)) {
2231 dest->def = src->def;
2232 } else {
2233 unsigned elems = glsl_get_length(src->type);
2234
2235 dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
2236 for (unsigned i = 0; i < elems; i++)
2237 dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
2238 }
2239
2240 return dest;
2241 }
2242
2243 static struct vtn_ssa_value *
2244 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
2245 struct vtn_ssa_value *insert, const uint32_t *indices,
2246 unsigned num_indices)
2247 {
2248 struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
2249
2250 struct vtn_ssa_value *cur = dest;
2251 unsigned i;
2252 for (i = 0; i < num_indices - 1; i++) {
2253 cur = cur->elems[indices[i]];
2254 }
2255
2256 if (glsl_type_is_vector_or_scalar(cur->type)) {
2257 /* According to the SPIR-V spec, OpCompositeInsert may work down to
2258 * the component granularity. In that case, the last index will be
2259 * the index to insert the scalar into the vector.
2260 */
2261
2262 cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
2263 } else {
2264 cur->elems[indices[i]] = insert;
2265 }
2266
2267 return dest;
2268 }
2269
2270 static struct vtn_ssa_value *
2271 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
2272 const uint32_t *indices, unsigned num_indices)
2273 {
2274 struct vtn_ssa_value *cur = src;
2275 for (unsigned i = 0; i < num_indices; i++) {
2276 if (glsl_type_is_vector_or_scalar(cur->type)) {
2277 assert(i == num_indices - 1);
2278 /* According to the SPIR-V spec, OpCompositeExtract may work down to
2279 * the component granularity. The last index will be the index of the
2280 * vector to extract.
2281 */
2282
2283 struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
2284 ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
2285 ret->def = vtn_vector_extract(b, cur->def, indices[i]);
2286 return ret;
2287 } else {
2288 cur = cur->elems[indices[i]];
2289 }
2290 }
2291
2292 return cur;
2293 }
2294
2295 static void
2296 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
2297 const uint32_t *w, unsigned count)
2298 {
2299 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2300 const struct glsl_type *type =
2301 vtn_value(b, w[1], vtn_value_type_type)->type->type;
2302 val->ssa = vtn_create_ssa_value(b, type);
2303
2304 switch (opcode) {
2305 case SpvOpVectorExtractDynamic:
2306 val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
2307 vtn_ssa_value(b, w[4])->def);
2308 break;
2309
2310 case SpvOpVectorInsertDynamic:
2311 val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
2312 vtn_ssa_value(b, w[4])->def,
2313 vtn_ssa_value(b, w[5])->def);
2314 break;
2315
2316 case SpvOpVectorShuffle:
2317 val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
2318 vtn_ssa_value(b, w[3])->def,
2319 vtn_ssa_value(b, w[4])->def,
2320 w + 5);
2321 break;
2322
2323 case SpvOpCompositeConstruct: {
2324 unsigned elems = count - 3;
2325 if (glsl_type_is_vector_or_scalar(type)) {
2326 nir_ssa_def *srcs[4];
2327 for (unsigned i = 0; i < elems; i++)
2328 srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
2329 val->ssa->def =
2330 vtn_vector_construct(b, glsl_get_vector_elements(type),
2331 elems, srcs);
2332 } else {
2333 val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2334 for (unsigned i = 0; i < elems; i++)
2335 val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
2336 }
2337 break;
2338 }
2339 case SpvOpCompositeExtract:
2340 val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
2341 w + 4, count - 4);
2342 break;
2343
2344 case SpvOpCompositeInsert:
2345 val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
2346 vtn_ssa_value(b, w[3]),
2347 w + 5, count - 5);
2348 break;
2349
2350 case SpvOpCopyObject:
2351 val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
2352 break;
2353
2354 default:
2355 unreachable("unknown composite operation");
2356 }
2357 }
2358
2359 static void
2360 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
2361 const uint32_t *w, unsigned count)
2362 {
2363 nir_intrinsic_op intrinsic_op;
2364 switch (opcode) {
2365 case SpvOpEmitVertex:
2366 case SpvOpEmitStreamVertex:
2367 intrinsic_op = nir_intrinsic_emit_vertex;
2368 break;
2369 case SpvOpEndPrimitive:
2370 case SpvOpEndStreamPrimitive:
2371 intrinsic_op = nir_intrinsic_end_primitive;
2372 break;
2373 case SpvOpMemoryBarrier:
2374 intrinsic_op = nir_intrinsic_memory_barrier;
2375 break;
2376 case SpvOpControlBarrier:
2377 intrinsic_op = nir_intrinsic_barrier;
2378 break;
2379 default:
2380 unreachable("unknown barrier instruction");
2381 }
2382
2383 nir_intrinsic_instr *intrin =
2384 nir_intrinsic_instr_create(b->shader, intrinsic_op);
2385
2386 if (opcode == SpvOpEmitStreamVertex || opcode == SpvOpEndStreamPrimitive)
2387 nir_intrinsic_set_stream_id(intrin, w[1]);
2388
2389 nir_builder_instr_insert(&b->nb, &intrin->instr);
2390 }
2391
2392 static unsigned
2393 gl_primitive_from_spv_execution_mode(SpvExecutionMode mode)
2394 {
2395 switch (mode) {
2396 case SpvExecutionModeInputPoints:
2397 case SpvExecutionModeOutputPoints:
2398 return 0; /* GL_POINTS */
2399 case SpvExecutionModeInputLines:
2400 return 1; /* GL_LINES */
2401 case SpvExecutionModeInputLinesAdjacency:
2402 return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
2403 case SpvExecutionModeTriangles:
2404 return 4; /* GL_TRIANGLES */
2405 case SpvExecutionModeInputTrianglesAdjacency:
2406 return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
2407 case SpvExecutionModeQuads:
2408 return 7; /* GL_QUADS */
2409 case SpvExecutionModeIsolines:
2410 return 0x8E7A; /* GL_ISOLINES */
2411 case SpvExecutionModeOutputLineStrip:
2412 return 3; /* GL_LINE_STRIP */
2413 case SpvExecutionModeOutputTriangleStrip:
2414 return 5; /* GL_TRIANGLE_STRIP */
2415 default:
2416 assert(!"Invalid primitive type");
2417 return 4;
2418 }
2419 }
2420
2421 static unsigned
2422 vertices_in_from_spv_execution_mode(SpvExecutionMode mode)
2423 {
2424 switch (mode) {
2425 case SpvExecutionModeInputPoints:
2426 return 1;
2427 case SpvExecutionModeInputLines:
2428 return 2;
2429 case SpvExecutionModeInputLinesAdjacency:
2430 return 4;
2431 case SpvExecutionModeTriangles:
2432 return 3;
2433 case SpvExecutionModeInputTrianglesAdjacency:
2434 return 6;
2435 default:
2436 assert(!"Invalid GS input mode");
2437 return 0;
2438 }
2439 }
2440
2441 static gl_shader_stage
2442 stage_for_execution_model(SpvExecutionModel model)
2443 {
2444 switch (model) {
2445 case SpvExecutionModelVertex:
2446 return MESA_SHADER_VERTEX;
2447 case SpvExecutionModelTessellationControl:
2448 return MESA_SHADER_TESS_CTRL;
2449 case SpvExecutionModelTessellationEvaluation:
2450 return MESA_SHADER_TESS_EVAL;
2451 case SpvExecutionModelGeometry:
2452 return MESA_SHADER_GEOMETRY;
2453 case SpvExecutionModelFragment:
2454 return MESA_SHADER_FRAGMENT;
2455 case SpvExecutionModelGLCompute:
2456 return MESA_SHADER_COMPUTE;
2457 default:
2458 unreachable("Unsupported execution model");
2459 }
2460 }
2461
2462 #define spv_check_supported(name, cap) do { \
2463 if (!(b->ext && b->ext->name)) \
2464 vtn_warn("Unsupported SPIR-V capability: %s", \
2465 spirv_capability_to_string(cap)); \
2466 } while(0)
2467
2468 static bool
2469 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
2470 const uint32_t *w, unsigned count)
2471 {
2472 switch (opcode) {
2473 case SpvOpSource:
2474 case SpvOpSourceExtension:
2475 case SpvOpSourceContinued:
2476 case SpvOpExtension:
2477 /* Unhandled, but these are for debug so that's ok. */
2478 break;
2479
2480 case SpvOpCapability: {
2481 SpvCapability cap = w[1];
2482 switch (cap) {
2483 case SpvCapabilityMatrix:
2484 case SpvCapabilityShader:
2485 case SpvCapabilityGeometry:
2486 case SpvCapabilityGeometryPointSize:
2487 case SpvCapabilityUniformBufferArrayDynamicIndexing:
2488 case SpvCapabilitySampledImageArrayDynamicIndexing:
2489 case SpvCapabilityStorageBufferArrayDynamicIndexing:
2490 case SpvCapabilityStorageImageArrayDynamicIndexing:
2491 case SpvCapabilityImageRect:
2492 case SpvCapabilitySampledRect:
2493 case SpvCapabilitySampled1D:
2494 case SpvCapabilityImage1D:
2495 case SpvCapabilitySampledCubeArray:
2496 case SpvCapabilitySampledBuffer:
2497 case SpvCapabilityImageBuffer:
2498 case SpvCapabilityImageQuery:
2499 case SpvCapabilityDerivativeControl:
2500 case SpvCapabilityInterpolationFunction:
2501 case SpvCapabilityMultiViewport:
2502 case SpvCapabilitySampleRateShading:
2503 case SpvCapabilityClipDistance:
2504 case SpvCapabilityCullDistance:
2505 case SpvCapabilityInputAttachment:
2506 case SpvCapabilityImageGatherExtended:
2507 case SpvCapabilityStorageImageExtendedFormats:
2508 break;
2509
2510 case SpvCapabilityGeometryStreams:
2511 case SpvCapabilityTessellation:
2512 case SpvCapabilityTessellationPointSize:
2513 case SpvCapabilityLinkage:
2514 case SpvCapabilityVector16:
2515 case SpvCapabilityFloat16Buffer:
2516 case SpvCapabilityFloat16:
2517 case SpvCapabilityFloat64:
2518 case SpvCapabilityInt64:
2519 case SpvCapabilityInt64Atomics:
2520 case SpvCapabilityAtomicStorage:
2521 case SpvCapabilityInt16:
2522 case SpvCapabilityStorageImageMultisample:
2523 case SpvCapabilityImageCubeArray:
2524 case SpvCapabilityInt8:
2525 case SpvCapabilitySparseResidency:
2526 case SpvCapabilityMinLod:
2527 case SpvCapabilityTransformFeedback:
2528 case SpvCapabilityStorageImageReadWithoutFormat:
2529 case SpvCapabilityStorageImageWriteWithoutFormat:
2530 vtn_warn("Unsupported SPIR-V capability: %s",
2531 spirv_capability_to_string(cap));
2532 break;
2533
2534 case SpvCapabilityAddresses:
2535 case SpvCapabilityKernel:
2536 case SpvCapabilityImageBasic:
2537 case SpvCapabilityImageReadWrite:
2538 case SpvCapabilityImageMipmap:
2539 case SpvCapabilityPipes:
2540 case SpvCapabilityGroups:
2541 case SpvCapabilityDeviceEnqueue:
2542 case SpvCapabilityLiteralSampler:
2543 case SpvCapabilityGenericPointer:
2544 vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
2545 spirv_capability_to_string(cap));
2546 break;
2547
2548 case SpvCapabilityImageMSArray:
2549 spv_check_supported(image_ms_array, cap);
2550 break;
2551 }
2552 break;
2553 }
2554
2555 case SpvOpExtInstImport:
2556 vtn_handle_extension(b, opcode, w, count);
2557 break;
2558
2559 case SpvOpMemoryModel:
2560 assert(w[1] == SpvAddressingModelLogical);
2561 assert(w[2] == SpvMemoryModelGLSL450);
2562 break;
2563
2564 case SpvOpEntryPoint: {
2565 struct vtn_value *entry_point = &b->values[w[2]];
2566 /* Let this be a name label regardless */
2567 unsigned name_words;
2568 entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
2569
2570 if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
2571 stage_for_execution_model(w[1]) != b->entry_point_stage)
2572 break;
2573
2574 assert(b->entry_point == NULL);
2575 b->entry_point = entry_point;
2576 break;
2577 }
2578
2579 case SpvOpString:
2580 vtn_push_value(b, w[1], vtn_value_type_string)->str =
2581 vtn_string_literal(b, &w[2], count - 2, NULL);
2582 break;
2583
2584 case SpvOpName:
2585 b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
2586 break;
2587
2588 case SpvOpMemberName:
2589 /* TODO */
2590 break;
2591
2592 case SpvOpExecutionMode:
2593 case SpvOpDecorationGroup:
2594 case SpvOpDecorate:
2595 case SpvOpMemberDecorate:
2596 case SpvOpGroupDecorate:
2597 case SpvOpGroupMemberDecorate:
2598 vtn_handle_decoration(b, opcode, w, count);
2599 break;
2600
2601 default:
2602 return false; /* End of preamble */
2603 }
2604
2605 return true;
2606 }
2607
2608 static void
2609 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
2610 const struct vtn_decoration *mode, void *data)
2611 {
2612 assert(b->entry_point == entry_point);
2613
2614 switch(mode->exec_mode) {
2615 case SpvExecutionModeOriginUpperLeft:
2616 case SpvExecutionModeOriginLowerLeft:
2617 b->origin_upper_left =
2618 (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
2619 break;
2620
2621 case SpvExecutionModeEarlyFragmentTests:
2622 assert(b->shader->stage == MESA_SHADER_FRAGMENT);
2623 b->shader->info->fs.early_fragment_tests = true;
2624 break;
2625
2626 case SpvExecutionModeInvocations:
2627 assert(b->shader->stage == MESA_SHADER_GEOMETRY);
2628 b->shader->info->gs.invocations = MAX2(1, mode->literals[0]);
2629 break;
2630
2631 case SpvExecutionModeDepthReplacing:
2632 assert(b->shader->stage == MESA_SHADER_FRAGMENT);
2633 b->shader->info->fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
2634 break;
2635 case SpvExecutionModeDepthGreater:
2636 assert(b->shader->stage == MESA_SHADER_FRAGMENT);
2637 b->shader->info->fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
2638 break;
2639 case SpvExecutionModeDepthLess:
2640 assert(b->shader->stage == MESA_SHADER_FRAGMENT);
2641 b->shader->info->fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
2642 break;
2643 case SpvExecutionModeDepthUnchanged:
2644 assert(b->shader->stage == MESA_SHADER_FRAGMENT);
2645 b->shader->info->fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2646 break;
2647
2648 case SpvExecutionModeLocalSize:
2649 assert(b->shader->stage == MESA_SHADER_COMPUTE);
2650 b->shader->info->cs.local_size[0] = mode->literals[0];
2651 b->shader->info->cs.local_size[1] = mode->literals[1];
2652 b->shader->info->cs.local_size[2] = mode->literals[2];
2653 break;
2654 case SpvExecutionModeLocalSizeHint:
2655 break; /* Nothing to do with this */
2656
2657 case SpvExecutionModeOutputVertices:
2658 assert(b->shader->stage == MESA_SHADER_GEOMETRY);
2659 b->shader->info->gs.vertices_out = mode->literals[0];
2660 break;
2661
2662 case SpvExecutionModeInputPoints:
2663 case SpvExecutionModeInputLines:
2664 case SpvExecutionModeInputLinesAdjacency:
2665 case SpvExecutionModeTriangles:
2666 case SpvExecutionModeInputTrianglesAdjacency:
2667 case SpvExecutionModeQuads:
2668 case SpvExecutionModeIsolines:
2669 if (b->shader->stage == MESA_SHADER_GEOMETRY) {
2670 b->shader->info->gs.vertices_in =
2671 vertices_in_from_spv_execution_mode(mode->exec_mode);
2672 } else {
2673 assert(!"Tesselation shaders not yet supported");
2674 }
2675 break;
2676
2677 case SpvExecutionModeOutputPoints:
2678 case SpvExecutionModeOutputLineStrip:
2679 case SpvExecutionModeOutputTriangleStrip:
2680 assert(b->shader->stage == MESA_SHADER_GEOMETRY);
2681 b->shader->info->gs.output_primitive =
2682 gl_primitive_from_spv_execution_mode(mode->exec_mode);
2683 break;
2684
2685 case SpvExecutionModeSpacingEqual:
2686 case SpvExecutionModeSpacingFractionalEven:
2687 case SpvExecutionModeSpacingFractionalOdd:
2688 case SpvExecutionModeVertexOrderCw:
2689 case SpvExecutionModeVertexOrderCcw:
2690 case SpvExecutionModePointMode:
2691 assert(!"TODO: Add tessellation metadata");
2692 break;
2693
2694 case SpvExecutionModePixelCenterInteger:
2695 b->pixel_center_integer = true;
2696 break;
2697
2698 case SpvExecutionModeXfb:
2699 assert(!"Unhandled execution mode");
2700 break;
2701
2702 case SpvExecutionModeVecTypeHint:
2703 case SpvExecutionModeContractionOff:
2704 break; /* OpenCL */
2705 }
2706 }
2707
2708 static bool
2709 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
2710 const uint32_t *w, unsigned count)
2711 {
2712 switch (opcode) {
2713 case SpvOpSource:
2714 case SpvOpSourceContinued:
2715 case SpvOpSourceExtension:
2716 case SpvOpExtension:
2717 case SpvOpCapability:
2718 case SpvOpExtInstImport:
2719 case SpvOpMemoryModel:
2720 case SpvOpEntryPoint:
2721 case SpvOpExecutionMode:
2722 case SpvOpString:
2723 case SpvOpName:
2724 case SpvOpMemberName:
2725 case SpvOpDecorationGroup:
2726 case SpvOpDecorate:
2727 case SpvOpMemberDecorate:
2728 case SpvOpGroupDecorate:
2729 case SpvOpGroupMemberDecorate:
2730 assert(!"Invalid opcode types and variables section");
2731 break;
2732
2733 case SpvOpTypeVoid:
2734 case SpvOpTypeBool:
2735 case SpvOpTypeInt:
2736 case SpvOpTypeFloat:
2737 case SpvOpTypeVector:
2738 case SpvOpTypeMatrix:
2739 case SpvOpTypeImage:
2740 case SpvOpTypeSampler:
2741 case SpvOpTypeSampledImage:
2742 case SpvOpTypeArray:
2743 case SpvOpTypeRuntimeArray:
2744 case SpvOpTypeStruct:
2745 case SpvOpTypeOpaque:
2746 case SpvOpTypePointer:
2747 case SpvOpTypeFunction:
2748 case SpvOpTypeEvent:
2749 case SpvOpTypeDeviceEvent:
2750 case SpvOpTypeReserveId:
2751 case SpvOpTypeQueue:
2752 case SpvOpTypePipe:
2753 vtn_handle_type(b, opcode, w, count);
2754 break;
2755
2756 case SpvOpConstantTrue:
2757 case SpvOpConstantFalse:
2758 case SpvOpConstant:
2759 case SpvOpConstantComposite:
2760 case SpvOpConstantSampler:
2761 case SpvOpConstantNull:
2762 case SpvOpSpecConstantTrue:
2763 case SpvOpSpecConstantFalse:
2764 case SpvOpSpecConstant:
2765 case SpvOpSpecConstantComposite:
2766 case SpvOpSpecConstantOp:
2767 vtn_handle_constant(b, opcode, w, count);
2768 break;
2769
2770 case SpvOpVariable:
2771 vtn_handle_variables(b, opcode, w, count);
2772 break;
2773
2774 default:
2775 return false; /* End of preamble */
2776 }
2777
2778 return true;
2779 }
2780
2781 static bool
2782 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
2783 const uint32_t *w, unsigned count)
2784 {
2785 switch (opcode) {
2786 case SpvOpLabel:
2787 break;
2788
2789 case SpvOpLoopMerge:
2790 case SpvOpSelectionMerge:
2791 /* This is handled by cfg pre-pass and walk_blocks */
2792 break;
2793
2794 case SpvOpUndef: {
2795 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
2796 val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
2797 break;
2798 }
2799
2800 case SpvOpExtInst:
2801 vtn_handle_extension(b, opcode, w, count);
2802 break;
2803
2804 case SpvOpVariable:
2805 case SpvOpLoad:
2806 case SpvOpStore:
2807 case SpvOpCopyMemory:
2808 case SpvOpCopyMemorySized:
2809 case SpvOpAccessChain:
2810 case SpvOpInBoundsAccessChain:
2811 case SpvOpArrayLength:
2812 vtn_handle_variables(b, opcode, w, count);
2813 break;
2814
2815 case SpvOpFunctionCall:
2816 vtn_handle_function_call(b, opcode, w, count);
2817 break;
2818
2819 case SpvOpSampledImage:
2820 case SpvOpImage:
2821 case SpvOpImageSampleImplicitLod:
2822 case SpvOpImageSampleExplicitLod:
2823 case SpvOpImageSampleDrefImplicitLod:
2824 case SpvOpImageSampleDrefExplicitLod:
2825 case SpvOpImageSampleProjImplicitLod:
2826 case SpvOpImageSampleProjExplicitLod:
2827 case SpvOpImageSampleProjDrefImplicitLod:
2828 case SpvOpImageSampleProjDrefExplicitLod:
2829 case SpvOpImageFetch:
2830 case SpvOpImageGather:
2831 case SpvOpImageDrefGather:
2832 case SpvOpImageQuerySizeLod:
2833 case SpvOpImageQueryLod:
2834 case SpvOpImageQueryLevels:
2835 case SpvOpImageQuerySamples:
2836 vtn_handle_texture(b, opcode, w, count);
2837 break;
2838
2839 case SpvOpImageRead:
2840 case SpvOpImageWrite:
2841 case SpvOpImageTexelPointer:
2842 vtn_handle_image(b, opcode, w, count);
2843 break;
2844
2845 case SpvOpImageQuerySize: {
2846 struct vtn_access_chain *image =
2847 vtn_value(b, w[3], vtn_value_type_access_chain)->access_chain;
2848 if (glsl_type_is_image(image->var->var->interface_type)) {
2849 vtn_handle_image(b, opcode, w, count);
2850 } else {
2851 vtn_handle_texture(b, opcode, w, count);
2852 }
2853 break;
2854 }
2855
2856 case SpvOpAtomicLoad:
2857 case SpvOpAtomicExchange:
2858 case SpvOpAtomicCompareExchange:
2859 case SpvOpAtomicCompareExchangeWeak:
2860 case SpvOpAtomicIIncrement:
2861 case SpvOpAtomicIDecrement:
2862 case SpvOpAtomicIAdd:
2863 case SpvOpAtomicISub:
2864 case SpvOpAtomicSMin:
2865 case SpvOpAtomicUMin:
2866 case SpvOpAtomicSMax:
2867 case SpvOpAtomicUMax:
2868 case SpvOpAtomicAnd:
2869 case SpvOpAtomicOr:
2870 case SpvOpAtomicXor: {
2871 struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
2872 if (pointer->value_type == vtn_value_type_image_pointer) {
2873 vtn_handle_image(b, opcode, w, count);
2874 } else {
2875 assert(pointer->value_type == vtn_value_type_access_chain);
2876 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
2877 }
2878 break;
2879 }
2880
2881 case SpvOpAtomicStore: {
2882 struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
2883 if (pointer->value_type == vtn_value_type_image_pointer) {
2884 vtn_handle_image(b, opcode, w, count);
2885 } else {
2886 assert(pointer->value_type == vtn_value_type_access_chain);
2887 vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
2888 }
2889 break;
2890 }
2891
2892 case SpvOpSNegate:
2893 case SpvOpFNegate:
2894 case SpvOpNot:
2895 case SpvOpAny:
2896 case SpvOpAll:
2897 case SpvOpConvertFToU:
2898 case SpvOpConvertFToS:
2899 case SpvOpConvertSToF:
2900 case SpvOpConvertUToF:
2901 case SpvOpUConvert:
2902 case SpvOpSConvert:
2903 case SpvOpFConvert:
2904 case SpvOpQuantizeToF16:
2905 case SpvOpConvertPtrToU:
2906 case SpvOpConvertUToPtr:
2907 case SpvOpPtrCastToGeneric:
2908 case SpvOpGenericCastToPtr:
2909 case SpvOpBitcast:
2910 case SpvOpIsNan:
2911 case SpvOpIsInf:
2912 case SpvOpIsFinite:
2913 case SpvOpIsNormal:
2914 case SpvOpSignBitSet:
2915 case SpvOpLessOrGreater:
2916 case SpvOpOrdered:
2917 case SpvOpUnordered:
2918 case SpvOpIAdd:
2919 case SpvOpFAdd:
2920 case SpvOpISub:
2921 case SpvOpFSub:
2922 case SpvOpIMul:
2923 case SpvOpFMul:
2924 case SpvOpUDiv:
2925 case SpvOpSDiv:
2926 case SpvOpFDiv:
2927 case SpvOpUMod:
2928 case SpvOpSRem:
2929 case SpvOpSMod:
2930 case SpvOpFRem:
2931 case SpvOpFMod:
2932 case SpvOpVectorTimesScalar:
2933 case SpvOpDot:
2934 case SpvOpIAddCarry:
2935 case SpvOpISubBorrow:
2936 case SpvOpUMulExtended:
2937 case SpvOpSMulExtended:
2938 case SpvOpShiftRightLogical:
2939 case SpvOpShiftRightArithmetic:
2940 case SpvOpShiftLeftLogical:
2941 case SpvOpLogicalEqual:
2942 case SpvOpLogicalNotEqual:
2943 case SpvOpLogicalOr:
2944 case SpvOpLogicalAnd:
2945 case SpvOpLogicalNot:
2946 case SpvOpBitwiseOr:
2947 case SpvOpBitwiseXor:
2948 case SpvOpBitwiseAnd:
2949 case SpvOpSelect:
2950 case SpvOpIEqual:
2951 case SpvOpFOrdEqual:
2952 case SpvOpFUnordEqual:
2953 case SpvOpINotEqual:
2954 case SpvOpFOrdNotEqual:
2955 case SpvOpFUnordNotEqual:
2956 case SpvOpULessThan:
2957 case SpvOpSLessThan:
2958 case SpvOpFOrdLessThan:
2959 case SpvOpFUnordLessThan:
2960 case SpvOpUGreaterThan:
2961 case SpvOpSGreaterThan:
2962 case SpvOpFOrdGreaterThan:
2963 case SpvOpFUnordGreaterThan:
2964 case SpvOpULessThanEqual:
2965 case SpvOpSLessThanEqual:
2966 case SpvOpFOrdLessThanEqual:
2967 case SpvOpFUnordLessThanEqual:
2968 case SpvOpUGreaterThanEqual:
2969 case SpvOpSGreaterThanEqual:
2970 case SpvOpFOrdGreaterThanEqual:
2971 case SpvOpFUnordGreaterThanEqual:
2972 case SpvOpDPdx:
2973 case SpvOpDPdy:
2974 case SpvOpFwidth:
2975 case SpvOpDPdxFine:
2976 case SpvOpDPdyFine:
2977 case SpvOpFwidthFine:
2978 case SpvOpDPdxCoarse:
2979 case SpvOpDPdyCoarse:
2980 case SpvOpFwidthCoarse:
2981 case SpvOpBitFieldInsert:
2982 case SpvOpBitFieldSExtract:
2983 case SpvOpBitFieldUExtract:
2984 case SpvOpBitReverse:
2985 case SpvOpBitCount:
2986 case SpvOpTranspose:
2987 case SpvOpOuterProduct:
2988 case SpvOpMatrixTimesScalar:
2989 case SpvOpVectorTimesMatrix:
2990 case SpvOpMatrixTimesVector:
2991 case SpvOpMatrixTimesMatrix:
2992 vtn_handle_alu(b, opcode, w, count);
2993 break;
2994
2995 case SpvOpVectorExtractDynamic:
2996 case SpvOpVectorInsertDynamic:
2997 case SpvOpVectorShuffle:
2998 case SpvOpCompositeConstruct:
2999 case SpvOpCompositeExtract:
3000 case SpvOpCompositeInsert:
3001 case SpvOpCopyObject:
3002 vtn_handle_composite(b, opcode, w, count);
3003 break;
3004
3005 case SpvOpEmitVertex:
3006 case SpvOpEndPrimitive:
3007 case SpvOpEmitStreamVertex:
3008 case SpvOpEndStreamPrimitive:
3009 case SpvOpControlBarrier:
3010 case SpvOpMemoryBarrier:
3011 vtn_handle_barrier(b, opcode, w, count);
3012 break;
3013
3014 default:
3015 unreachable("Unhandled opcode");
3016 }
3017
3018 return true;
3019 }
3020
3021 nir_function *
3022 spirv_to_nir(const uint32_t *words, size_t word_count,
3023 struct nir_spirv_specialization *spec, unsigned num_spec,
3024 gl_shader_stage stage, const char *entry_point_name,
3025 const struct nir_spirv_supported_extensions *ext,
3026 const nir_shader_compiler_options *options)
3027 {
3028 const uint32_t *word_end = words + word_count;
3029
3030 /* Handle the SPIR-V header (first 4 dwords) */
3031 assert(word_count > 5);
3032
3033 assert(words[0] == SpvMagicNumber);
3034 assert(words[1] >= 0x10000);
3035 /* words[2] == generator magic */
3036 unsigned value_id_bound = words[3];
3037 assert(words[4] == 0);
3038
3039 words+= 5;
3040
3041 /* Initialize the stn_builder object */
3042 struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
3043 b->value_id_bound = value_id_bound;
3044 b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
3045 exec_list_make_empty(&b->functions);
3046 b->entry_point_stage = stage;
3047 b->entry_point_name = entry_point_name;
3048 b->ext = ext;
3049
3050 /* Handle all the preamble instructions */
3051 words = vtn_foreach_instruction(b, words, word_end,
3052 vtn_handle_preamble_instruction);
3053
3054 if (b->entry_point == NULL) {
3055 assert(!"Entry point not found");
3056 ralloc_free(b);
3057 return NULL;
3058 }
3059
3060 b->shader = nir_shader_create(NULL, stage, options, NULL);
3061
3062 /* Set shader info defaults */
3063 b->shader->info->gs.invocations = 1;
3064
3065 /* Parse execution modes */
3066 vtn_foreach_execution_mode(b, b->entry_point,
3067 vtn_handle_execution_mode, NULL);
3068
3069 b->specializations = spec;
3070 b->num_specializations = num_spec;
3071
3072 /* Handle all variable, type, and constant instructions */
3073 words = vtn_foreach_instruction(b, words, word_end,
3074 vtn_handle_variable_or_type_instruction);
3075
3076 vtn_build_cfg(b, words, word_end);
3077
3078 foreach_list_typed(struct vtn_function, func, node, &b->functions) {
3079 b->impl = func->impl;
3080 b->const_table = _mesa_hash_table_create(b, _mesa_hash_pointer,
3081 _mesa_key_pointer_equal);
3082
3083 vtn_function_emit(b, func, vtn_handle_body_instruction);
3084 }
3085
3086 assert(b->entry_point->value_type == vtn_value_type_function);
3087 nir_function *entry_point = b->entry_point->func->impl->function;
3088 assert(entry_point);
3089
3090 ralloc_free(b);
3091
3092 return entry_point;
3093 }