blob: fab1e8891a42c80b02d0415d46c5df0fe32c0c4b [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"
Chris Forbes4ae55b32017-06-09 14:42:56 -070037#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070038#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039
40enum FORMAT_TYPE {
41 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
42 FORMAT_TYPE_SINT = 2,
43 FORMAT_TYPE_UINT = 4,
44};
45
46typedef std::pair<unsigned, unsigned> location_t;
47
48struct interface_var {
49 uint32_t id;
50 uint32_t type_id;
51 uint32_t offset;
52 bool is_patch;
53 bool is_block_member;
54 bool is_relaxed_precision;
55 // TODO: collect the name, too? Isn't required to be present.
56};
57
58struct shader_stage_attributes {
59 char const *const name;
60 bool arrayed_input;
61 bool arrayed_output;
62};
63
64static shader_stage_attributes shader_stage_attribs[] = {
65 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
66 {"geometry shader", true, false}, {"fragment shader", false, false},
67};
68
69// SPIRV utility functions
70void shader_module::build_def_index() {
71 for (auto insn : *this) {
72 switch (insn.opcode()) {
73 // Types
74 case spv::OpTypeVoid:
75 case spv::OpTypeBool:
76 case spv::OpTypeInt:
77 case spv::OpTypeFloat:
78 case spv::OpTypeVector:
79 case spv::OpTypeMatrix:
80 case spv::OpTypeImage:
81 case spv::OpTypeSampler:
82 case spv::OpTypeSampledImage:
83 case spv::OpTypeArray:
84 case spv::OpTypeRuntimeArray:
85 case spv::OpTypeStruct:
86 case spv::OpTypeOpaque:
87 case spv::OpTypePointer:
88 case spv::OpTypeFunction:
89 case spv::OpTypeEvent:
90 case spv::OpTypeDeviceEvent:
91 case spv::OpTypeReserveId:
92 case spv::OpTypeQueue:
93 case spv::OpTypePipe:
94 def_index[insn.word(1)] = insn.offset();
95 break;
96
97 // Fixed constants
98 case spv::OpConstantTrue:
99 case spv::OpConstantFalse:
100 case spv::OpConstant:
101 case spv::OpConstantComposite:
102 case spv::OpConstantSampler:
103 case spv::OpConstantNull:
104 def_index[insn.word(2)] = insn.offset();
105 break;
106
107 // Specialization constants
108 case spv::OpSpecConstantTrue:
109 case spv::OpSpecConstantFalse:
110 case spv::OpSpecConstant:
111 case spv::OpSpecConstantComposite:
112 case spv::OpSpecConstantOp:
113 def_index[insn.word(2)] = insn.offset();
114 break;
115
116 // Variables
117 case spv::OpVariable:
118 def_index[insn.word(2)] = insn.offset();
119 break;
120
121 // Functions
122 case spv::OpFunction:
123 def_index[insn.word(2)] = insn.offset();
124 break;
125
126 default:
127 // We don't care about any other defs for now.
128 break;
129 }
130 }
131}
132
133static spirv_inst_iter find_entrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
134 for (auto insn : *src) {
135 if (insn.opcode() == spv::OpEntryPoint) {
136 auto entrypointName = (char const *)&insn.word(3);
137 auto entrypointStageBits = 1u << insn.word(1);
138
139 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
140 return insn;
141 }
142 }
143 }
144
145 return src->end();
146}
147
148static char const *storage_class_name(unsigned sc) {
149 switch (sc) {
150 case spv::StorageClassInput:
151 return "input";
152 case spv::StorageClassOutput:
153 return "output";
154 case spv::StorageClassUniformConstant:
155 return "const uniform";
156 case spv::StorageClassUniform:
157 return "uniform";
158 case spv::StorageClassWorkgroup:
159 return "workgroup local";
160 case spv::StorageClassCrossWorkgroup:
161 return "workgroup global";
162 case spv::StorageClassPrivate:
163 return "private global";
164 case spv::StorageClassFunction:
165 return "function";
166 case spv::StorageClassGeneric:
167 return "generic";
168 case spv::StorageClassAtomicCounter:
169 return "atomic counter";
170 case spv::StorageClassImage:
171 return "image";
172 case spv::StorageClassPushConstant:
173 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800174 case spv::StorageClassStorageBuffer:
175 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700176 default:
177 return "unknown";
178 }
179}
180
181// Get the value of an integral constant
182unsigned get_constant_value(shader_module const *src, unsigned id) {
183 auto value = src->get_def(id);
184 assert(value != src->end());
185
186 if (value.opcode() != spv::OpConstant) {
187 // TODO: Either ensure that the specialization transform is already performed on a module we're
188 // considering here, OR -- specialize on the fly now.
189 return 1;
190 }
191
192 return value.word(3);
193}
194
195static void describe_type_inner(std::ostringstream &ss, shader_module const *src, unsigned type) {
196 auto insn = src->get_def(type);
197 assert(insn != src->end());
198
199 switch (insn.opcode()) {
200 case spv::OpTypeBool:
201 ss << "bool";
202 break;
203 case spv::OpTypeInt:
204 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
205 break;
206 case spv::OpTypeFloat:
207 ss << "float" << insn.word(2);
208 break;
209 case spv::OpTypeVector:
210 ss << "vec" << insn.word(3) << " of ";
211 describe_type_inner(ss, src, insn.word(2));
212 break;
213 case spv::OpTypeMatrix:
214 ss << "mat" << insn.word(3) << " of ";
215 describe_type_inner(ss, src, insn.word(2));
216 break;
217 case spv::OpTypeArray:
218 ss << "arr[" << get_constant_value(src, insn.word(3)) << "] of ";
219 describe_type_inner(ss, src, insn.word(2));
220 break;
221 case spv::OpTypePointer:
222 ss << "ptr to " << storage_class_name(insn.word(2)) << " ";
223 describe_type_inner(ss, src, insn.word(3));
224 break;
225 case spv::OpTypeStruct: {
226 ss << "struct of (";
227 for (unsigned i = 2; i < insn.len(); i++) {
228 describe_type_inner(ss, src, insn.word(i));
229 if (i == insn.len() - 1) {
230 ss << ")";
231 } else {
232 ss << ", ";
233 }
234 }
235 break;
236 }
237 case spv::OpTypeSampler:
238 ss << "sampler";
239 break;
240 case spv::OpTypeSampledImage:
241 ss << "sampler+";
242 describe_type_inner(ss, src, insn.word(2));
243 break;
244 case spv::OpTypeImage:
245 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
246 break;
247 default:
248 ss << "oddtype";
249 break;
250 }
251}
252
253static std::string describe_type(shader_module const *src, unsigned type) {
254 std::ostringstream ss;
255 describe_type_inner(ss, src, type);
256 return ss.str();
257}
258
259static bool is_narrow_numeric_type(spirv_inst_iter type) {
260 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
261 return type.word(2) < 64;
262}
263
264static bool types_match(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
265 bool b_arrayed, bool relaxed) {
266 // Walk two type trees together, and complain about differences
267 auto a_insn = a->get_def(a_type);
268 auto b_insn = b->get_def(b_type);
269 assert(a_insn != a->end());
270 assert(b_insn != b->end());
271
272 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
273 return types_match(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
274 }
275
276 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
277 // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
278 return types_match(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
279 }
280
281 if (a_insn.opcode() == spv::OpTypeVector && relaxed && is_narrow_numeric_type(b_insn)) {
282 return types_match(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
283 }
284
285 if (a_insn.opcode() != b_insn.opcode()) {
286 return false;
287 }
288
289 if (a_insn.opcode() == spv::OpTypePointer) {
290 // Match on pointee type. storage class is expected to differ
291 return types_match(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
292 }
293
294 if (a_arrayed || b_arrayed) {
295 // If we havent resolved array-of-verts by here, we're not going to.
296 return false;
297 }
298
299 switch (a_insn.opcode()) {
300 case spv::OpTypeBool:
301 return true;
302 case spv::OpTypeInt:
303 // Match on width, signedness
304 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
305 case spv::OpTypeFloat:
306 // Match on width
307 return a_insn.word(2) == b_insn.word(2);
308 case spv::OpTypeVector:
309 // Match on element type, count.
310 if (!types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
311 if (relaxed && is_narrow_numeric_type(a->get_def(a_insn.word(2)))) {
312 return a_insn.word(3) >= b_insn.word(3);
313 } else {
314 return a_insn.word(3) == b_insn.word(3);
315 }
316 case spv::OpTypeMatrix:
317 // Match on element type, count.
318 return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700319 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700320 case spv::OpTypeArray:
321 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
322 // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
323 return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700324 get_constant_value(a, a_insn.word(3)) == get_constant_value(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700325 case spv::OpTypeStruct:
326 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700327 {
328 if (a_insn.len() != b_insn.len()) {
329 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700330 }
Chris Forbes47567b72017-06-09 12:09:45 -0700331
Dave Houltona9df0ce2018-02-07 10:51:23 -0700332 for (unsigned i = 2; i < a_insn.len(); i++) {
333 if (!types_match(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
334 return false;
335 }
336 }
337
338 return true;
339 }
Chris Forbes47567b72017-06-09 12:09:45 -0700340 default:
341 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
342 return false;
343 }
344}
345
346static unsigned value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
347 auto it = map.find(id);
348 if (it == map.end())
349 return def;
350 else
351 return it->second;
352}
353
354static unsigned get_locations_consumed_by_type(shader_module const *src, unsigned type, bool strip_array_level) {
355 auto insn = src->get_def(type);
356 assert(insn != src->end());
357
358 switch (insn.opcode()) {
359 case spv::OpTypePointer:
360 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
361 // pointers around.
362 return get_locations_consumed_by_type(src, insn.word(3), strip_array_level);
363 case spv::OpTypeArray:
364 if (strip_array_level) {
365 return get_locations_consumed_by_type(src, insn.word(2), false);
366 } else {
367 return get_constant_value(src, insn.word(3)) * get_locations_consumed_by_type(src, insn.word(2), false);
368 }
369 case spv::OpTypeMatrix:
370 // Num locations is the dimension * element size
371 return insn.word(3) * get_locations_consumed_by_type(src, insn.word(2), false);
372 case spv::OpTypeVector: {
373 auto scalar_type = src->get_def(insn.word(2));
374 auto bit_width =
375 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
376
377 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
378 return (bit_width * insn.word(3) + 127) / 128;
379 }
380 default:
381 // Everything else is just 1.
382 return 1;
383
384 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
385 }
386}
387
388static unsigned get_locations_consumed_by_format(VkFormat format) {
389 switch (format) {
390 case VK_FORMAT_R64G64B64A64_SFLOAT:
391 case VK_FORMAT_R64G64B64A64_SINT:
392 case VK_FORMAT_R64G64B64A64_UINT:
393 case VK_FORMAT_R64G64B64_SFLOAT:
394 case VK_FORMAT_R64G64B64_SINT:
395 case VK_FORMAT_R64G64B64_UINT:
396 return 2;
397 default:
398 return 1;
399 }
400}
401
402static unsigned get_format_type(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700403 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
404 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
405 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
406 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700407 // 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
Chris Forbesa313d772017-06-13 13:59:41 -0700457static bool collect_interface_block_members(shader_module const *src, std::map<location_t, interface_var> *out,
Chris Forbes47567b72017-06-09 12:09:45 -0700458 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts,
Chris Forbesa313d772017-06-13 13:59:41 -0700459 uint32_t id, uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700460 // 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.
Chris Forbesa313d772017-06-13 13:59:41 -0700464 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700465 }
466
467 std::unordered_map<unsigned, unsigned> member_components;
468 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700469 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700470
471 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
472 for (auto insn : *src) {
473 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
474 unsigned member_index = insn.word(2);
475
476 if (insn.word(3) == spv::DecorationComponent) {
477 unsigned component = insn.word(4);
478 member_components[member_index] = component;
479 }
480
481 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
482 member_relaxed_precision[member_index] = 1;
483 }
Chris Forbesa313d772017-06-13 13:59:41 -0700484
485 if (insn.word(3) == spv::DecorationPatch) {
486 member_patch[member_index] = 1;
487 }
Chris Forbes47567b72017-06-09 12:09:45 -0700488 }
489 }
490
Chris Forbesa313d772017-06-13 13:59:41 -0700491 // TODO: correctly handle location assignment from outside
492
Chris Forbes47567b72017-06-09 12:09:45 -0700493 // Second pass -- produce the output, from Location decorations
494 for (auto insn : *src) {
495 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
496 unsigned member_index = insn.word(2);
497 unsigned member_type_id = type.word(2 + member_index);
498
499 if (insn.word(3) == spv::DecorationLocation) {
500 unsigned location = insn.word(4);
501 unsigned num_locations = get_locations_consumed_by_type(src, member_type_id, false);
502 auto component_it = member_components.find(member_index);
503 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
504 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700505 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700506
507 for (unsigned int offset = 0; offset < num_locations; offset++) {
508 interface_var v = {};
509 v.id = id;
510 // TODO: member index in interface_var too?
511 v.type_id = member_type_id;
512 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700513 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700514 v.is_block_member = true;
515 v.is_relaxed_precision = is_relaxed_precision;
516 (*out)[std::make_pair(location + offset, component)] = v;
517 }
518 }
519 }
520 }
Chris Forbesa313d772017-06-13 13:59:41 -0700521
522 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700523}
524
525static std::map<location_t, interface_var> collect_interface_by_location(shader_module const *src, spirv_inst_iter entrypoint,
526 spv::StorageClass sinterface, bool is_array_of_verts) {
527 std::unordered_map<unsigned, unsigned> var_locations;
528 std::unordered_map<unsigned, unsigned> var_builtins;
529 std::unordered_map<unsigned, unsigned> var_components;
530 std::unordered_map<unsigned, unsigned> blocks;
531 std::unordered_map<unsigned, unsigned> var_patch;
532 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
533
534 for (auto insn : *src) {
535 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
536 // fits neither model.
537 if (insn.opcode() == spv::OpDecorate) {
538 if (insn.word(2) == spv::DecorationLocation) {
539 var_locations[insn.word(1)] = insn.word(3);
540 }
541
542 if (insn.word(2) == spv::DecorationBuiltIn) {
543 var_builtins[insn.word(1)] = insn.word(3);
544 }
545
546 if (insn.word(2) == spv::DecorationComponent) {
547 var_components[insn.word(1)] = insn.word(3);
548 }
549
550 if (insn.word(2) == spv::DecorationBlock) {
551 blocks[insn.word(1)] = 1;
552 }
553
554 if (insn.word(2) == spv::DecorationPatch) {
555 var_patch[insn.word(1)] = 1;
556 }
557
558 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
559 var_relaxed_precision[insn.word(1)] = 1;
560 }
561 }
562 }
563
564 // TODO: handle grouped decorations
565 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
566
567 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
568 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
569 uint32_t word = 3;
570 while (entrypoint.word(word) & 0xff000000u) {
571 ++word;
572 }
573 ++word;
574
575 std::map<location_t, interface_var> out;
576
577 for (; word < entrypoint.len(); word++) {
578 auto insn = src->get_def(entrypoint.word(word));
579 assert(insn != src->end());
580 assert(insn.opcode() == spv::OpVariable);
581
582 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
583 unsigned id = insn.word(2);
584 unsigned type = insn.word(1);
585
Jamie Madill061d1112017-11-08 16:25:22 -0500586 int location = value_or_default(var_locations, id, static_cast<unsigned>(-1));
587 int builtin = value_or_default(var_builtins, id, static_cast<unsigned>(-1));
Chris Forbes47567b72017-06-09 12:09:45 -0700588 unsigned component = value_or_default(var_components, id, 0); // Unspecified is OK, is 0
589 bool is_patch = var_patch.find(id) != var_patch.end();
590 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
591
Dave Houltona9df0ce2018-02-07 10:51:23 -0700592 if (builtin != -1)
593 continue;
Chris Forbesa313d772017-06-13 13:59:41 -0700594 else if (!collect_interface_block_members(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700595 // 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 }
Chris Forbes47567b72017-06-09 12:09:45 -0700607 }
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
Chris Forbes8af24522018-03-07 11:37:45 -0800646static bool is_writable_descriptor_type(shader_module const *module, uint32_t type_id) {
647 auto type = module->get_def(type_id);
648
649 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
650 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
651 if (type.opcode() == spv::OpTypeArray) {
652 type = module->get_def(type.word(2));
653 } else {
654 type = module->get_def(type.word(3));
655 }
656 }
657
658 switch (type.opcode()) {
659 case spv::OpTypeImage: {
660 auto dim = type.word(3);
661 auto sampled = type.word(7);
662 return sampled == 2 && dim != spv::DimSubpassData;
663 }
664
665 case spv::OpTypeStruct:
666 for (auto insn : *module) {
667 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
668 if (insn.word(2) == spv::DecorationBufferBlock) {
669 return true;
670 }
671 }
672 }
673 }
674
675 return false;
676}
677
Chris Forbes47567b72017-06-09 12:09:45 -0700678static std::vector<std::pair<descriptor_slot_t, interface_var>> collect_interface_by_descriptor_slot(
Chris Forbes8af24522018-03-07 11:37:45 -0800679 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
680 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700681 std::unordered_map<unsigned, unsigned> var_sets;
682 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800683 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700684
685 for (auto insn : *src) {
686 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
687 // DecorationDescriptorSet and DecorationBinding.
688 if (insn.opcode() == spv::OpDecorate) {
689 if (insn.word(2) == spv::DecorationDescriptorSet) {
690 var_sets[insn.word(1)] = insn.word(3);
691 }
692
693 if (insn.word(2) == spv::DecorationBinding) {
694 var_bindings[insn.word(1)] = insn.word(3);
695 }
Chris Forbes8af24522018-03-07 11:37:45 -0800696
697 if (insn.word(2) == spv::DecorationNonWritable) {
698 var_nonwritable[insn.word(1)] = 1;
699 }
Chris Forbes47567b72017-06-09 12:09:45 -0700700 }
701 }
702
703 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
704
705 for (auto id : accessible_ids) {
706 auto insn = src->get_def(id);
707 assert(insn != src->end());
708
709 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800710 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
711 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700712 unsigned set = value_or_default(var_sets, insn.word(2), 0);
713 unsigned binding = value_or_default(var_bindings, insn.word(2), 0);
714
715 interface_var v = {};
716 v.id = insn.word(2);
717 v.type_id = insn.word(1);
718 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800719
720 if (var_nonwritable.find(id) == var_nonwritable.end() && is_writable_descriptor_type(src, insn.word(1))) {
721 *has_writable_descriptor = true;
722 }
Chris Forbes47567b72017-06-09 12:09:45 -0700723 }
724 }
725
726 return out;
727}
728
Chris Forbes47567b72017-06-09 12:09:45 -0700729static bool validate_vi_consistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
730 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
731 // be specified only once.
732 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
733 bool skip = false;
734
735 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
736 auto desc = &vi->pVertexBindingDescriptions[i];
737 auto &binding = bindings[desc->binding];
738 if (binding) {
739 // TODO: VALIDATION_ERROR_096005cc perhaps?
740 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
741 SHADER_CHECKER_INCONSISTENT_VI, "SC", "Duplicate vertex input binding descriptions for binding %d",
742 desc->binding);
743 } else {
744 binding = desc;
745 }
746 }
747
748 return skip;
749}
750
751static bool validate_vi_against_vs_inputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
752 shader_module const *vs, spirv_inst_iter entrypoint) {
753 bool skip = false;
754
755 auto inputs = collect_interface_by_location(vs, entrypoint, spv::StorageClassInput, false);
756
757 // Build index by location
758 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
759 if (vi) {
760 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
761 auto num_locations = get_locations_consumed_by_format(vi->pVertexAttributeDescriptions[i].format);
762 for (auto j = 0u; j < num_locations; j++) {
763 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
764 }
765 }
766 }
767
768 auto it_a = attribs.begin();
769 auto it_b = inputs.begin();
770 bool used = false;
771
772 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
773 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
774 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
775 auto a_first = a_at_end ? 0 : it_a->first;
776 auto b_first = b_at_end ? 0 : it_b->first.first;
777 if (!a_at_end && (b_at_end || a_first < b_first)) {
778 if (!used && log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
779 0, __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
780 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
781 skip = true;
782 }
783 used = false;
784 it_a++;
785 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
786 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
787 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Vertex shader consumes input at location %d but not provided",
788 b_first);
789 it_b++;
790 } else {
791 unsigned attrib_type = get_format_type(it_a->second->format);
792 unsigned input_type = get_fundamental_type(vs, it_b->second.type_id);
793
794 // Type checking
795 if (!(attrib_type & input_type)) {
796 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
797 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
798 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
799 string_VkFormat(it_a->second->format), a_first, describe_type(vs, it_b->second.type_id).c_str());
800 }
801
802 // OK!
803 used = true;
804 it_b++;
805 }
806 }
807
808 return skip;
809}
810
811static bool validate_fs_outputs_against_render_pass(debug_report_data const *report_data, shader_module const *fs,
Chris Forbesa400a8a2017-07-20 13:10:24 -0700812 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline,
Chris Forbes47567b72017-06-09 12:09:45 -0700813 uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100814 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700815
Chris Forbes47567b72017-06-09 12:09:45 -0700816 std::map<uint32_t, VkFormat> color_attachments;
817 auto subpass = rpci->pSubpasses[subpass_index];
818 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
819 uint32_t attachment = subpass.pColorAttachments[i].attachment;
820 if (attachment == VK_ATTACHMENT_UNUSED) continue;
821 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
822 color_attachments[i] = rpci->pAttachments[attachment].format;
823 }
824 }
825
826 bool skip = false;
827
828 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
829
830 auto outputs = collect_interface_by_location(fs, entrypoint, spv::StorageClassOutput, false);
831
832 auto it_a = outputs.begin();
833 auto it_b = color_attachments.begin();
834
835 // Walk attachment list and outputs together
836
837 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
838 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
839 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
840
841 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
842 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
843 SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
844 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
845 it_a++;
846 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700847 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
848 // shader to not produce a matching output.
Chris Forbesa400a8a2017-07-20 13:10:24 -0700849 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700850 skip |=
851 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
Chris Forbes47567b72017-06-09 12:09:45 -0700852 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Attachment %d not written by fragment shader", it_b->first);
Chris Forbesefdd4082017-07-20 11:19:16 -0700853 }
Chris Forbes47567b72017-06-09 12:09:45 -0700854 it_b++;
855 } else {
856 unsigned output_type = get_fundamental_type(fs, it_a->second.type_id);
857 unsigned att_type = get_format_type(it_b->second);
858
859 // Type checking
860 if (!(output_type & att_type)) {
861 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
862 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
863 "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
864 string_VkFormat(it_b->second), describe_type(fs, it_a->second.type_id).c_str());
865 }
866
867 // OK!
868 it_a++;
869 it_b++;
870 }
871 }
872
873 return skip;
874}
875
876// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
877// important for identifying the set of shader resources actually used by an entrypoint, for example.
878// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
879// - NOT the shader input/output interfaces.
880//
881// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
882// converting parts of this to be generated from the machine-readable spec instead.
883static std::unordered_set<uint32_t> mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint) {
884 std::unordered_set<uint32_t> ids;
885 std::unordered_set<uint32_t> worklist;
886 worklist.insert(entrypoint.word(2));
887
888 while (!worklist.empty()) {
889 auto id_iter = worklist.begin();
890 auto id = *id_iter;
891 worklist.erase(id_iter);
892
893 auto insn = src->get_def(id);
894 if (insn == src->end()) {
895 // ID is something we didn't collect in build_def_index. that's OK -- we'll stumble across all kinds of things here
896 // that we may not care about.
897 continue;
898 }
899
900 // Try to add to the output set
901 if (!ids.insert(id).second) {
902 continue; // If we already saw this id, we don't want to walk it again.
903 }
904
905 switch (insn.opcode()) {
906 case spv::OpFunction:
907 // Scan whole body of the function, enlisting anything interesting
908 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
909 switch (insn.opcode()) {
910 case spv::OpLoad:
911 case spv::OpAtomicLoad:
912 case spv::OpAtomicExchange:
913 case spv::OpAtomicCompareExchange:
914 case spv::OpAtomicCompareExchangeWeak:
915 case spv::OpAtomicIIncrement:
916 case spv::OpAtomicIDecrement:
917 case spv::OpAtomicIAdd:
918 case spv::OpAtomicISub:
919 case spv::OpAtomicSMin:
920 case spv::OpAtomicUMin:
921 case spv::OpAtomicSMax:
922 case spv::OpAtomicUMax:
923 case spv::OpAtomicAnd:
924 case spv::OpAtomicOr:
925 case spv::OpAtomicXor:
926 worklist.insert(insn.word(3)); // ptr
927 break;
928 case spv::OpStore:
929 case spv::OpAtomicStore:
930 worklist.insert(insn.word(1)); // ptr
931 break;
932 case spv::OpAccessChain:
933 case spv::OpInBoundsAccessChain:
934 worklist.insert(insn.word(3)); // base ptr
935 break;
936 case spv::OpSampledImage:
937 case spv::OpImageSampleImplicitLod:
938 case spv::OpImageSampleExplicitLod:
939 case spv::OpImageSampleDrefImplicitLod:
940 case spv::OpImageSampleDrefExplicitLod:
941 case spv::OpImageSampleProjImplicitLod:
942 case spv::OpImageSampleProjExplicitLod:
943 case spv::OpImageSampleProjDrefImplicitLod:
944 case spv::OpImageSampleProjDrefExplicitLod:
945 case spv::OpImageFetch:
946 case spv::OpImageGather:
947 case spv::OpImageDrefGather:
948 case spv::OpImageRead:
949 case spv::OpImage:
950 case spv::OpImageQueryFormat:
951 case spv::OpImageQueryOrder:
952 case spv::OpImageQuerySizeLod:
953 case spv::OpImageQuerySize:
954 case spv::OpImageQueryLod:
955 case spv::OpImageQueryLevels:
956 case spv::OpImageQuerySamples:
957 case spv::OpImageSparseSampleImplicitLod:
958 case spv::OpImageSparseSampleExplicitLod:
959 case spv::OpImageSparseSampleDrefImplicitLod:
960 case spv::OpImageSparseSampleDrefExplicitLod:
961 case spv::OpImageSparseSampleProjImplicitLod:
962 case spv::OpImageSparseSampleProjExplicitLod:
963 case spv::OpImageSparseSampleProjDrefImplicitLod:
964 case spv::OpImageSparseSampleProjDrefExplicitLod:
965 case spv::OpImageSparseFetch:
966 case spv::OpImageSparseGather:
967 case spv::OpImageSparseDrefGather:
968 case spv::OpImageTexelPointer:
969 worklist.insert(insn.word(3)); // Image or sampled image
970 break;
971 case spv::OpImageWrite:
972 worklist.insert(insn.word(1)); // Image -- different operand order to above
973 break;
974 case spv::OpFunctionCall:
975 for (uint32_t i = 3; i < insn.len(); i++) {
976 worklist.insert(insn.word(i)); // fn itself, and all args
977 }
978 break;
979
980 case spv::OpExtInst:
981 for (uint32_t i = 5; i < insn.len(); i++) {
982 worklist.insert(insn.word(i)); // Operands to ext inst
983 }
984 break;
985 }
986 }
987 break;
988 }
989 }
990
991 return ids;
992}
993
994static bool validate_push_constant_block_against_pipeline(debug_report_data const *report_data,
995 std::vector<VkPushConstantRange> const *push_constant_ranges,
996 shader_module const *src, spirv_inst_iter type,
997 VkShaderStageFlagBits stage) {
998 bool skip = false;
999
1000 // Strip off ptrs etc
1001 type = get_struct_type(src, type, false);
1002 assert(type != src->end());
1003
1004 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1005 // TODO: arrays, matrices, weird sizes
1006 for (auto insn : *src) {
1007 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1008 if (insn.word(3) == spv::DecorationOffset) {
1009 unsigned offset = insn.word(4);
1010 auto size = 4; // Bytes; TODO: calculate this based on the type
1011
1012 bool found_range = false;
1013 for (auto const &range : *push_constant_ranges) {
1014 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1015 found_range = true;
1016
1017 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001018 skip |=
1019 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1020 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_NOT_ACCESSIBLE_FROM_STAGE, "SC",
1021 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1022 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001023 }
1024
1025 break;
1026 }
1027 }
1028
1029 if (!found_range) {
1030 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1031 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_OUT_OF_RANGE, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001032 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001033 }
1034 }
1035 }
1036 }
1037
1038 return skip;
1039}
1040
1041static bool validate_push_constant_usage(debug_report_data const *report_data,
1042 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1043 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
1044 bool skip = false;
1045
1046 for (auto id : accessible_ids) {
1047 auto def_insn = src->get_def(id);
1048 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1049 skip |= validate_push_constant_block_against_pipeline(report_data, push_constant_ranges, src,
1050 src->get_def(def_insn.word(1)), stage);
1051 }
1052 }
1053
1054 return skip;
1055}
1056
1057// Validate that data for each specialization entry is fully contained within the buffer.
1058static bool validate_specialization_offsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
1059 bool skip = false;
1060
1061 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1062
1063 if (spec) {
1064 for (auto i = 0u; i < spec->mapEntryCount; i++) {
1065 // TODO: This is a good place for VALIDATION_ERROR_1360060a.
1066 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
1067 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1068 VALIDATION_ERROR_1360060c, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001069 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1070 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided). %s.",
1071 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1072 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize,
1073 validation_error_map[VALIDATION_ERROR_1360060c]);
Chris Forbes47567b72017-06-09 12:09:45 -07001074 }
1075 }
1076 }
1077
1078 return skip;
1079}
1080
1081static bool descriptor_type_match(shader_module const *module, uint32_t type_id, VkDescriptorType descriptor_type,
1082 unsigned &descriptor_count) {
1083 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001084 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001085 descriptor_count = 1;
1086
1087 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
1088 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
1089 if (type.opcode() == spv::OpTypeArray) {
1090 descriptor_count *= get_constant_value(module, type.word(3));
1091 type = module->get_def(type.word(2));
1092 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001093 if (type.word(2) == spv::StorageClassStorageBuffer) {
1094 is_storage_buffer = true;
1095 }
Chris Forbes47567b72017-06-09 12:09:45 -07001096 type = module->get_def(type.word(3));
1097 }
1098 }
1099
1100 switch (type.opcode()) {
1101 case spv::OpTypeStruct: {
1102 for (auto insn : *module) {
1103 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1104 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001105 if (is_storage_buffer) {
1106 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
1107 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
1108 } else {
1109 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
1110 descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1111 }
Chris Forbes47567b72017-06-09 12:09:45 -07001112 } else if (insn.word(2) == spv::DecorationBufferBlock) {
1113 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001114 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
Chris Forbes47567b72017-06-09 12:09:45 -07001115 }
1116 }
1117 }
1118
1119 // Invalid
1120 return false;
1121 }
1122
1123 case spv::OpTypeSampler:
1124 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER || descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1125
1126 case spv::OpTypeSampledImage:
1127 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
1128 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1129 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1130 auto image_type = module->get_def(type.word(2));
1131 auto dim = image_type.word(3);
1132 auto sampled = image_type.word(7);
1133 return dim == spv::DimBuffer && sampled == 1;
1134 }
1135 return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1136
1137 case spv::OpTypeImage: {
1138 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1139 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1140 auto dim = type.word(3);
1141 auto sampled = type.word(7);
1142
1143 if (dim == spv::DimSubpassData) {
1144 return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
1145 } else if (dim == spv::DimBuffer) {
1146 if (sampled == 1) {
1147 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
1148 } else {
1149 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1150 }
1151 } else if (sampled == 1) {
1152 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001153 descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
Chris Forbes47567b72017-06-09 12:09:45 -07001154 } else {
1155 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
1156 }
1157 }
1158
1159 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1160 default:
1161 return false; // Mismatch
1162 }
1163}
1164
1165static bool require_feature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
1166 if (!feature) {
1167 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1168 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001169 "Shader requires VkPhysicalDeviceFeatures::%s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001170 return true;
1171 }
1172 }
1173
1174 return false;
1175}
1176
1177static bool require_extension(debug_report_data const *report_data, bool extension, char const *extension_name) {
1178 if (!extension) {
1179 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001180 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC", "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001181 extension_name)) {
1182 return true;
1183 }
1184 }
1185
1186 return false;
1187}
1188
Chris Forbes349b3132018-03-07 11:38:08 -08001189static bool validate_shader_capabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1190 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001191 bool skip = false;
1192
1193 auto report_data = GetReportData(dev_data);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001194 auto const &enabledFeatures = GetEnabledFeatures(dev_data);
1195 auto const &extensions = GetEnabledExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001196
1197 struct CapabilityInfo {
1198 char const *name;
1199 VkBool32 const VkPhysicalDeviceFeatures::*feature;
1200 bool const DeviceExtensions::*extension;
1201 };
1202
1203 using F = VkPhysicalDeviceFeatures;
1204 using E = DeviceExtensions;
1205
1206 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001207 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001208 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1209 // feature bits.
1210 {spv::CapabilityMatrix, {nullptr}},
1211 {spv::CapabilityShader, {nullptr}},
1212 {spv::CapabilityInputAttachment, {nullptr}},
1213 {spv::CapabilitySampled1D, {nullptr}},
1214 {spv::CapabilityImage1D, {nullptr}},
1215 {spv::CapabilitySampledBuffer, {nullptr}},
1216 {spv::CapabilityImageQuery, {nullptr}},
1217 {spv::CapabilityDerivativeControl, {nullptr}},
1218
1219 // Capabilities that are optionally supported, but require a feature to
1220 // be enabled on the device
1221 {spv::CapabilityGeometry, {"geometryShader", &F::geometryShader}},
1222 {spv::CapabilityTessellation, {"tessellationShader", &F::tessellationShader}},
1223 {spv::CapabilityFloat64, {"shaderFloat64", &F::shaderFloat64}},
1224 {spv::CapabilityInt64, {"shaderInt64", &F::shaderInt64}},
1225 {spv::CapabilityTessellationPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1226 {spv::CapabilityGeometryPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1227 {spv::CapabilityImageGatherExtended, {"shaderImageGatherExtended", &F::shaderImageGatherExtended}},
1228 {spv::CapabilityStorageImageMultisample, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1229 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"shaderUniformBufferArrayDynamicIndexing", &F::shaderUniformBufferArrayDynamicIndexing}},
1230 {spv::CapabilitySampledImageArrayDynamicIndexing, {"shaderSampledImageArrayDynamicIndexing", &F::shaderSampledImageArrayDynamicIndexing}},
1231 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"shaderStorageBufferArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1232 {spv::CapabilityStorageImageArrayDynamicIndexing, {"shaderStorageImageArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1233 {spv::CapabilityClipDistance, {"shaderClipDistance", &F::shaderClipDistance}},
1234 {spv::CapabilityCullDistance, {"shaderCullDistance", &F::shaderCullDistance}},
1235 {spv::CapabilityImageCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1236 {spv::CapabilitySampleRateShading, {"sampleRateShading", &F::sampleRateShading}},
1237 {spv::CapabilitySparseResidency, {"shaderResourceResidency", &F::shaderResourceResidency}},
1238 {spv::CapabilityMinLod, {"shaderResourceMinLod", &F::shaderResourceMinLod}},
1239 {spv::CapabilitySampledCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1240 {spv::CapabilityImageMSArray, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1241 {spv::CapabilityStorageImageExtendedFormats, {"shaderStorageImageExtendedFormats", &F::shaderStorageImageExtendedFormats}},
1242 {spv::CapabilityInterpolationFunction, {"sampleRateShading", &F::sampleRateShading}},
1243 {spv::CapabilityStorageImageReadWithoutFormat, {"shaderStorageImageReadWithoutFormat", &F::shaderStorageImageReadWithoutFormat}},
1244 {spv::CapabilityStorageImageWriteWithoutFormat, {"shaderStorageImageWriteWithoutFormat", &F::shaderStorageImageWriteWithoutFormat}},
1245 {spv::CapabilityMultiViewport, {"multiViewport", &F::multiViewport}},
1246
1247 // Capabilities that require an extension
1248 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &E::vk_khr_shader_draw_parameters}},
1249 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &E::vk_nv_geometry_shader_passthrough}},
1250 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &E::vk_nv_sample_mask_override_coverage}},
Dave Houltoneb10ea82017-12-22 12:21:50 -07001251 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &E::vk_ext_shader_viewport_index_layer}},
Chris Forbes47567b72017-06-09 12:09:45 -07001252 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1253 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1254 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_ballot }},
1255 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_vote }},
1256 };
1257 // clang-format on
1258
1259 for (auto insn : *src) {
1260 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001261 size_t n = capabilities.count(insn.word(1));
1262 if (1 == n) { // key occurs exactly once
1263 auto it = capabilities.find(insn.word(1));
1264 if (it != capabilities.end()) {
1265 if (it->second.feature) {
1266 skip |= require_feature(report_data, enabledFeatures->*(it->second.feature), it->second.name);
1267 }
1268 if (it->second.extension) {
1269 skip |= require_extension(report_data, extensions->*(it->second.extension), it->second.name);
1270 }
Chris Forbes47567b72017-06-09 12:09:45 -07001271 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001272 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1273 bool needs_feature = false, has_feature = false;
1274 bool needs_ext = false, has_ext = false;
1275 std::string feature_names = "(one of) [ ";
1276 std::string extension_names = feature_names;
1277 auto caps = capabilities.equal_range(insn.word(1));
1278 for (auto it = caps.first; it != caps.second; ++it) {
1279 if (it->second.feature) {
1280 needs_feature = true;
1281 has_feature = has_feature || enabledFeatures->*(it->second.feature);
1282 feature_names += it->second.name;
1283 feature_names += " ";
1284 }
1285 if (it->second.extension) {
1286 needs_ext = true;
1287 has_ext = has_ext || extensions->*(it->second.extension);
1288 extension_names += it->second.name;
1289 extension_names += " ";
1290 }
1291 }
1292 if (needs_feature) {
1293 feature_names += "]";
1294 skip |= require_feature(report_data, has_feature, feature_names.c_str());
1295 }
1296 if (needs_ext) {
1297 extension_names += "]";
1298 skip |= require_extension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001299 }
1300 }
1301 }
1302 }
1303
Chris Forbes349b3132018-03-07 11:38:08 -08001304 if (has_writable_descriptor) {
1305 switch (stage) {
1306 case VK_SHADER_STAGE_COMPUTE_BIT:
1307 /* No feature requirements for writes and atomics from compute
1308 * stage */
1309 break;
1310 case VK_SHADER_STAGE_FRAGMENT_BIT:
1311 skip |= require_feature(report_data, enabledFeatures->fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
1312 break;
1313 default:
1314 skip |=
1315 require_feature(report_data, enabledFeatures->vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
1316 break;
1317 }
1318 }
1319
Chris Forbes47567b72017-06-09 12:09:45 -07001320 return skip;
1321}
1322
1323static uint32_t descriptor_type_to_reqs(shader_module const *module, uint32_t type_id) {
1324 auto type = module->get_def(type_id);
1325
1326 while (true) {
1327 switch (type.opcode()) {
1328 case spv::OpTypeArray:
1329 case spv::OpTypeSampledImage:
1330 type = module->get_def(type.word(2));
1331 break;
1332 case spv::OpTypePointer:
1333 type = module->get_def(type.word(3));
1334 break;
1335 case spv::OpTypeImage: {
1336 auto dim = type.word(3);
1337 auto arrayed = type.word(5);
1338 auto msaa = type.word(6);
1339
1340 switch (dim) {
1341 case spv::Dim1D:
1342 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1343 case spv::Dim2D:
1344 return (msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE) |
Dave Houltona9df0ce2018-02-07 10:51:23 -07001345 (arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D);
Chris Forbes47567b72017-06-09 12:09:45 -07001346 case spv::Dim3D:
1347 return DESCRIPTOR_REQ_VIEW_TYPE_3D;
1348 case spv::DimCube:
1349 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1350 case spv::DimSubpassData:
1351 return msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1352 default: // buffer, etc.
1353 return 0;
1354 }
1355 }
1356 default:
1357 return 0;
1358 }
1359 }
1360}
1361
1362// For given pipelineLayout verify that the set_layout_node at slot.first
1363// has the requested binding at slot.second and return ptr to that binding
1364static VkDescriptorSetLayoutBinding const *get_descriptor_binding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1365 descriptor_slot_t slot) {
1366 if (!pipelineLayout) return nullptr;
1367
1368 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1369
1370 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1371}
1372
Dave Houltona9df0ce2018-02-07 10:51:23 -07001373static bool validate_pipeline_shader_stage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
1374 PIPELINE_STATE *pipeline, shader_module const **out_module,
1375 spirv_inst_iter *out_entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001376 bool skip = false;
1377 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1378 auto report_data = GetReportData(dev_data);
1379
1380 if (!module->has_valid_spirv) return false;
1381
1382 // Find the entrypoint
1383 auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
1384 if (entrypoint == module->end()) {
1385 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1386 VALIDATION_ERROR_10600586, "SC", "No entrypoint found named `%s` for stage %s. %s.", pStage->pName,
1387 string_VkShaderStageFlagBits(pStage->stage), validation_error_map[VALIDATION_ERROR_10600586])) {
1388 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1389 }
1390 }
1391
Chris Forbes47567b72017-06-09 12:09:45 -07001392 // Mark accessible ids
1393 auto accessible_ids = mark_accessible_ids(module, entrypoint);
1394
1395 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001396 bool has_writable_descriptor = false;
1397 auto descriptor_uses = collect_interface_by_descriptor_slot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001398
Chris Forbes349b3132018-03-07 11:38:08 -08001399 // Validate shader capabilities against enabled device features
1400 skip |= validate_shader_capabilities(dev_data, module, pStage->stage, has_writable_descriptor);
1401
Chris Forbes47567b72017-06-09 12:09:45 -07001402 skip |= validate_specialization_offsets(report_data, pStage);
John Zulauff0d06392018-02-16 13:07:24 -07001403 skip |= validate_push_constant_usage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001404 pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001405
1406 // Validate descriptor use
1407 for (auto use : descriptor_uses) {
1408 // While validating shaders capture which slots are used by the pipeline
1409 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
1410 reqs = descriptor_req(reqs | descriptor_type_to_reqs(module, use.second.type_id));
1411
1412 // Verify given pipelineLayout has requested setLayout with requested binding
Chris Forbesc2f751a2017-06-21 11:34:16 -07001413 const auto &binding = get_descriptor_binding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001414 unsigned required_descriptor_count;
1415
1416 if (!binding) {
1417 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1418 SHADER_CHECKER_MISSING_DESCRIPTOR, "SC",
1419 "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
1420 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str());
1421 } else if (~binding->stageFlags & pStage->stage) {
1422 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1423 SHADER_CHECKER_DESCRIPTOR_NOT_ACCESSIBLE_FROM_STAGE, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001424 "Shader uses descriptor slot %u.%u (used as type `%s`) but descriptor not accessible from stage %s",
Chris Forbes47567b72017-06-09 12:09:45 -07001425 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1426 string_VkShaderStageFlagBits(pStage->stage));
1427 } else if (!descriptor_type_match(module, use.second.type_id, binding->descriptorType, required_descriptor_count)) {
1428 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1429 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001430 "Type mismatch on descriptor slot %u.%u (used as type `%s`) but descriptor of type %s", use.first.first,
1431 use.first.second, describe_type(module, use.second.type_id).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001432 string_VkDescriptorType(binding->descriptorType));
1433 } else if (binding->descriptorCount < required_descriptor_count) {
1434 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1435 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1436 "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
1437 required_descriptor_count, use.first.first, use.first.second,
1438 describe_type(module, use.second.type_id).c_str(), binding->descriptorCount);
1439 }
1440 }
1441
1442 // Validate use of input attachments against subpass structure
1443 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1444 auto input_attachment_uses = collect_interface_by_input_attachment_index(module, accessible_ids);
1445
Petr Krause91f7a12017-12-14 20:57:36 +01001446 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001447 auto subpass = pipeline->graphicsPipelineCI.subpass;
1448
1449 for (auto use : input_attachment_uses) {
1450 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1451 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001452 ? input_attachments[use.first].attachment
1453 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001454
1455 if (index == VK_ATTACHMENT_UNUSED) {
1456 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1457 SHADER_CHECKER_MISSING_INPUT_ATTACHMENT, "SC",
1458 "Shader consumes input attachment index %d but not provided in subpass", use.first);
1459 } else if (!(get_format_type(rpci->pAttachments[index].format) & get_fundamental_type(module, use.second.type_id))) {
1460 skip |=
1461 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1462 SHADER_CHECKER_INPUT_ATTACHMENT_TYPE_MISMATCH, "SC",
1463 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
1464 string_VkFormat(rpci->pAttachments[index].format), describe_type(module, use.second.type_id).c_str());
1465 }
1466 }
1467 }
1468
1469 return skip;
1470}
1471
1472static bool validate_interface_between_stages(debug_report_data const *report_data, shader_module const *producer,
1473 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1474 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1475 shader_stage_attributes const *consumer_stage) {
1476 bool skip = false;
1477
1478 auto outputs =
1479 collect_interface_by_location(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1480 auto inputs =
1481 collect_interface_by_location(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
1482
1483 auto a_it = outputs.begin();
1484 auto b_it = inputs.begin();
1485
1486 // Maps sorted by key (location); walk them together to find mismatches
1487 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1488 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1489 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1490 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1491 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1492
1493 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
1494 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1495 __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1496 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1497 a_first.second, consumer_stage->name);
1498 a_it++;
1499 } else if (a_at_end || a_first > b_first) {
1500 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1501 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "%s consumes input location %u.%u which is not written by %s",
1502 consumer_stage->name, b_first.first, b_first.second, producer_stage->name);
1503 b_it++;
1504 } else {
1505 // subtleties of arrayed interfaces:
1506 // - if is_patch, then the member is not arrayed, even though the interface may be.
1507 // - if is_block_member, then the extra array level of an arrayed interface is not
1508 // expressed in the member type -- it's expressed in the block type.
1509 if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1510 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1511 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
1512 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1513 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC", "Type mismatch on location %u.%u: '%s' vs '%s'",
1514 a_first.first, a_first.second, describe_type(producer, a_it->second.type_id).c_str(),
1515 describe_type(consumer, b_it->second.type_id).c_str());
1516 }
1517 if (a_it->second.is_patch != b_it->second.is_patch) {
1518 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1519 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001520 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
Chris Forbes47567b72017-06-09 12:09:45 -07001521 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1522 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1523 }
1524 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
1525 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1526 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1527 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1528 a_first.second, producer_stage->name, consumer_stage->name);
1529 }
1530 a_it++;
1531 b_it++;
1532 }
1533 }
1534
1535 return skip;
1536}
1537
1538// Validate that the shaders used by the given pipeline and store the active_slots
1539// that are actually used by the pipeline into pPipeline->active_slots
Chris Forbesa400a8a2017-07-20 13:10:24 -07001540bool validate_and_capture_pipeline_shader_state(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1541 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001542 int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1543 int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
1544 auto report_data = GetReportData(dev_data);
1545
1546 shader_module const *shaders[5];
1547 memset(shaders, 0, sizeof(shaders));
1548 spirv_inst_iter entrypoints[5];
1549 memset(entrypoints, 0, sizeof(entrypoints));
1550 bool skip = false;
1551
1552 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1553 auto pStage = &pCreateInfo->pStages[i];
1554 auto stage_id = get_shader_stage_id(pStage->stage);
Chris Forbesa400a8a2017-07-20 13:10:24 -07001555 skip |= validate_pipeline_shader_stage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id]);
Chris Forbes47567b72017-06-09 12:09:45 -07001556 }
1557
1558 // if the shader stages are no good individually, cross-stage validation is pointless.
1559 if (skip) return true;
1560
1561 auto vi = pCreateInfo->pVertexInputState;
1562
1563 if (vi) {
1564 skip |= validate_vi_consistency(report_data, vi);
1565 }
1566
1567 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
1568 skip |= validate_vi_against_vs_inputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
1569 }
1570
1571 int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1572 int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
1573
1574 while (!shaders[producer] && producer != fragment_stage) {
1575 producer++;
1576 consumer++;
1577 }
1578
1579 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1580 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001581 if (shaders[consumer]) {
1582 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
1583 skip |= validate_interface_between_stages(report_data, shaders[producer], entrypoints[producer],
1584 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1585 &shader_stage_attribs[consumer]);
1586 }
Chris Forbes47567b72017-06-09 12:09:45 -07001587
1588 producer = consumer;
1589 }
1590 }
1591
1592 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001593 skip |= validate_fs_outputs_against_render_pass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1594 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001595 }
1596
1597 return skip;
1598}
1599
Chris Forbesa400a8a2017-07-20 13:10:24 -07001600bool validate_compute_pipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1601 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001602
1603 shader_module const *module;
1604 spirv_inst_iter entrypoint;
1605
Chris Forbesa400a8a2017-07-20 13:10:24 -07001606 return validate_pipeline_shader_stage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint);
Chris Forbes47567b72017-06-09 12:09:45 -07001607}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001608
Dave Houltona9df0ce2018-02-07 10:51:23 -07001609uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001610
Dave Houltona9df0ce2018-02-07 10:51:23 -07001611static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001612 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1613 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1614 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1615 }
1616
1617 return nullptr;
1618}
1619
Chris Forbes4ae55b32017-06-09 14:42:56 -07001620bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1621 bool skip = false;
1622 spv_result_t spv_valid = SPV_SUCCESS;
1623 auto report_data = GetReportData(dev_data);
1624
1625 if (GetDisables(dev_data)->shader_validation) {
1626 return false;
1627 }
1628
1629 auto have_glsl_shader = GetEnabledExtensions(dev_data)->vk_nv_glsl_shader;
1630
1631 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001632 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1633 VALIDATION_ERROR_12a00ac0, "SC",
Chris Forbes4ae55b32017-06-09 14:42:56 -07001634 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ". %s",
1635 pCreateInfo->codeSize, validation_error_map[VALIDATION_ERROR_12a00ac0]);
1636 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001637 auto cache = GetValidationCacheInfo(pCreateInfo);
1638 uint32_t hash = 0;
1639 if (cache) {
1640 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001641 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001642 }
1643
Chris Forbes4ae55b32017-06-09 14:42:56 -07001644 // Use SPIRV-Tools validator to try and catch any issues with the module itself
1645 spv_context ctx = spvContextCreate(SPV_ENV_VULKAN_1_0);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001646 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001647 spv_diagnostic diag = nullptr;
1648
1649 spv_valid = spvValidate(ctx, &binary, &diag);
1650 if (spv_valid != SPV_SUCCESS) {
1651 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001652 skip |=
1653 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
1654 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__, SHADER_CHECKER_INCONSISTENT_SPIRV, "SC",
1655 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07001656 }
Chris Forbes9a61e082017-07-24 15:35:29 -07001657 } else {
1658 if (cache) {
1659 cache->Insert(hash);
1660 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07001661 }
1662
1663 spvDiagnosticDestroy(diag);
1664 spvContextDestroy(ctx);
1665 }
1666
1667 *spirv_valid = (spv_valid == SPV_SUCCESS);
1668 return skip;
1669}