OSDN Git Service

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