shader_validation.cpp revision bb6e1ecb1215cdd9aa496b3f9e2c5521711760f6
1/* Copyright (c) 2015-2017 The Khronos Group Inc.
2 * Copyright (c) 2015-2017 Valve Corporation
3 * Copyright (c) 2015-2017 LunarG, Inc.
4 * Copyright (C) 2015-2017 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Chris Forbes <chrisf@ijw.co.nz>
19 */
20
21#include <cinttypes>
22#include <cassert>
23#include <vector>
24#include <unordered_map>
25#include <string>
26#include <sstream>
27#include <SPIRV/spirv.hpp>
28#include "vk_loader_platform.h"
29#include "vk_enum_string_helper.h"
30#include "vk_layer_table.h"
31#include "vk_layer_data.h"
32#include "vk_layer_extension_utils.h"
33#include "vk_layer_utils.h"
34#include "core_validation.h"
35#include "core_validation_types.h"
36#include "shader_validation.h"
37#include "spirv-tools/libspirv.h"
38
39enum FORMAT_TYPE {
40    FORMAT_TYPE_FLOAT = 1,  // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
41    FORMAT_TYPE_SINT = 2,
42    FORMAT_TYPE_UINT = 4,
43};
44
45typedef std::pair<unsigned, unsigned> location_t;
46
47struct interface_var {
48    uint32_t id;
49    uint32_t type_id;
50    uint32_t offset;
51    bool is_patch;
52    bool is_block_member;
53    bool is_relaxed_precision;
54    // TODO: collect the name, too? Isn't required to be present.
55};
56
57struct shader_stage_attributes {
58    char const *const name;
59    bool arrayed_input;
60    bool arrayed_output;
61};
62
63static shader_stage_attributes shader_stage_attribs[] = {
64    {"vertex shader", false, false},  {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
65    {"geometry shader", true, false}, {"fragment shader", false, false},
66};
67
68// SPIRV utility functions
69void shader_module::build_def_index() {
70    for (auto insn : *this) {
71        switch (insn.opcode()) {
72            // Types
73            case spv::OpTypeVoid:
74            case spv::OpTypeBool:
75            case spv::OpTypeInt:
76            case spv::OpTypeFloat:
77            case spv::OpTypeVector:
78            case spv::OpTypeMatrix:
79            case spv::OpTypeImage:
80            case spv::OpTypeSampler:
81            case spv::OpTypeSampledImage:
82            case spv::OpTypeArray:
83            case spv::OpTypeRuntimeArray:
84            case spv::OpTypeStruct:
85            case spv::OpTypeOpaque:
86            case spv::OpTypePointer:
87            case spv::OpTypeFunction:
88            case spv::OpTypeEvent:
89            case spv::OpTypeDeviceEvent:
90            case spv::OpTypeReserveId:
91            case spv::OpTypeQueue:
92            case spv::OpTypePipe:
93                def_index[insn.word(1)] = insn.offset();
94                break;
95
96                // Fixed constants
97            case spv::OpConstantTrue:
98            case spv::OpConstantFalse:
99            case spv::OpConstant:
100            case spv::OpConstantComposite:
101            case spv::OpConstantSampler:
102            case spv::OpConstantNull:
103                def_index[insn.word(2)] = insn.offset();
104                break;
105
106                // Specialization constants
107            case spv::OpSpecConstantTrue:
108            case spv::OpSpecConstantFalse:
109            case spv::OpSpecConstant:
110            case spv::OpSpecConstantComposite:
111            case spv::OpSpecConstantOp:
112                def_index[insn.word(2)] = insn.offset();
113                break;
114
115                // Variables
116            case spv::OpVariable:
117                def_index[insn.word(2)] = insn.offset();
118                break;
119
120                // Functions
121            case spv::OpFunction:
122                def_index[insn.word(2)] = insn.offset();
123                break;
124
125            default:
126                // We don't care about any other defs for now.
127                break;
128        }
129    }
130}
131
132static spirv_inst_iter find_entrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
133    for (auto insn : *src) {
134        if (insn.opcode() == spv::OpEntryPoint) {
135            auto entrypointName = (char const *)&insn.word(3);
136            auto entrypointStageBits = 1u << insn.word(1);
137
138            if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
139                return insn;
140            }
141        }
142    }
143
144    return src->end();
145}
146
147static char const *storage_class_name(unsigned sc) {
148    switch (sc) {
149        case spv::StorageClassInput:
150            return "input";
151        case spv::StorageClassOutput:
152            return "output";
153        case spv::StorageClassUniformConstant:
154            return "const uniform";
155        case spv::StorageClassUniform:
156            return "uniform";
157        case spv::StorageClassWorkgroup:
158            return "workgroup local";
159        case spv::StorageClassCrossWorkgroup:
160            return "workgroup global";
161        case spv::StorageClassPrivate:
162            return "private global";
163        case spv::StorageClassFunction:
164            return "function";
165        case spv::StorageClassGeneric:
166            return "generic";
167        case spv::StorageClassAtomicCounter:
168            return "atomic counter";
169        case spv::StorageClassImage:
170            return "image";
171        case spv::StorageClassPushConstant:
172            return "push constant";
173        default:
174            return "unknown";
175    }
176}
177
178// Get the value of an integral constant
179unsigned get_constant_value(shader_module const *src, unsigned id) {
180    auto value = src->get_def(id);
181    assert(value != src->end());
182
183    if (value.opcode() != spv::OpConstant) {
184        // TODO: Either ensure that the specialization transform is already performed on a module we're
185        //       considering here, OR -- specialize on the fly now.
186        return 1;
187    }
188
189    return value.word(3);
190}
191
192static void describe_type_inner(std::ostringstream &ss, shader_module const *src, unsigned type) {
193    auto insn = src->get_def(type);
194    assert(insn != src->end());
195
196    switch (insn.opcode()) {
197        case spv::OpTypeBool:
198            ss << "bool";
199            break;
200        case spv::OpTypeInt:
201            ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
202            break;
203        case spv::OpTypeFloat:
204            ss << "float" << insn.word(2);
205            break;
206        case spv::OpTypeVector:
207            ss << "vec" << insn.word(3) << " of ";
208            describe_type_inner(ss, src, insn.word(2));
209            break;
210        case spv::OpTypeMatrix:
211            ss << "mat" << insn.word(3) << " of ";
212            describe_type_inner(ss, src, insn.word(2));
213            break;
214        case spv::OpTypeArray:
215            ss << "arr[" << get_constant_value(src, insn.word(3)) << "] of ";
216            describe_type_inner(ss, src, insn.word(2));
217            break;
218        case spv::OpTypePointer:
219            ss << "ptr to " << storage_class_name(insn.word(2)) << " ";
220            describe_type_inner(ss, src, insn.word(3));
221            break;
222        case spv::OpTypeStruct: {
223            ss << "struct of (";
224            for (unsigned i = 2; i < insn.len(); i++) {
225                describe_type_inner(ss, src, insn.word(i));
226                if (i == insn.len() - 1) {
227                    ss << ")";
228                } else {
229                    ss << ", ";
230                }
231            }
232            break;
233        }
234        case spv::OpTypeSampler:
235            ss << "sampler";
236            break;
237        case spv::OpTypeSampledImage:
238            ss << "sampler+";
239            describe_type_inner(ss, src, insn.word(2));
240            break;
241        case spv::OpTypeImage:
242            ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
243            break;
244        default:
245            ss << "oddtype";
246            break;
247    }
248}
249
250static std::string describe_type(shader_module const *src, unsigned type) {
251    std::ostringstream ss;
252    describe_type_inner(ss, src, type);
253    return ss.str();
254}
255
256static bool is_narrow_numeric_type(spirv_inst_iter type) {
257    if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
258    return type.word(2) < 64;
259}
260
261static bool types_match(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
262                        bool b_arrayed, bool relaxed) {
263    // Walk two type trees together, and complain about differences
264    auto a_insn = a->get_def(a_type);
265    auto b_insn = b->get_def(b_type);
266    assert(a_insn != a->end());
267    assert(b_insn != b->end());
268
269    if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
270        return types_match(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
271    }
272
273    if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
274        // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
275        return types_match(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
276    }
277
278    if (a_insn.opcode() == spv::OpTypeVector && relaxed && is_narrow_numeric_type(b_insn)) {
279        return types_match(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
280    }
281
282    if (a_insn.opcode() != b_insn.opcode()) {
283        return false;
284    }
285
286    if (a_insn.opcode() == spv::OpTypePointer) {
287        // Match on pointee type. storage class is expected to differ
288        return types_match(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
289    }
290
291    if (a_arrayed || b_arrayed) {
292        // If we havent resolved array-of-verts by here, we're not going to.
293        return false;
294    }
295
296    switch (a_insn.opcode()) {
297        case spv::OpTypeBool:
298            return true;
299        case spv::OpTypeInt:
300            // Match on width, signedness
301            return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
302        case spv::OpTypeFloat:
303            // Match on width
304            return a_insn.word(2) == b_insn.word(2);
305        case spv::OpTypeVector:
306            // Match on element type, count.
307            if (!types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
308            if (relaxed && is_narrow_numeric_type(a->get_def(a_insn.word(2)))) {
309                return a_insn.word(3) >= b_insn.word(3);
310            } else {
311                return a_insn.word(3) == b_insn.word(3);
312            }
313        case spv::OpTypeMatrix:
314            // Match on element type, count.
315            return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
316                a_insn.word(3) == b_insn.word(3);
317        case spv::OpTypeArray:
318            // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
319            // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
320            return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
321                get_constant_value(a, a_insn.word(3)) == get_constant_value(b, b_insn.word(3));
322        case spv::OpTypeStruct:
323            // Match on all element types
324        {
325            if (a_insn.len() != b_insn.len()) {
326                return false;  // Structs cannot match if member counts differ
327            }
328
329            for (unsigned i = 2; i < a_insn.len(); i++) {
330                if (!types_match(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
331                    return false;
332                }
333            }
334
335            return true;
336        }
337        default:
338            // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
339            return false;
340    }
341}
342
343static unsigned value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
344    auto it = map.find(id);
345    if (it == map.end())
346        return def;
347    else
348        return it->second;
349}
350
351static unsigned get_locations_consumed_by_type(shader_module const *src, unsigned type, bool strip_array_level) {
352    auto insn = src->get_def(type);
353    assert(insn != src->end());
354
355    switch (insn.opcode()) {
356        case spv::OpTypePointer:
357            // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
358            // pointers around.
359            return get_locations_consumed_by_type(src, insn.word(3), strip_array_level);
360        case spv::OpTypeArray:
361            if (strip_array_level) {
362                return get_locations_consumed_by_type(src, insn.word(2), false);
363            } else {
364                return get_constant_value(src, insn.word(3)) * get_locations_consumed_by_type(src, insn.word(2), false);
365            }
366        case spv::OpTypeMatrix:
367            // Num locations is the dimension * element size
368            return insn.word(3) * get_locations_consumed_by_type(src, insn.word(2), false);
369        case spv::OpTypeVector: {
370            auto scalar_type = src->get_def(insn.word(2));
371            auto bit_width =
372                (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
373
374            // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
375            return (bit_width * insn.word(3) + 127) / 128;
376        }
377        default:
378            // Everything else is just 1.
379            return 1;
380
381            // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
382    }
383}
384
385static unsigned get_locations_consumed_by_format(VkFormat format) {
386    switch (format) {
387        case VK_FORMAT_R64G64B64A64_SFLOAT:
388        case VK_FORMAT_R64G64B64A64_SINT:
389        case VK_FORMAT_R64G64B64A64_UINT:
390        case VK_FORMAT_R64G64B64_SFLOAT:
391        case VK_FORMAT_R64G64B64_SINT:
392        case VK_FORMAT_R64G64B64_UINT:
393            return 2;
394        default:
395            return 1;
396    }
397}
398
399static unsigned get_format_type(VkFormat fmt) {
400    if (FormatIsSInt(fmt))
401        return FORMAT_TYPE_SINT;
402    if (FormatIsUInt(fmt))
403        return FORMAT_TYPE_UINT;
404    if (FormatIsDepthAndStencil(fmt))
405        return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
406    if (fmt == VK_FORMAT_UNDEFINED)
407        return 0;
408    // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
409    return FORMAT_TYPE_FLOAT;
410}
411
412// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
413static unsigned get_fundamental_type(shader_module const *src, unsigned type) {
414    auto insn = src->get_def(type);
415    assert(insn != src->end());
416
417    switch (insn.opcode()) {
418        case spv::OpTypeInt:
419            return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
420        case spv::OpTypeFloat:
421            return FORMAT_TYPE_FLOAT;
422        case spv::OpTypeVector:
423            return get_fundamental_type(src, insn.word(2));
424        case spv::OpTypeMatrix:
425            return get_fundamental_type(src, insn.word(2));
426        case spv::OpTypeArray:
427            return get_fundamental_type(src, insn.word(2));
428        case spv::OpTypePointer:
429            return get_fundamental_type(src, insn.word(3));
430        case spv::OpTypeImage:
431            return get_fundamental_type(src, insn.word(2));
432
433        default:
434            return 0;
435    }
436}
437
438static uint32_t get_shader_stage_id(VkShaderStageFlagBits stage) {
439    uint32_t bit_pos = uint32_t(u_ffs(stage));
440    return bit_pos - 1;
441}
442
443static spirv_inst_iter get_struct_type(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
444    while (true) {
445        if (def.opcode() == spv::OpTypePointer) {
446            def = src->get_def(def.word(3));
447        } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
448            def = src->get_def(def.word(2));
449            is_array_of_verts = false;
450        } else if (def.opcode() == spv::OpTypeStruct) {
451            return def;
452        } else {
453            return src->end();
454        }
455    }
456}
457
458static bool collect_interface_block_members(shader_module const *src, std::map<location_t, interface_var> *out,
459                                            std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts,
460                                            uint32_t id, uint32_t type_id, bool is_patch, int /*first_location*/) {
461    // Walk down the type_id presented, trying to determine whether it's actually an interface block.
462    auto type = get_struct_type(src, src->get_def(type_id), is_array_of_verts && !is_patch);
463    if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
464        // This isn't an interface block.
465        return false;
466    }
467
468    std::unordered_map<unsigned, unsigned> member_components;
469    std::unordered_map<unsigned, unsigned> member_relaxed_precision;
470    std::unordered_map<unsigned, unsigned> member_patch;
471
472    // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
473    for (auto insn : *src) {
474        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
475            unsigned member_index = insn.word(2);
476
477            if (insn.word(3) == spv::DecorationComponent) {
478                unsigned component = insn.word(4);
479                member_components[member_index] = component;
480            }
481
482            if (insn.word(3) == spv::DecorationRelaxedPrecision) {
483                member_relaxed_precision[member_index] = 1;
484            }
485
486            if (insn.word(3) == spv::DecorationPatch) {
487                member_patch[member_index] = 1;
488            }
489        }
490    }
491
492    // TODO: correctly handle location assignment from outside
493
494    // Second pass -- produce the output, from Location decorations
495    for (auto insn : *src) {
496        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
497            unsigned member_index = insn.word(2);
498            unsigned member_type_id = type.word(2 + member_index);
499
500            if (insn.word(3) == spv::DecorationLocation) {
501                unsigned location = insn.word(4);
502                unsigned num_locations = get_locations_consumed_by_type(src, member_type_id, false);
503                auto component_it = member_components.find(member_index);
504                unsigned component = component_it == member_components.end() ? 0 : component_it->second;
505                bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
506                bool member_is_patch = is_patch || member_patch.count(member_index)>0;
507
508                for (unsigned int offset = 0; offset < num_locations; offset++) {
509                    interface_var v = {};
510                    v.id = id;
511                    // TODO: member index in interface_var too?
512                    v.type_id = member_type_id;
513                    v.offset = offset;
514                    v.is_patch = member_is_patch;
515                    v.is_block_member = true;
516                    v.is_relaxed_precision = is_relaxed_precision;
517                    (*out)[std::make_pair(location + offset, component)] = v;
518                }
519            }
520        }
521    }
522
523    return true;
524}
525
526static std::map<location_t, interface_var> collect_interface_by_location(shader_module const *src, spirv_inst_iter entrypoint,
527                                                                         spv::StorageClass sinterface, bool is_array_of_verts) {
528    std::unordered_map<unsigned, unsigned> var_locations;
529    std::unordered_map<unsigned, unsigned> var_builtins;
530    std::unordered_map<unsigned, unsigned> var_components;
531    std::unordered_map<unsigned, unsigned> blocks;
532    std::unordered_map<unsigned, unsigned> var_patch;
533    std::unordered_map<unsigned, unsigned> var_relaxed_precision;
534
535    for (auto insn : *src) {
536        // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
537        // fits neither model.
538        if (insn.opcode() == spv::OpDecorate) {
539            if (insn.word(2) == spv::DecorationLocation) {
540                var_locations[insn.word(1)] = insn.word(3);
541            }
542
543            if (insn.word(2) == spv::DecorationBuiltIn) {
544                var_builtins[insn.word(1)] = insn.word(3);
545            }
546
547            if (insn.word(2) == spv::DecorationComponent) {
548                var_components[insn.word(1)] = insn.word(3);
549            }
550
551            if (insn.word(2) == spv::DecorationBlock) {
552                blocks[insn.word(1)] = 1;
553            }
554
555            if (insn.word(2) == spv::DecorationPatch) {
556                var_patch[insn.word(1)] = 1;
557            }
558
559            if (insn.word(2) == spv::DecorationRelaxedPrecision) {
560                var_relaxed_precision[insn.word(1)] = 1;
561            }
562        }
563    }
564
565    // TODO: handle grouped decorations
566    // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
567
568    // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
569    // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
570    uint32_t word = 3;
571    while (entrypoint.word(word) & 0xff000000u) {
572        ++word;
573    }
574    ++word;
575
576    std::map<location_t, interface_var> out;
577
578    for (; word < entrypoint.len(); word++) {
579        auto insn = src->get_def(entrypoint.word(word));
580        assert(insn != src->end());
581        assert(insn.opcode() == spv::OpVariable);
582
583        if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
584            unsigned id = insn.word(2);
585            unsigned type = insn.word(1);
586
587            int location = value_or_default(var_locations, id, static_cast<unsigned>(-1));
588            int builtin = value_or_default(var_builtins, id, static_cast<unsigned>(-1));
589            unsigned component = value_or_default(var_components, id, 0);  // Unspecified is OK, is 0
590            bool is_patch = var_patch.find(id) != var_patch.end();
591            bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
592
593            if (builtin != -1) continue;
594            else if (!collect_interface_block_members(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
595                // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
596                // one result for each.
597                unsigned num_locations = get_locations_consumed_by_type(src, type, is_array_of_verts && !is_patch);
598                for (unsigned int offset = 0; offset < num_locations; offset++) {
599                    interface_var v = {};
600                    v.id = id;
601                    v.type_id = type;
602                    v.offset = offset;
603                    v.is_patch = is_patch;
604                    v.is_relaxed_precision = is_relaxed_precision;
605                    out[std::make_pair(location + offset, component)] = v;
606                }
607            }
608        }
609    }
610
611    return out;
612}
613
614static std::vector<std::pair<uint32_t, interface_var>> collect_interface_by_input_attachment_index(
615    shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
616    std::vector<std::pair<uint32_t, interface_var>> out;
617
618    for (auto insn : *src) {
619        if (insn.opcode() == spv::OpDecorate) {
620            if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
621                auto attachment_index = insn.word(3);
622                auto id = insn.word(1);
623
624                if (accessible_ids.count(id)) {
625                    auto def = src->get_def(id);
626                    assert(def != src->end());
627
628                    if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
629                        auto num_locations = get_locations_consumed_by_type(src, def.word(1), false);
630                        for (unsigned int offset = 0; offset < num_locations; offset++) {
631                            interface_var v = {};
632                            v.id = id;
633                            v.type_id = def.word(1);
634                            v.offset = offset;
635                            out.emplace_back(attachment_index + offset, v);
636                        }
637                    }
638                }
639            }
640        }
641    }
642
643    return out;
644}
645
646static std::vector<std::pair<descriptor_slot_t, interface_var>> collect_interface_by_descriptor_slot(
647    debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
648    std::unordered_map<unsigned, unsigned> var_sets;
649    std::unordered_map<unsigned, unsigned> var_bindings;
650
651    for (auto insn : *src) {
652        // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
653        // DecorationDescriptorSet and DecorationBinding.
654        if (insn.opcode() == spv::OpDecorate) {
655            if (insn.word(2) == spv::DecorationDescriptorSet) {
656                var_sets[insn.word(1)] = insn.word(3);
657            }
658
659            if (insn.word(2) == spv::DecorationBinding) {
660                var_bindings[insn.word(1)] = insn.word(3);
661            }
662        }
663    }
664
665    std::vector<std::pair<descriptor_slot_t, interface_var>> out;
666
667    for (auto id : accessible_ids) {
668        auto insn = src->get_def(id);
669        assert(insn != src->end());
670
671        if (insn.opcode() == spv::OpVariable &&
672            (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant)) {
673            unsigned set = value_or_default(var_sets, insn.word(2), 0);
674            unsigned binding = value_or_default(var_bindings, insn.word(2), 0);
675
676            interface_var v = {};
677            v.id = insn.word(2);
678            v.type_id = insn.word(1);
679            out.emplace_back(std::make_pair(set, binding), v);
680        }
681    }
682
683    return out;
684}
685
686
687
688static bool validate_vi_consistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
689    // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer.  Each binding should
690    // be specified only once.
691    std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
692    bool skip = false;
693
694    for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
695        auto desc = &vi->pVertexBindingDescriptions[i];
696        auto &binding = bindings[desc->binding];
697        if (binding) {
698            // TODO: VALIDATION_ERROR_096005cc perhaps?
699            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
700                            SHADER_CHECKER_INCONSISTENT_VI, "SC", "Duplicate vertex input binding descriptions for binding %d",
701                            desc->binding);
702        } else {
703            binding = desc;
704        }
705    }
706
707    return skip;
708}
709
710static bool validate_vi_against_vs_inputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
711                                          shader_module const *vs, spirv_inst_iter entrypoint) {
712    bool skip = false;
713
714    auto inputs = collect_interface_by_location(vs, entrypoint, spv::StorageClassInput, false);
715
716    // Build index by location
717    std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
718    if (vi) {
719        for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
720            auto num_locations = get_locations_consumed_by_format(vi->pVertexAttributeDescriptions[i].format);
721            for (auto j = 0u; j < num_locations; j++) {
722                attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
723            }
724        }
725    }
726
727    auto it_a = attribs.begin();
728    auto it_b = inputs.begin();
729    bool used = false;
730
731    while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
732        bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
733        bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
734        auto a_first = a_at_end ? 0 : it_a->first;
735        auto b_first = b_at_end ? 0 : it_b->first.first;
736        if (!a_at_end && (b_at_end || a_first < b_first)) {
737            if (!used && log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
738                                 0, __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
739                                 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
740                skip = true;
741            }
742            used = false;
743            it_a++;
744        } else if (!b_at_end && (a_at_end || b_first < a_first)) {
745            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
746                            SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Vertex shader consumes input at location %d but not provided",
747                            b_first);
748            it_b++;
749        } else {
750            unsigned attrib_type = get_format_type(it_a->second->format);
751            unsigned input_type = get_fundamental_type(vs, it_b->second.type_id);
752
753            // Type checking
754            if (!(attrib_type & input_type)) {
755                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
756                                SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
757                                "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
758                                string_VkFormat(it_a->second->format), a_first, describe_type(vs, it_b->second.type_id).c_str());
759            }
760
761            // OK!
762            used = true;
763            it_b++;
764        }
765    }
766
767    return skip;
768}
769
770static bool validate_fs_outputs_against_render_pass(debug_report_data const *report_data, shader_module const *fs,
771                                                    spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline,
772                                                    uint32_t subpass_index) {
773    auto rpci = pipeline->render_pass_ci.ptr();
774
775    std::map<uint32_t, VkFormat> color_attachments;
776    auto subpass = rpci->pSubpasses[subpass_index];
777    for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
778        uint32_t attachment = subpass.pColorAttachments[i].attachment;
779        if (attachment == VK_ATTACHMENT_UNUSED) continue;
780        if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
781            color_attachments[i] = rpci->pAttachments[attachment].format;
782        }
783    }
784
785    bool skip = false;
786
787    // TODO: dual source blend index (spv::DecIndex, zero if not provided)
788
789    auto outputs = collect_interface_by_location(fs, entrypoint, spv::StorageClassOutput, false);
790
791    auto it_a = outputs.begin();
792    auto it_b = color_attachments.begin();
793
794    // Walk attachment list and outputs together
795
796    while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
797        bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
798        bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
799
800        if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
801            skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
802                            SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
803                            "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
804            it_a++;
805        } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
806            // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
807            // shader to not produce a matching output.
808            if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
809                skip |=
810                    log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
811                            SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Attachment %d not written by fragment shader", it_b->first);
812            }
813            it_b++;
814        } else {
815            unsigned output_type = get_fundamental_type(fs, it_a->second.type_id);
816            unsigned att_type = get_format_type(it_b->second);
817
818            // Type checking
819            if (!(output_type & att_type)) {
820                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
821                                SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
822                                "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
823                                string_VkFormat(it_b->second), describe_type(fs, it_a->second.type_id).c_str());
824            }
825
826            // OK!
827            it_a++;
828            it_b++;
829        }
830    }
831
832    return skip;
833}
834
835// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
836// important for identifying the set of shader resources actually used by an entrypoint, for example.
837// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
838//  - NOT the shader input/output interfaces.
839//
840// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
841// converting parts of this to be generated from the machine-readable spec instead.
842static std::unordered_set<uint32_t> mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint) {
843    std::unordered_set<uint32_t> ids;
844    std::unordered_set<uint32_t> worklist;
845    worklist.insert(entrypoint.word(2));
846
847    while (!worklist.empty()) {
848        auto id_iter = worklist.begin();
849        auto id = *id_iter;
850        worklist.erase(id_iter);
851
852        auto insn = src->get_def(id);
853        if (insn == src->end()) {
854            // ID is something we didn't collect in build_def_index. that's OK -- we'll stumble across all kinds of things here
855            // that we may not care about.
856            continue;
857        }
858
859        // Try to add to the output set
860        if (!ids.insert(id).second) {
861            continue;  // If we already saw this id, we don't want to walk it again.
862        }
863
864        switch (insn.opcode()) {
865            case spv::OpFunction:
866                // Scan whole body of the function, enlisting anything interesting
867                while (++insn, insn.opcode() != spv::OpFunctionEnd) {
868                    switch (insn.opcode()) {
869                        case spv::OpLoad:
870                        case spv::OpAtomicLoad:
871                        case spv::OpAtomicExchange:
872                        case spv::OpAtomicCompareExchange:
873                        case spv::OpAtomicCompareExchangeWeak:
874                        case spv::OpAtomicIIncrement:
875                        case spv::OpAtomicIDecrement:
876                        case spv::OpAtomicIAdd:
877                        case spv::OpAtomicISub:
878                        case spv::OpAtomicSMin:
879                        case spv::OpAtomicUMin:
880                        case spv::OpAtomicSMax:
881                        case spv::OpAtomicUMax:
882                        case spv::OpAtomicAnd:
883                        case spv::OpAtomicOr:
884                        case spv::OpAtomicXor:
885                            worklist.insert(insn.word(3));  // ptr
886                            break;
887                        case spv::OpStore:
888                        case spv::OpAtomicStore:
889                            worklist.insert(insn.word(1));  // ptr
890                            break;
891                        case spv::OpAccessChain:
892                        case spv::OpInBoundsAccessChain:
893                            worklist.insert(insn.word(3));  // base ptr
894                            break;
895                        case spv::OpSampledImage:
896                        case spv::OpImageSampleImplicitLod:
897                        case spv::OpImageSampleExplicitLod:
898                        case spv::OpImageSampleDrefImplicitLod:
899                        case spv::OpImageSampleDrefExplicitLod:
900                        case spv::OpImageSampleProjImplicitLod:
901                        case spv::OpImageSampleProjExplicitLod:
902                        case spv::OpImageSampleProjDrefImplicitLod:
903                        case spv::OpImageSampleProjDrefExplicitLod:
904                        case spv::OpImageFetch:
905                        case spv::OpImageGather:
906                        case spv::OpImageDrefGather:
907                        case spv::OpImageRead:
908                        case spv::OpImage:
909                        case spv::OpImageQueryFormat:
910                        case spv::OpImageQueryOrder:
911                        case spv::OpImageQuerySizeLod:
912                        case spv::OpImageQuerySize:
913                        case spv::OpImageQueryLod:
914                        case spv::OpImageQueryLevels:
915                        case spv::OpImageQuerySamples:
916                        case spv::OpImageSparseSampleImplicitLod:
917                        case spv::OpImageSparseSampleExplicitLod:
918                        case spv::OpImageSparseSampleDrefImplicitLod:
919                        case spv::OpImageSparseSampleDrefExplicitLod:
920                        case spv::OpImageSparseSampleProjImplicitLod:
921                        case spv::OpImageSparseSampleProjExplicitLod:
922                        case spv::OpImageSparseSampleProjDrefImplicitLod:
923                        case spv::OpImageSparseSampleProjDrefExplicitLod:
924                        case spv::OpImageSparseFetch:
925                        case spv::OpImageSparseGather:
926                        case spv::OpImageSparseDrefGather:
927                        case spv::OpImageTexelPointer:
928                            worklist.insert(insn.word(3));  // Image or sampled image
929                            break;
930                        case spv::OpImageWrite:
931                            worklist.insert(insn.word(1));  // Image -- different operand order to above
932                            break;
933                        case spv::OpFunctionCall:
934                            for (uint32_t i = 3; i < insn.len(); i++) {
935                                worklist.insert(insn.word(i));  // fn itself, and all args
936                            }
937                            break;
938
939                        case spv::OpExtInst:
940                            for (uint32_t i = 5; i < insn.len(); i++) {
941                                worklist.insert(insn.word(i));  // Operands to ext inst
942                            }
943                            break;
944                    }
945                }
946                break;
947        }
948    }
949
950    return ids;
951}
952
953static bool validate_push_constant_block_against_pipeline(debug_report_data const *report_data,
954                                                          std::vector<VkPushConstantRange> const *push_constant_ranges,
955                                                          shader_module const *src, spirv_inst_iter type,
956                                                          VkShaderStageFlagBits stage) {
957    bool skip = false;
958
959    // Strip off ptrs etc
960    type = get_struct_type(src, type, false);
961    assert(type != src->end());
962
963    // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
964    // TODO: arrays, matrices, weird sizes
965    for (auto insn : *src) {
966        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
967            if (insn.word(3) == spv::DecorationOffset) {
968                unsigned offset = insn.word(4);
969                auto size = 4;  // Bytes; TODO: calculate this based on the type
970
971                bool found_range = false;
972                for (auto const &range : *push_constant_ranges) {
973                    if (range.offset <= offset && range.offset + range.size >= offset + size) {
974                        found_range = true;
975
976                        if ((range.stageFlags & stage) == 0) {
977                            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
978                                            __LINE__, SHADER_CHECKER_PUSH_CONSTANT_NOT_ACCESSIBLE_FROM_STAGE, "SC",
979                                            "Push constant range covering variable starting at "
980                                                "offset %u not accessible from stage %s",
981                                            offset, string_VkShaderStageFlagBits(stage));
982                        }
983
984                        break;
985                    }
986                }
987
988                if (!found_range) {
989                    skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
990                                    __LINE__, SHADER_CHECKER_PUSH_CONSTANT_OUT_OF_RANGE, "SC",
991                                    "Push constant range covering variable starting at "
992                                        "offset %u not declared in layout",
993                                    offset);
994                }
995            }
996        }
997    }
998
999    return skip;
1000}
1001
1002static bool validate_push_constant_usage(debug_report_data const *report_data,
1003                                         std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1004                                         std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
1005    bool skip = false;
1006
1007    for (auto id : accessible_ids) {
1008        auto def_insn = src->get_def(id);
1009        if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1010            skip |= validate_push_constant_block_against_pipeline(report_data, push_constant_ranges, src,
1011                                                                  src->get_def(def_insn.word(1)), stage);
1012        }
1013    }
1014
1015    return skip;
1016}
1017
1018// Validate that data for each specialization entry is fully contained within the buffer.
1019static bool validate_specialization_offsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
1020    bool skip = false;
1021
1022    VkSpecializationInfo const *spec = info->pSpecializationInfo;
1023
1024    if (spec) {
1025        for (auto i = 0u; i < spec->mapEntryCount; i++) {
1026            // TODO: This is a good place for VALIDATION_ERROR_1360060a.
1027            if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
1028                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1029                                VALIDATION_ERROR_1360060c, "SC",
1030                                "Specialization entry %u (for constant id %u) references memory outside provided "
1031                                    "specialization data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER
1032                " bytes provided). %s.",
1033                    i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1034                    spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize,
1035                    validation_error_map[VALIDATION_ERROR_1360060c]);
1036            }
1037        }
1038    }
1039
1040    return skip;
1041}
1042
1043static bool descriptor_type_match(shader_module const *module, uint32_t type_id, VkDescriptorType descriptor_type,
1044                                  unsigned &descriptor_count) {
1045    auto type = module->get_def(type_id);
1046
1047    descriptor_count = 1;
1048
1049    // Strip off any array or ptrs. Where we remove array levels, adjust the  descriptor count for each dimension.
1050    while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
1051        if (type.opcode() == spv::OpTypeArray) {
1052            descriptor_count *= get_constant_value(module, type.word(3));
1053            type = module->get_def(type.word(2));
1054        } else {
1055            type = module->get_def(type.word(3));
1056        }
1057    }
1058
1059    switch (type.opcode()) {
1060        case spv::OpTypeStruct: {
1061            for (auto insn : *module) {
1062                if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1063                    if (insn.word(2) == spv::DecorationBlock) {
1064                        return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
1065                            descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1066                    } else if (insn.word(2) == spv::DecorationBufferBlock) {
1067                        return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
1068                            descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
1069                    }
1070                }
1071            }
1072
1073            // Invalid
1074            return false;
1075        }
1076
1077        case spv::OpTypeSampler:
1078            return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER || descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1079
1080        case spv::OpTypeSampledImage:
1081            if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
1082                // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1083                // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1084                auto image_type = module->get_def(type.word(2));
1085                auto dim = image_type.word(3);
1086                auto sampled = image_type.word(7);
1087                return dim == spv::DimBuffer && sampled == 1;
1088            }
1089            return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1090
1091        case spv::OpTypeImage: {
1092            // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1093            // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1094            auto dim = type.word(3);
1095            auto sampled = type.word(7);
1096
1097            if (dim == spv::DimSubpassData) {
1098                return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
1099            } else if (dim == spv::DimBuffer) {
1100                if (sampled == 1) {
1101                    return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
1102                } else {
1103                    return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1104                }
1105            } else if (sampled == 1) {
1106                return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
1107                    descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1108            } else {
1109                return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
1110            }
1111        }
1112
1113            // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1114        default:
1115            return false;  // Mismatch
1116    }
1117}
1118
1119static bool require_feature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
1120    if (!feature) {
1121        if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1122                    SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
1123                    "Shader requires VkPhysicalDeviceFeatures::%s but is not "
1124                        "enabled on the device",
1125                    feature_name)) {
1126            return true;
1127        }
1128    }
1129
1130    return false;
1131}
1132
1133static bool require_extension(debug_report_data const *report_data, bool extension, char const *extension_name) {
1134    if (!extension) {
1135        if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1136                    SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
1137                    "Shader requires extension %s but is not "
1138                        "enabled on the device",
1139                    extension_name)) {
1140            return true;
1141        }
1142    }
1143
1144    return false;
1145}
1146
1147static bool validate_shader_capabilities(layer_data *dev_data, shader_module const *src) {
1148    bool skip = false;
1149
1150    auto report_data = GetReportData(dev_data);
1151    auto const & enabledFeatures = GetEnabledFeatures(dev_data);
1152    auto const & extensions = GetEnabledExtensions(dev_data);
1153
1154    struct CapabilityInfo {
1155        char const *name;
1156        VkBool32 const VkPhysicalDeviceFeatures::*feature;
1157        bool const DeviceExtensions::*extension;
1158    };
1159
1160    using F = VkPhysicalDeviceFeatures;
1161    using E = DeviceExtensions;
1162
1163    // clang-format off
1164    static const std::unordered_map<uint32_t, CapabilityInfo> capabilities = {
1165        // Capabilities always supported by a Vulkan 1.0 implementation -- no
1166        // feature bits.
1167        {spv::CapabilityMatrix, {nullptr}},
1168        {spv::CapabilityShader, {nullptr}},
1169        {spv::CapabilityInputAttachment, {nullptr}},
1170        {spv::CapabilitySampled1D, {nullptr}},
1171        {spv::CapabilityImage1D, {nullptr}},
1172        {spv::CapabilitySampledBuffer, {nullptr}},
1173        {spv::CapabilityImageQuery, {nullptr}},
1174        {spv::CapabilityDerivativeControl, {nullptr}},
1175
1176        // Capabilities that are optionally supported, but require a feature to
1177        // be enabled on the device
1178        {spv::CapabilityGeometry, {"geometryShader", &F::geometryShader}},
1179        {spv::CapabilityTessellation, {"tessellationShader", &F::tessellationShader}},
1180        {spv::CapabilityFloat64, {"shaderFloat64", &F::shaderFloat64}},
1181        {spv::CapabilityInt64, {"shaderInt64", &F::shaderInt64}},
1182        {spv::CapabilityTessellationPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1183        {spv::CapabilityGeometryPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1184        {spv::CapabilityImageGatherExtended, {"shaderImageGatherExtended", &F::shaderImageGatherExtended}},
1185        {spv::CapabilityStorageImageMultisample, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1186        {spv::CapabilityUniformBufferArrayDynamicIndexing, {"shaderUniformBufferArrayDynamicIndexing", &F::shaderUniformBufferArrayDynamicIndexing}},
1187        {spv::CapabilitySampledImageArrayDynamicIndexing, {"shaderSampledImageArrayDynamicIndexing", &F::shaderSampledImageArrayDynamicIndexing}},
1188        {spv::CapabilityStorageBufferArrayDynamicIndexing, {"shaderStorageBufferArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1189        {spv::CapabilityStorageImageArrayDynamicIndexing, {"shaderStorageImageArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1190        {spv::CapabilityClipDistance, {"shaderClipDistance", &F::shaderClipDistance}},
1191        {spv::CapabilityCullDistance, {"shaderCullDistance", &F::shaderCullDistance}},
1192        {spv::CapabilityImageCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1193        {spv::CapabilitySampleRateShading, {"sampleRateShading", &F::sampleRateShading}},
1194        {spv::CapabilitySparseResidency, {"shaderResourceResidency", &F::shaderResourceResidency}},
1195        {spv::CapabilityMinLod, {"shaderResourceMinLod", &F::shaderResourceMinLod}},
1196        {spv::CapabilitySampledCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1197        {spv::CapabilityImageMSArray, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1198        {spv::CapabilityStorageImageExtendedFormats, {"shaderStorageImageExtendedFormats", &F::shaderStorageImageExtendedFormats}},
1199        {spv::CapabilityInterpolationFunction, {"sampleRateShading", &F::sampleRateShading}},
1200        {spv::CapabilityStorageImageReadWithoutFormat, {"shaderStorageImageReadWithoutFormat", &F::shaderStorageImageReadWithoutFormat}},
1201        {spv::CapabilityStorageImageWriteWithoutFormat, {"shaderStorageImageWriteWithoutFormat", &F::shaderStorageImageWriteWithoutFormat}},
1202        {spv::CapabilityMultiViewport, {"multiViewport", &F::multiViewport}},
1203
1204        // Capabilities that require an extension
1205        {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &E::vk_khr_shader_draw_parameters}},
1206        {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &E::vk_nv_geometry_shader_passthrough}},
1207        {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &E::vk_nv_sample_mask_override_coverage}},
1208        {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1209        {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1210        {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_ballot }},
1211        {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_vote }},
1212    };
1213    // clang-format on
1214
1215    for (auto insn : *src) {
1216        if (insn.opcode() == spv::OpCapability) {
1217            auto it = capabilities.find(insn.word(1));
1218            if (it != capabilities.end()) {
1219                if (it->second.feature) {
1220                    skip |= require_feature(report_data, enabledFeatures->*(it->second.feature), it->second.name);
1221                }
1222                if (it->second.extension) {
1223                    skip |= require_extension(report_data, extensions->*(it->second.extension), it->second.name);
1224                }
1225            }
1226        }
1227    }
1228
1229    return skip;
1230}
1231
1232static uint32_t descriptor_type_to_reqs(shader_module const *module, uint32_t type_id) {
1233    auto type = module->get_def(type_id);
1234
1235    while (true) {
1236        switch (type.opcode()) {
1237            case spv::OpTypeArray:
1238            case spv::OpTypeSampledImage:
1239                type = module->get_def(type.word(2));
1240                break;
1241            case spv::OpTypePointer:
1242                type = module->get_def(type.word(3));
1243                break;
1244            case spv::OpTypeImage: {
1245                auto dim = type.word(3);
1246                auto arrayed = type.word(5);
1247                auto msaa = type.word(6);
1248
1249                switch (dim) {
1250                    case spv::Dim1D:
1251                        return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1252                    case spv::Dim2D:
1253                        return (msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE) |
1254                            (arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D);
1255                    case spv::Dim3D:
1256                        return DESCRIPTOR_REQ_VIEW_TYPE_3D;
1257                    case spv::DimCube:
1258                        return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1259                    case spv::DimSubpassData:
1260                        return msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1261                    default:  // buffer, etc.
1262                        return 0;
1263                }
1264            }
1265            default:
1266                return 0;
1267        }
1268    }
1269}
1270
1271// For given pipelineLayout verify that the set_layout_node at slot.first
1272//  has the requested binding at slot.second and return ptr to that binding
1273static VkDescriptorSetLayoutBinding const *get_descriptor_binding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1274                                                                  descriptor_slot_t slot) {
1275    if (!pipelineLayout) return nullptr;
1276
1277    if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1278
1279    return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1280}
1281
1282
1283static bool validate_pipeline_shader_stage(
1284    layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
1285    shader_module const **out_module, spirv_inst_iter *out_entrypoint) {
1286    bool skip = false;
1287    auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1288    auto report_data = GetReportData(dev_data);
1289
1290    if (!module->has_valid_spirv) return false;
1291
1292    // Find the entrypoint
1293    auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
1294    if (entrypoint == module->end()) {
1295        if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1296                    VALIDATION_ERROR_10600586, "SC", "No entrypoint found named `%s` for stage %s. %s.", pStage->pName,
1297                    string_VkShaderStageFlagBits(pStage->stage), validation_error_map[VALIDATION_ERROR_10600586])) {
1298            return true;  // no point continuing beyond here, any analysis is just going to be garbage.
1299        }
1300    }
1301
1302    // Validate shader capabilities against enabled device features
1303    skip |= validate_shader_capabilities(dev_data, module);
1304
1305    // Mark accessible ids
1306    auto accessible_ids = mark_accessible_ids(module, entrypoint);
1307
1308    // Validate descriptor set layout against what the entrypoint actually uses
1309    auto descriptor_uses = collect_interface_by_descriptor_slot(report_data, module, accessible_ids);
1310
1311    skip |= validate_specialization_offsets(report_data, pStage);
1312    skip |= validate_push_constant_usage(report_data, &pipeline->pipeline_layout.push_constant_ranges, module, accessible_ids, pStage->stage);
1313
1314    // Validate descriptor use
1315    for (auto use : descriptor_uses) {
1316        // While validating shaders capture which slots are used by the pipeline
1317        auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
1318        reqs = descriptor_req(reqs | descriptor_type_to_reqs(module, use.second.type_id));
1319
1320        // Verify given pipelineLayout has requested setLayout with requested binding
1321        const auto &binding = get_descriptor_binding(&pipeline->pipeline_layout, use.first);
1322        unsigned required_descriptor_count;
1323
1324        if (!binding) {
1325            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1326                            SHADER_CHECKER_MISSING_DESCRIPTOR, "SC",
1327                            "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
1328                            use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str());
1329        } else if (~binding->stageFlags & pStage->stage) {
1330            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1331                            SHADER_CHECKER_DESCRIPTOR_NOT_ACCESSIBLE_FROM_STAGE, "SC",
1332                            "Shader uses descriptor slot %u.%u (used "
1333                                "as type `%s`) but descriptor not "
1334                                "accessible from stage %s",
1335                            use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1336                            string_VkShaderStageFlagBits(pStage->stage));
1337        } else if (!descriptor_type_match(module, use.second.type_id, binding->descriptorType, required_descriptor_count)) {
1338            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1339                            SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1340                            "Type mismatch on descriptor slot "
1341                                "%u.%u (used as type `%s`) but "
1342                                "descriptor of type %s",
1343                            use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1344                            string_VkDescriptorType(binding->descriptorType));
1345        } else if (binding->descriptorCount < required_descriptor_count) {
1346            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1347                            SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1348                            "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
1349                            required_descriptor_count, use.first.first, use.first.second,
1350                            describe_type(module, use.second.type_id).c_str(), binding->descriptorCount);
1351        }
1352    }
1353
1354    // Validate use of input attachments against subpass structure
1355    if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1356        auto input_attachment_uses = collect_interface_by_input_attachment_index(module, accessible_ids);
1357
1358        auto rpci = pipeline->render_pass_ci.ptr();
1359        auto subpass = pipeline->graphicsPipelineCI.subpass;
1360
1361        for (auto use : input_attachment_uses) {
1362            auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1363            auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
1364                         ? input_attachments[use.first].attachment
1365                         : VK_ATTACHMENT_UNUSED;
1366
1367            if (index == VK_ATTACHMENT_UNUSED) {
1368                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1369                                SHADER_CHECKER_MISSING_INPUT_ATTACHMENT, "SC",
1370                                "Shader consumes input attachment index %d but not provided in subpass", use.first);
1371            } else if (!(get_format_type(rpci->pAttachments[index].format) & get_fundamental_type(module, use.second.type_id))) {
1372                skip |=
1373                    log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1374                            SHADER_CHECKER_INPUT_ATTACHMENT_TYPE_MISMATCH, "SC",
1375                            "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
1376                            string_VkFormat(rpci->pAttachments[index].format), describe_type(module, use.second.type_id).c_str());
1377            }
1378        }
1379    }
1380
1381    return skip;
1382}
1383
1384static bool validate_interface_between_stages(debug_report_data const *report_data, shader_module const *producer,
1385                                              spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1386                                              shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1387                                              shader_stage_attributes const *consumer_stage) {
1388    bool skip = false;
1389
1390    auto outputs =
1391        collect_interface_by_location(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1392    auto inputs =
1393        collect_interface_by_location(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
1394
1395    auto a_it = outputs.begin();
1396    auto b_it = inputs.begin();
1397
1398    // Maps sorted by key (location); walk them together to find mismatches
1399    while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1400        bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1401        bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1402        auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1403        auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1404
1405        if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
1406            skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1407                            __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1408                            "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1409                            a_first.second, consumer_stage->name);
1410            a_it++;
1411        } else if (a_at_end || a_first > b_first) {
1412            skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1413                            SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "%s consumes input location %u.%u which is not written by %s",
1414                            consumer_stage->name, b_first.first, b_first.second, producer_stage->name);
1415            b_it++;
1416        } else {
1417            // subtleties of arrayed interfaces:
1418            // - if is_patch, then the member is not arrayed, even though the interface may be.
1419            // - if is_block_member, then the extra array level of an arrayed interface is not
1420            //   expressed in the member type -- it's expressed in the block type.
1421            if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1422                             producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1423                             consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
1424                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1425                                SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC", "Type mismatch on location %u.%u: '%s' vs '%s'",
1426                                a_first.first, a_first.second, describe_type(producer, a_it->second.type_id).c_str(),
1427                                describe_type(consumer, b_it->second.type_id).c_str());
1428            }
1429            if (a_it->second.is_patch != b_it->second.is_patch) {
1430                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1431                                SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1432                                "Decoration mismatch on location %u.%u: is per-%s in %s stage but "
1433                                    "per-%s in %s stage",
1434                                a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1435                                b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1436            }
1437            if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
1438                skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1439                                SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1440                                "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1441                                a_first.second, producer_stage->name, consumer_stage->name);
1442            }
1443            a_it++;
1444            b_it++;
1445        }
1446    }
1447
1448    return skip;
1449}
1450
1451// Validate that the shaders used by the given pipeline and store the active_slots
1452//  that are actually used by the pipeline into pPipeline->active_slots
1453bool validate_and_capture_pipeline_shader_state(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1454    auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
1455    int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1456    int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
1457    auto report_data = GetReportData(dev_data);
1458
1459    shader_module const *shaders[5];
1460    memset(shaders, 0, sizeof(shaders));
1461    spirv_inst_iter entrypoints[5];
1462    memset(entrypoints, 0, sizeof(entrypoints));
1463    bool skip = false;
1464
1465    for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1466        auto pStage = &pCreateInfo->pStages[i];
1467        auto stage_id = get_shader_stage_id(pStage->stage);
1468        skip |= validate_pipeline_shader_stage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id]);
1469    }
1470
1471    // if the shader stages are no good individually, cross-stage validation is pointless.
1472    if (skip) return true;
1473
1474    auto vi = pCreateInfo->pVertexInputState;
1475
1476    if (vi) {
1477        skip |= validate_vi_consistency(report_data, vi);
1478    }
1479
1480    if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
1481        skip |= validate_vi_against_vs_inputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
1482    }
1483
1484    int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1485    int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
1486
1487    while (!shaders[producer] && producer != fragment_stage) {
1488        producer++;
1489        consumer++;
1490    }
1491
1492    for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1493        assert(shaders[producer]);
1494        if (shaders[consumer] && shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
1495            skip |= validate_interface_between_stages(report_data, shaders[producer], entrypoints[producer],
1496                                                      &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1497                                                      &shader_stage_attribs[consumer]);
1498
1499            producer = consumer;
1500        }
1501    }
1502
1503    if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
1504        skip |= validate_fs_outputs_against_render_pass(report_data, shaders[fragment_stage], entrypoints[fragment_stage],
1505                                                        pipeline, pCreateInfo->subpass);
1506    }
1507
1508    return skip;
1509}
1510
1511bool validate_compute_pipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1512    auto pCreateInfo = pipeline->computePipelineCI.ptr();
1513
1514    shader_module const *module;
1515    spirv_inst_iter entrypoint;
1516
1517    return validate_pipeline_shader_stage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint);
1518}
1519
1520bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1521    bool skip = false;
1522    spv_result_t spv_valid = SPV_SUCCESS;
1523    auto report_data = GetReportData(dev_data);
1524
1525    if (GetDisables(dev_data)->shader_validation) {
1526        return false;
1527    }
1528
1529    auto have_glsl_shader = GetEnabledExtensions(dev_data)->vk_nv_glsl_shader;
1530
1531    if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
1532        skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1533                        __LINE__, VALIDATION_ERROR_12a00ac0, "SC",
1534                        "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ". %s",
1535                        pCreateInfo->codeSize, validation_error_map[VALIDATION_ERROR_12a00ac0]);
1536    } else {
1537        // Use SPIRV-Tools validator to try and catch any issues with the module itself
1538        spv_context ctx = spvContextCreate(SPV_ENV_VULKAN_1_0);
1539        spv_const_binary_t binary{ pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t) };
1540        spv_diagnostic diag = nullptr;
1541
1542        spv_valid = spvValidate(ctx, &binary, &diag);
1543        if (spv_valid != SPV_SUCCESS) {
1544            if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
1545                skip |= log_msg(report_data,
1546                                spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
1547                                VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__, SHADER_CHECKER_INCONSISTENT_SPIRV, "SC",
1548                                "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
1549            }
1550        }
1551
1552        spvDiagnosticDestroy(diag);
1553        spvContextDestroy(ctx);
1554    }
1555
1556    *spirv_valid = (spv_valid == SPV_SUCCESS);
1557    return skip;
1558}
1559