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