OSDN Git Service

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