blob: 6269551c34608218e407142126497327e6b5b3be [file] [log] [blame]
Dave Houlton51653902018-06-22 17:32:13 -06001/* Copyright (c) 2015-2018 The Khronos Group Inc.
2 * Copyright (c) 2015-2018 Valve Corporation
3 * Copyright (c) 2015-2018 LunarG, Inc.
4 * Copyright (C) 2015-2018 Google Inc.
Chris Forbes47567b72017-06-09 12:09:45 -07005 *
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>
Dave Houlton51653902018-06-22 17:32:13 -060019 * Author: Dave Houlton <daveh@lunarg.com>
Chris Forbes47567b72017-06-09 12:09:45 -070020 */
21
22#include <cinttypes>
23#include <cassert>
24#include <vector>
25#include <unordered_map>
26#include <string>
27#include <sstream>
28#include <SPIRV/spirv.hpp>
29#include "vk_loader_platform.h"
30#include "vk_enum_string_helper.h"
31#include "vk_layer_table.h"
32#include "vk_layer_data.h"
33#include "vk_layer_extension_utils.h"
34#include "vk_layer_utils.h"
35#include "core_validation.h"
36#include "core_validation_types.h"
37#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070038#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070039#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040
41enum FORMAT_TYPE {
42 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
43 FORMAT_TYPE_SINT = 2,
44 FORMAT_TYPE_UINT = 4,
45};
46
47typedef std::pair<unsigned, unsigned> location_t;
48
49struct interface_var {
50 uint32_t id;
51 uint32_t type_id;
52 uint32_t offset;
53 bool is_patch;
54 bool is_block_member;
55 bool is_relaxed_precision;
56 // TODO: collect the name, too? Isn't required to be present.
57};
58
59struct shader_stage_attributes {
60 char const *const name;
61 bool arrayed_input;
62 bool arrayed_output;
63};
64
65static shader_stage_attributes shader_stage_attribs[] = {
66 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
67 {"geometry shader", true, false}, {"fragment shader", false, false},
68};
69
70// SPIRV utility functions
71void shader_module::build_def_index() {
72 for (auto insn : *this) {
73 switch (insn.opcode()) {
74 // Types
75 case spv::OpTypeVoid:
76 case spv::OpTypeBool:
77 case spv::OpTypeInt:
78 case spv::OpTypeFloat:
79 case spv::OpTypeVector:
80 case spv::OpTypeMatrix:
81 case spv::OpTypeImage:
82 case spv::OpTypeSampler:
83 case spv::OpTypeSampledImage:
84 case spv::OpTypeArray:
85 case spv::OpTypeRuntimeArray:
86 case spv::OpTypeStruct:
87 case spv::OpTypeOpaque:
88 case spv::OpTypePointer:
89 case spv::OpTypeFunction:
90 case spv::OpTypeEvent:
91 case spv::OpTypeDeviceEvent:
92 case spv::OpTypeReserveId:
93 case spv::OpTypeQueue:
94 case spv::OpTypePipe:
95 def_index[insn.word(1)] = insn.offset();
96 break;
97
98 // Fixed constants
99 case spv::OpConstantTrue:
100 case spv::OpConstantFalse:
101 case spv::OpConstant:
102 case spv::OpConstantComposite:
103 case spv::OpConstantSampler:
104 case spv::OpConstantNull:
105 def_index[insn.word(2)] = insn.offset();
106 break;
107
108 // Specialization constants
109 case spv::OpSpecConstantTrue:
110 case spv::OpSpecConstantFalse:
111 case spv::OpSpecConstant:
112 case spv::OpSpecConstantComposite:
113 case spv::OpSpecConstantOp:
114 def_index[insn.word(2)] = insn.offset();
115 break;
116
117 // Variables
118 case spv::OpVariable:
119 def_index[insn.word(2)] = insn.offset();
120 break;
121
122 // Functions
123 case spv::OpFunction:
124 def_index[insn.word(2)] = insn.offset();
125 break;
126
127 default:
128 // We don't care about any other defs for now.
129 break;
130 }
131 }
132}
133
134static spirv_inst_iter find_entrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
135 for (auto insn : *src) {
136 if (insn.opcode() == spv::OpEntryPoint) {
137 auto entrypointName = (char const *)&insn.word(3);
138 auto entrypointStageBits = 1u << insn.word(1);
139
140 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
141 return insn;
142 }
143 }
144 }
145
146 return src->end();
147}
148
149static char const *storage_class_name(unsigned sc) {
150 switch (sc) {
151 case spv::StorageClassInput:
152 return "input";
153 case spv::StorageClassOutput:
154 return "output";
155 case spv::StorageClassUniformConstant:
156 return "const uniform";
157 case spv::StorageClassUniform:
158 return "uniform";
159 case spv::StorageClassWorkgroup:
160 return "workgroup local";
161 case spv::StorageClassCrossWorkgroup:
162 return "workgroup global";
163 case spv::StorageClassPrivate:
164 return "private global";
165 case spv::StorageClassFunction:
166 return "function";
167 case spv::StorageClassGeneric:
168 return "generic";
169 case spv::StorageClassAtomicCounter:
170 return "atomic counter";
171 case spv::StorageClassImage:
172 return "image";
173 case spv::StorageClassPushConstant:
174 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800175 case spv::StorageClassStorageBuffer:
176 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700177 default:
178 return "unknown";
179 }
180}
181
182// Get the value of an integral constant
183unsigned get_constant_value(shader_module const *src, unsigned id) {
184 auto value = src->get_def(id);
185 assert(value != src->end());
186
187 if (value.opcode() != spv::OpConstant) {
188 // TODO: Either ensure that the specialization transform is already performed on a module we're
189 // considering here, OR -- specialize on the fly now.
190 return 1;
191 }
192
193 return value.word(3);
194}
195
196static void describe_type_inner(std::ostringstream &ss, shader_module const *src, unsigned type) {
197 auto insn = src->get_def(type);
198 assert(insn != src->end());
199
200 switch (insn.opcode()) {
201 case spv::OpTypeBool:
202 ss << "bool";
203 break;
204 case spv::OpTypeInt:
205 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
206 break;
207 case spv::OpTypeFloat:
208 ss << "float" << insn.word(2);
209 break;
210 case spv::OpTypeVector:
211 ss << "vec" << insn.word(3) << " of ";
212 describe_type_inner(ss, src, insn.word(2));
213 break;
214 case spv::OpTypeMatrix:
215 ss << "mat" << insn.word(3) << " of ";
216 describe_type_inner(ss, src, insn.word(2));
217 break;
218 case spv::OpTypeArray:
219 ss << "arr[" << get_constant_value(src, insn.word(3)) << "] of ";
220 describe_type_inner(ss, src, insn.word(2));
221 break;
222 case spv::OpTypePointer:
223 ss << "ptr to " << storage_class_name(insn.word(2)) << " ";
224 describe_type_inner(ss, src, insn.word(3));
225 break;
226 case spv::OpTypeStruct: {
227 ss << "struct of (";
228 for (unsigned i = 2; i < insn.len(); i++) {
229 describe_type_inner(ss, src, insn.word(i));
230 if (i == insn.len() - 1) {
231 ss << ")";
232 } else {
233 ss << ", ";
234 }
235 }
236 break;
237 }
238 case spv::OpTypeSampler:
239 ss << "sampler";
240 break;
241 case spv::OpTypeSampledImage:
242 ss << "sampler+";
243 describe_type_inner(ss, src, insn.word(2));
244 break;
245 case spv::OpTypeImage:
246 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
247 break;
248 default:
249 ss << "oddtype";
250 break;
251 }
252}
253
254static std::string describe_type(shader_module const *src, unsigned type) {
255 std::ostringstream ss;
256 describe_type_inner(ss, src, type);
257 return ss.str();
258}
259
260static bool is_narrow_numeric_type(spirv_inst_iter type) {
261 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
262 return type.word(2) < 64;
263}
264
265static bool types_match(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
266 bool b_arrayed, bool relaxed) {
267 // Walk two type trees together, and complain about differences
268 auto a_insn = a->get_def(a_type);
269 auto b_insn = b->get_def(b_type);
270 assert(a_insn != a->end());
271 assert(b_insn != b->end());
272
273 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
274 return types_match(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
275 }
276
277 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
278 // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
279 return types_match(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
280 }
281
282 if (a_insn.opcode() == spv::OpTypeVector && relaxed && is_narrow_numeric_type(b_insn)) {
283 return types_match(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
284 }
285
286 if (a_insn.opcode() != b_insn.opcode()) {
287 return false;
288 }
289
290 if (a_insn.opcode() == spv::OpTypePointer) {
291 // Match on pointee type. storage class is expected to differ
292 return types_match(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
293 }
294
295 if (a_arrayed || b_arrayed) {
296 // If we havent resolved array-of-verts by here, we're not going to.
297 return false;
298 }
299
300 switch (a_insn.opcode()) {
301 case spv::OpTypeBool:
302 return true;
303 case spv::OpTypeInt:
304 // Match on width, signedness
305 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
306 case spv::OpTypeFloat:
307 // Match on width
308 return a_insn.word(2) == b_insn.word(2);
309 case spv::OpTypeVector:
310 // Match on element type, count.
311 if (!types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
312 if (relaxed && is_narrow_numeric_type(a->get_def(a_insn.word(2)))) {
313 return a_insn.word(3) >= b_insn.word(3);
314 } else {
315 return a_insn.word(3) == b_insn.word(3);
316 }
317 case spv::OpTypeMatrix:
318 // Match on element type, count.
319 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 -0700320 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700321 case spv::OpTypeArray:
322 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
323 // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
324 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 -0700325 get_constant_value(a, a_insn.word(3)) == get_constant_value(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700326 case spv::OpTypeStruct:
327 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700328 {
329 if (a_insn.len() != b_insn.len()) {
330 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700331 }
Chris Forbes47567b72017-06-09 12:09:45 -0700332
Dave Houltona9df0ce2018-02-07 10:51:23 -0700333 for (unsigned i = 2; i < a_insn.len(); i++) {
334 if (!types_match(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
335 return false;
336 }
337 }
338
339 return true;
340 }
Chris Forbes47567b72017-06-09 12:09:45 -0700341 default:
342 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
343 return false;
344 }
345}
346
347static unsigned value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
348 auto it = map.find(id);
349 if (it == map.end())
350 return def;
351 else
352 return it->second;
353}
354
355static unsigned get_locations_consumed_by_type(shader_module const *src, unsigned type, bool strip_array_level) {
356 auto insn = src->get_def(type);
357 assert(insn != src->end());
358
359 switch (insn.opcode()) {
360 case spv::OpTypePointer:
361 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
362 // pointers around.
363 return get_locations_consumed_by_type(src, insn.word(3), strip_array_level);
364 case spv::OpTypeArray:
365 if (strip_array_level) {
366 return get_locations_consumed_by_type(src, insn.word(2), false);
367 } else {
368 return get_constant_value(src, insn.word(3)) * get_locations_consumed_by_type(src, insn.word(2), false);
369 }
370 case spv::OpTypeMatrix:
371 // Num locations is the dimension * element size
372 return insn.word(3) * get_locations_consumed_by_type(src, insn.word(2), false);
373 case spv::OpTypeVector: {
374 auto scalar_type = src->get_def(insn.word(2));
375 auto bit_width =
376 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
377
378 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
379 return (bit_width * insn.word(3) + 127) / 128;
380 }
381 default:
382 // Everything else is just 1.
383 return 1;
384
385 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
386 }
387}
388
389static unsigned get_locations_consumed_by_format(VkFormat format) {
390 switch (format) {
391 case VK_FORMAT_R64G64B64A64_SFLOAT:
392 case VK_FORMAT_R64G64B64A64_SINT:
393 case VK_FORMAT_R64G64B64A64_UINT:
394 case VK_FORMAT_R64G64B64_SFLOAT:
395 case VK_FORMAT_R64G64B64_SINT:
396 case VK_FORMAT_R64G64B64_UINT:
397 return 2;
398 default:
399 return 1;
400 }
401}
402
403static unsigned get_format_type(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700404 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
405 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
406 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
407 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700408 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
409 return FORMAT_TYPE_FLOAT;
410}
411
412// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
413static unsigned get_fundamental_type(shader_module const *src, unsigned type) {
414 auto insn = src->get_def(type);
415 assert(insn != src->end());
416
417 switch (insn.opcode()) {
418 case spv::OpTypeInt:
419 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
420 case spv::OpTypeFloat:
421 return FORMAT_TYPE_FLOAT;
422 case spv::OpTypeVector:
423 return get_fundamental_type(src, insn.word(2));
424 case spv::OpTypeMatrix:
425 return get_fundamental_type(src, insn.word(2));
426 case spv::OpTypeArray:
427 return get_fundamental_type(src, insn.word(2));
428 case spv::OpTypePointer:
429 return get_fundamental_type(src, insn.word(3));
430 case spv::OpTypeImage:
431 return get_fundamental_type(src, insn.word(2));
432
433 default:
434 return 0;
435 }
436}
437
438static uint32_t get_shader_stage_id(VkShaderStageFlagBits stage) {
439 uint32_t bit_pos = uint32_t(u_ffs(stage));
440 return bit_pos - 1;
441}
442
443static spirv_inst_iter get_struct_type(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
444 while (true) {
445 if (def.opcode() == spv::OpTypePointer) {
446 def = src->get_def(def.word(3));
447 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
448 def = src->get_def(def.word(2));
449 is_array_of_verts = false;
450 } else if (def.opcode() == spv::OpTypeStruct) {
451 return def;
452 } else {
453 return src->end();
454 }
455 }
456}
457
Chris Forbesa313d772017-06-13 13:59:41 -0700458static bool collect_interface_block_members(shader_module const *src, std::map<location_t, interface_var> *out,
Chris Forbes47567b72017-06-09 12:09:45 -0700459 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts,
Chris Forbesa313d772017-06-13 13:59:41 -0700460 uint32_t id, uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700461 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
462 auto type = get_struct_type(src, src->get_def(type_id), is_array_of_verts && !is_patch);
463 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
464 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700465 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700466 }
467
468 std::unordered_map<unsigned, unsigned> member_components;
469 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700470 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700471
472 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
473 for (auto insn : *src) {
474 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
475 unsigned member_index = insn.word(2);
476
477 if (insn.word(3) == spv::DecorationComponent) {
478 unsigned component = insn.word(4);
479 member_components[member_index] = component;
480 }
481
482 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
483 member_relaxed_precision[member_index] = 1;
484 }
Chris Forbesa313d772017-06-13 13:59:41 -0700485
486 if (insn.word(3) == spv::DecorationPatch) {
487 member_patch[member_index] = 1;
488 }
Chris Forbes47567b72017-06-09 12:09:45 -0700489 }
490 }
491
Chris Forbesa313d772017-06-13 13:59:41 -0700492 // TODO: correctly handle location assignment from outside
493
Chris Forbes47567b72017-06-09 12:09:45 -0700494 // Second pass -- produce the output, from Location decorations
495 for (auto insn : *src) {
496 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
497 unsigned member_index = insn.word(2);
498 unsigned member_type_id = type.word(2 + member_index);
499
500 if (insn.word(3) == spv::DecorationLocation) {
501 unsigned location = insn.word(4);
502 unsigned num_locations = get_locations_consumed_by_type(src, member_type_id, false);
503 auto component_it = member_components.find(member_index);
504 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
505 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700506 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700507
508 for (unsigned int offset = 0; offset < num_locations; offset++) {
509 interface_var v = {};
510 v.id = id;
511 // TODO: member index in interface_var too?
512 v.type_id = member_type_id;
513 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700514 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700515 v.is_block_member = true;
516 v.is_relaxed_precision = is_relaxed_precision;
517 (*out)[std::make_pair(location + offset, component)] = v;
518 }
519 }
520 }
521 }
Chris Forbesa313d772017-06-13 13:59:41 -0700522
523 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700524}
525
526static std::map<location_t, interface_var> collect_interface_by_location(shader_module const *src, spirv_inst_iter entrypoint,
527 spv::StorageClass sinterface, bool is_array_of_verts) {
528 std::unordered_map<unsigned, unsigned> var_locations;
529 std::unordered_map<unsigned, unsigned> var_builtins;
530 std::unordered_map<unsigned, unsigned> var_components;
531 std::unordered_map<unsigned, unsigned> blocks;
532 std::unordered_map<unsigned, unsigned> var_patch;
533 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
534
535 for (auto insn : *src) {
536 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
537 // fits neither model.
538 if (insn.opcode() == spv::OpDecorate) {
539 if (insn.word(2) == spv::DecorationLocation) {
540 var_locations[insn.word(1)] = insn.word(3);
541 }
542
543 if (insn.word(2) == spv::DecorationBuiltIn) {
544 var_builtins[insn.word(1)] = insn.word(3);
545 }
546
547 if (insn.word(2) == spv::DecorationComponent) {
548 var_components[insn.word(1)] = insn.word(3);
549 }
550
551 if (insn.word(2) == spv::DecorationBlock) {
552 blocks[insn.word(1)] = 1;
553 }
554
555 if (insn.word(2) == spv::DecorationPatch) {
556 var_patch[insn.word(1)] = 1;
557 }
558
559 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
560 var_relaxed_precision[insn.word(1)] = 1;
561 }
562 }
563 }
564
565 // TODO: handle grouped decorations
566 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
567
568 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
569 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
570 uint32_t word = 3;
571 while (entrypoint.word(word) & 0xff000000u) {
572 ++word;
573 }
574 ++word;
575
576 std::map<location_t, interface_var> out;
577
578 for (; word < entrypoint.len(); word++) {
579 auto insn = src->get_def(entrypoint.word(word));
580 assert(insn != src->end());
581 assert(insn.opcode() == spv::OpVariable);
582
583 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
584 unsigned id = insn.word(2);
585 unsigned type = insn.word(1);
586
Jamie Madill061d1112017-11-08 16:25:22 -0500587 int location = value_or_default(var_locations, id, static_cast<unsigned>(-1));
588 int builtin = value_or_default(var_builtins, id, static_cast<unsigned>(-1));
Chris Forbes47567b72017-06-09 12:09:45 -0700589 unsigned component = value_or_default(var_components, id, 0); // Unspecified is OK, is 0
590 bool is_patch = var_patch.find(id) != var_patch.end();
591 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
592
Dave Houltona9df0ce2018-02-07 10:51:23 -0700593 if (builtin != -1)
594 continue;
Chris Forbesa313d772017-06-13 13:59:41 -0700595 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 -0700596 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
597 // one result for each.
598 unsigned num_locations = get_locations_consumed_by_type(src, type, is_array_of_verts && !is_patch);
599 for (unsigned int offset = 0; offset < num_locations; offset++) {
600 interface_var v = {};
601 v.id = id;
602 v.type_id = type;
603 v.offset = offset;
604 v.is_patch = is_patch;
605 v.is_relaxed_precision = is_relaxed_precision;
606 out[std::make_pair(location + offset, component)] = v;
607 }
Chris Forbes47567b72017-06-09 12:09:45 -0700608 }
609 }
610 }
611
612 return out;
613}
614
615static std::vector<std::pair<uint32_t, interface_var>> collect_interface_by_input_attachment_index(
616 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
617 std::vector<std::pair<uint32_t, interface_var>> out;
618
619 for (auto insn : *src) {
620 if (insn.opcode() == spv::OpDecorate) {
621 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
622 auto attachment_index = insn.word(3);
623 auto id = insn.word(1);
624
625 if (accessible_ids.count(id)) {
626 auto def = src->get_def(id);
627 assert(def != src->end());
628
629 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
630 auto num_locations = get_locations_consumed_by_type(src, def.word(1), false);
631 for (unsigned int offset = 0; offset < num_locations; offset++) {
632 interface_var v = {};
633 v.id = id;
634 v.type_id = def.word(1);
635 v.offset = offset;
636 out.emplace_back(attachment_index + offset, v);
637 }
638 }
639 }
640 }
641 }
642 }
643
644 return out;
645}
646
Chris Forbes8af24522018-03-07 11:37:45 -0800647static bool is_writable_descriptor_type(shader_module const *module, uint32_t type_id) {
648 auto type = module->get_def(type_id);
649
650 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
651 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
652 if (type.opcode() == spv::OpTypeArray) {
653 type = module->get_def(type.word(2));
654 } else {
Chris Forbes928b2bd2018-03-14 09:28:35 -0700655 if (type.word(2) == spv::StorageClassStorageBuffer) {
656 return true;
657 }
Chris Forbes8af24522018-03-07 11:37:45 -0800658 type = module->get_def(type.word(3));
659 }
660 }
661
662 switch (type.opcode()) {
663 case spv::OpTypeImage: {
664 auto dim = type.word(3);
665 auto sampled = type.word(7);
666 return sampled == 2 && dim != spv::DimSubpassData;
667 }
668
669 case spv::OpTypeStruct:
670 for (auto insn : *module) {
671 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
672 if (insn.word(2) == spv::DecorationBufferBlock) {
673 return true;
674 }
675 }
676 }
677 }
678
679 return false;
680}
681
Chris Forbes47567b72017-06-09 12:09:45 -0700682static std::vector<std::pair<descriptor_slot_t, interface_var>> collect_interface_by_descriptor_slot(
Chris Forbes8af24522018-03-07 11:37:45 -0800683 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
684 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700685 std::unordered_map<unsigned, unsigned> var_sets;
686 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800687 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700688
689 for (auto insn : *src) {
690 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
691 // DecorationDescriptorSet and DecorationBinding.
692 if (insn.opcode() == spv::OpDecorate) {
693 if (insn.word(2) == spv::DecorationDescriptorSet) {
694 var_sets[insn.word(1)] = insn.word(3);
695 }
696
697 if (insn.word(2) == spv::DecorationBinding) {
698 var_bindings[insn.word(1)] = insn.word(3);
699 }
Chris Forbes8af24522018-03-07 11:37:45 -0800700
701 if (insn.word(2) == spv::DecorationNonWritable) {
702 var_nonwritable[insn.word(1)] = 1;
703 }
Chris Forbes47567b72017-06-09 12:09:45 -0700704 }
705 }
706
707 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
708
709 for (auto id : accessible_ids) {
710 auto insn = src->get_def(id);
711 assert(insn != src->end());
712
713 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800714 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
715 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700716 unsigned set = value_or_default(var_sets, insn.word(2), 0);
717 unsigned binding = value_or_default(var_bindings, insn.word(2), 0);
718
719 interface_var v = {};
720 v.id = insn.word(2);
721 v.type_id = insn.word(1);
722 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800723
724 if (var_nonwritable.find(id) == var_nonwritable.end() && is_writable_descriptor_type(src, insn.word(1))) {
725 *has_writable_descriptor = true;
726 }
Chris Forbes47567b72017-06-09 12:09:45 -0700727 }
728 }
729
730 return out;
731}
732
Chris Forbes47567b72017-06-09 12:09:45 -0700733static bool validate_vi_consistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
734 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
735 // be specified only once.
736 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
737 bool skip = false;
738
739 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
740 auto desc = &vi->pVertexBindingDescriptions[i];
741 auto &binding = bindings[desc->binding];
742 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600743 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600744 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -0600745 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700746 desc->binding);
747 } else {
748 binding = desc;
749 }
750 }
751
752 return skip;
753}
754
755static bool validate_vi_against_vs_inputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
756 shader_module const *vs, spirv_inst_iter entrypoint) {
757 bool skip = false;
758
759 auto inputs = collect_interface_by_location(vs, entrypoint, spv::StorageClassInput, false);
760
761 // Build index by location
762 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
763 if (vi) {
764 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
765 auto num_locations = get_locations_consumed_by_format(vi->pVertexAttributeDescriptions[i].format);
766 for (auto j = 0u; j < num_locations; j++) {
767 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
768 }
769 }
770 }
771
772 auto it_a = attribs.begin();
773 auto it_b = inputs.begin();
774 bool used = false;
775
776 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
777 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
778 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
779 auto a_first = a_at_end ? 0 : it_a->first;
780 auto b_first = b_at_end ? 0 : it_b->first.first;
781 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600782 if (!used &&
783 log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600784 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600785 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700786 skip = true;
787 }
788 used = false;
789 it_a++;
790 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600791 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600792 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600793 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700794 it_b++;
795 } else {
796 unsigned attrib_type = get_format_type(it_a->second->format);
797 unsigned input_type = get_fundamental_type(vs, it_b->second.type_id);
798
799 // Type checking
800 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600801 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600802 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700803 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
804 string_VkFormat(it_a->second->format), a_first, describe_type(vs, it_b->second.type_id).c_str());
805 }
806
807 // OK!
808 used = true;
809 it_b++;
810 }
811 }
812
813 return skip;
814}
815
816static bool validate_fs_outputs_against_render_pass(debug_report_data const *report_data, shader_module const *fs,
Chris Forbesa400a8a2017-07-20 13:10:24 -0700817 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline,
Chris Forbes47567b72017-06-09 12:09:45 -0700818 uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100819 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700820
Chris Forbes47567b72017-06-09 12:09:45 -0700821 std::map<uint32_t, VkFormat> color_attachments;
822 auto subpass = rpci->pSubpasses[subpass_index];
823 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
824 uint32_t attachment = subpass.pColorAttachments[i].attachment;
825 if (attachment == VK_ATTACHMENT_UNUSED) continue;
826 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
827 color_attachments[i] = rpci->pAttachments[attachment].format;
828 }
829 }
830
831 bool skip = false;
832
833 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
834
835 auto outputs = collect_interface_by_location(fs, entrypoint, spv::StorageClassOutput, false);
836
837 auto it_a = outputs.begin();
838 auto it_b = color_attachments.begin();
839
840 // Walk attachment list and outputs together
841
842 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
843 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
844 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
845
846 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600847 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600848 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Chris Forbes47567b72017-06-09 12:09:45 -0700849 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
850 it_a++;
851 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700852 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
853 // shader to not produce a matching output.
Chris Forbesa400a8a2017-07-20 13:10:24 -0700854 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Mark Young4e919b22018-05-21 15:53:59 -0600855 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600856 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600857 "Attachment %d not written by fragment shader", it_b->first);
Chris Forbesefdd4082017-07-20 11:19:16 -0700858 }
Chris Forbes47567b72017-06-09 12:09:45 -0700859 it_b++;
860 } else {
861 unsigned output_type = get_fundamental_type(fs, it_a->second.type_id);
862 unsigned att_type = get_format_type(it_b->second);
863
864 // Type checking
865 if (!(output_type & att_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600866 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600867 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700868 "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
869 string_VkFormat(it_b->second), describe_type(fs, it_a->second.type_id).c_str());
870 }
871
872 // OK!
873 it_a++;
874 it_b++;
875 }
876 }
877
878 return skip;
879}
880
881// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
882// important for identifying the set of shader resources actually used by an entrypoint, for example.
883// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
884// - NOT the shader input/output interfaces.
885//
886// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
887// converting parts of this to be generated from the machine-readable spec instead.
888static std::unordered_set<uint32_t> mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint) {
889 std::unordered_set<uint32_t> ids;
890 std::unordered_set<uint32_t> worklist;
891 worklist.insert(entrypoint.word(2));
892
893 while (!worklist.empty()) {
894 auto id_iter = worklist.begin();
895 auto id = *id_iter;
896 worklist.erase(id_iter);
897
898 auto insn = src->get_def(id);
899 if (insn == src->end()) {
900 // ID is something we didn't collect in build_def_index. that's OK -- we'll stumble across all kinds of things here
901 // that we may not care about.
902 continue;
903 }
904
905 // Try to add to the output set
906 if (!ids.insert(id).second) {
907 continue; // If we already saw this id, we don't want to walk it again.
908 }
909
910 switch (insn.opcode()) {
911 case spv::OpFunction:
912 // Scan whole body of the function, enlisting anything interesting
913 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
914 switch (insn.opcode()) {
915 case spv::OpLoad:
916 case spv::OpAtomicLoad:
917 case spv::OpAtomicExchange:
918 case spv::OpAtomicCompareExchange:
919 case spv::OpAtomicCompareExchangeWeak:
920 case spv::OpAtomicIIncrement:
921 case spv::OpAtomicIDecrement:
922 case spv::OpAtomicIAdd:
923 case spv::OpAtomicISub:
924 case spv::OpAtomicSMin:
925 case spv::OpAtomicUMin:
926 case spv::OpAtomicSMax:
927 case spv::OpAtomicUMax:
928 case spv::OpAtomicAnd:
929 case spv::OpAtomicOr:
930 case spv::OpAtomicXor:
931 worklist.insert(insn.word(3)); // ptr
932 break;
933 case spv::OpStore:
934 case spv::OpAtomicStore:
935 worklist.insert(insn.word(1)); // ptr
936 break;
937 case spv::OpAccessChain:
938 case spv::OpInBoundsAccessChain:
939 worklist.insert(insn.word(3)); // base ptr
940 break;
941 case spv::OpSampledImage:
942 case spv::OpImageSampleImplicitLod:
943 case spv::OpImageSampleExplicitLod:
944 case spv::OpImageSampleDrefImplicitLod:
945 case spv::OpImageSampleDrefExplicitLod:
946 case spv::OpImageSampleProjImplicitLod:
947 case spv::OpImageSampleProjExplicitLod:
948 case spv::OpImageSampleProjDrefImplicitLod:
949 case spv::OpImageSampleProjDrefExplicitLod:
950 case spv::OpImageFetch:
951 case spv::OpImageGather:
952 case spv::OpImageDrefGather:
953 case spv::OpImageRead:
954 case spv::OpImage:
955 case spv::OpImageQueryFormat:
956 case spv::OpImageQueryOrder:
957 case spv::OpImageQuerySizeLod:
958 case spv::OpImageQuerySize:
959 case spv::OpImageQueryLod:
960 case spv::OpImageQueryLevels:
961 case spv::OpImageQuerySamples:
962 case spv::OpImageSparseSampleImplicitLod:
963 case spv::OpImageSparseSampleExplicitLod:
964 case spv::OpImageSparseSampleDrefImplicitLod:
965 case spv::OpImageSparseSampleDrefExplicitLod:
966 case spv::OpImageSparseSampleProjImplicitLod:
967 case spv::OpImageSparseSampleProjExplicitLod:
968 case spv::OpImageSparseSampleProjDrefImplicitLod:
969 case spv::OpImageSparseSampleProjDrefExplicitLod:
970 case spv::OpImageSparseFetch:
971 case spv::OpImageSparseGather:
972 case spv::OpImageSparseDrefGather:
973 case spv::OpImageTexelPointer:
974 worklist.insert(insn.word(3)); // Image or sampled image
975 break;
976 case spv::OpImageWrite:
977 worklist.insert(insn.word(1)); // Image -- different operand order to above
978 break;
979 case spv::OpFunctionCall:
980 for (uint32_t i = 3; i < insn.len(); i++) {
981 worklist.insert(insn.word(i)); // fn itself, and all args
982 }
983 break;
984
985 case spv::OpExtInst:
986 for (uint32_t i = 5; i < insn.len(); i++) {
987 worklist.insert(insn.word(i)); // Operands to ext inst
988 }
989 break;
990 }
991 }
992 break;
993 }
994 }
995
996 return ids;
997}
998
999static bool validate_push_constant_block_against_pipeline(debug_report_data const *report_data,
1000 std::vector<VkPushConstantRange> const *push_constant_ranges,
1001 shader_module const *src, spirv_inst_iter type,
1002 VkShaderStageFlagBits stage) {
1003 bool skip = false;
1004
1005 // Strip off ptrs etc
1006 type = get_struct_type(src, type, false);
1007 assert(type != src->end());
1008
1009 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1010 // TODO: arrays, matrices, weird sizes
1011 for (auto insn : *src) {
1012 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1013 if (insn.word(3) == spv::DecorationOffset) {
1014 unsigned offset = insn.word(4);
1015 auto size = 4; // Bytes; TODO: calculate this based on the type
1016
1017 bool found_range = false;
1018 for (auto const &range : *push_constant_ranges) {
1019 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1020 found_range = true;
1021
1022 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001023 skip |=
1024 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001025 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001026 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1027 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001028 }
1029
1030 break;
1031 }
1032 }
1033
1034 if (!found_range) {
1035 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001036 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001037 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001038 }
1039 }
1040 }
1041 }
1042
1043 return skip;
1044}
1045
1046static bool validate_push_constant_usage(debug_report_data const *report_data,
1047 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1048 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
1049 bool skip = false;
1050
1051 for (auto id : accessible_ids) {
1052 auto def_insn = src->get_def(id);
1053 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1054 skip |= validate_push_constant_block_against_pipeline(report_data, push_constant_ranges, src,
1055 src->get_def(def_insn.word(1)), stage);
1056 }
1057 }
1058
1059 return skip;
1060}
1061
1062// Validate that data for each specialization entry is fully contained within the buffer.
1063static bool validate_specialization_offsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
1064 bool skip = false;
1065
1066 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1067
1068 if (spec) {
1069 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001070 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001071 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001072 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001073 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001074 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001075 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001076 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001077 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001078 }
1079 }
1080 }
1081
1082 return skip;
1083}
1084
1085static bool descriptor_type_match(shader_module const *module, uint32_t type_id, VkDescriptorType descriptor_type,
1086 unsigned &descriptor_count) {
1087 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001088 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001089 descriptor_count = 1;
1090
1091 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Jeff Bolzfdf96072018-04-10 14:32:18 -05001092 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1093 if (type.opcode() == spv::OpTypeRuntimeArray) {
1094 descriptor_count = 0;
1095 type = module->get_def(type.word(2));
1096 } else if (type.opcode() == spv::OpTypeArray) {
Chris Forbes47567b72017-06-09 12:09:45 -07001097 descriptor_count *= get_constant_value(module, type.word(3));
1098 type = module->get_def(type.word(2));
1099 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001100 if (type.word(2) == spv::StorageClassStorageBuffer) {
1101 is_storage_buffer = true;
1102 }
Chris Forbes47567b72017-06-09 12:09:45 -07001103 type = module->get_def(type.word(3));
1104 }
1105 }
1106
1107 switch (type.opcode()) {
1108 case spv::OpTypeStruct: {
1109 for (auto insn : *module) {
1110 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1111 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001112 if (is_storage_buffer) {
1113 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
1114 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
1115 } else {
1116 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
1117 descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1118 }
Chris Forbes47567b72017-06-09 12:09:45 -07001119 } else if (insn.word(2) == spv::DecorationBufferBlock) {
1120 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001121 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
Chris Forbes47567b72017-06-09 12:09:45 -07001122 }
1123 }
1124 }
1125
1126 // Invalid
1127 return false;
1128 }
1129
1130 case spv::OpTypeSampler:
1131 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER || descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1132
1133 case spv::OpTypeSampledImage:
1134 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
1135 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1136 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1137 auto image_type = module->get_def(type.word(2));
1138 auto dim = image_type.word(3);
1139 auto sampled = image_type.word(7);
1140 return dim == spv::DimBuffer && sampled == 1;
1141 }
1142 return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1143
1144 case spv::OpTypeImage: {
1145 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1146 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1147 auto dim = type.word(3);
1148 auto sampled = type.word(7);
1149
1150 if (dim == spv::DimSubpassData) {
1151 return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
1152 } else if (dim == spv::DimBuffer) {
1153 if (sampled == 1) {
1154 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
1155 } else {
1156 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1157 }
1158 } else if (sampled == 1) {
1159 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001160 descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
Chris Forbes47567b72017-06-09 12:09:45 -07001161 } else {
1162 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
1163 }
1164 }
1165
1166 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1167 default:
1168 return false; // Mismatch
1169 }
1170}
1171
1172static bool require_feature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
1173 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001174 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001175 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001176 return true;
1177 }
1178 }
1179
1180 return false;
1181}
1182
1183static bool require_extension(debug_report_data const *report_data, bool extension, char const *extension_name) {
1184 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001185 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001186 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001187 extension_name)) {
1188 return true;
1189 }
1190 }
1191
1192 return false;
1193}
1194
Chris Forbes349b3132018-03-07 11:38:08 -08001195static bool validate_shader_capabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1196 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001197 bool skip = false;
1198
1199 auto report_data = GetReportData(dev_data);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001200 auto const &enabledFeatures = GetEnabledFeatures(dev_data);
Cort Strattond2742852018-05-03 13:42:10 -04001201 auto const &extensions = GetDeviceExtensions(dev_data);
Jeff Bolzfdf96072018-04-10 14:32:18 -05001202 auto const &descriptorIndexingFeatures = GetEnabledDescriptorIndexingFeatures(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001203
1204 struct CapabilityInfo {
1205 char const *name;
Jeff Bolzfdf96072018-04-10 14:32:18 -05001206 VkBool32 const *feature;
1207 bool const *extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001208 };
1209
Chris Forbes47567b72017-06-09 12:09:45 -07001210 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001211 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001212 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1213 // feature bits.
1214 {spv::CapabilityMatrix, {nullptr}},
1215 {spv::CapabilityShader, {nullptr}},
1216 {spv::CapabilityInputAttachment, {nullptr}},
1217 {spv::CapabilitySampled1D, {nullptr}},
1218 {spv::CapabilityImage1D, {nullptr}},
1219 {spv::CapabilitySampledBuffer, {nullptr}},
1220 {spv::CapabilityImageQuery, {nullptr}},
1221 {spv::CapabilityDerivativeControl, {nullptr}},
1222
1223 // Capabilities that are optionally supported, but require a feature to
1224 // be enabled on the device
Jeff Bolzfdf96072018-04-10 14:32:18 -05001225 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &enabledFeatures->geometryShader}},
1226 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &enabledFeatures->tessellationShader}},
1227 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &enabledFeatures->shaderFloat64}},
1228 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &enabledFeatures->shaderInt64}},
1229 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &enabledFeatures->shaderTessellationAndGeometryPointSize}},
1230 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &enabledFeatures->shaderTessellationAndGeometryPointSize}},
1231 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &enabledFeatures->shaderImageGatherExtended}},
1232 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &enabledFeatures->shaderStorageImageMultisample}},
1233 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &enabledFeatures->shaderUniformBufferArrayDynamicIndexing}},
1234 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &enabledFeatures->shaderSampledImageArrayDynamicIndexing}},
1235 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &enabledFeatures->shaderStorageBufferArrayDynamicIndexing}},
1236 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &enabledFeatures->shaderStorageBufferArrayDynamicIndexing}},
1237 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &enabledFeatures->shaderClipDistance}},
1238 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &enabledFeatures->shaderCullDistance}},
1239 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &enabledFeatures->imageCubeArray}},
1240 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &enabledFeatures->sampleRateShading}},
1241 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &enabledFeatures->shaderResourceResidency}},
1242 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &enabledFeatures->shaderResourceMinLod}},
1243 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &enabledFeatures->imageCubeArray}},
1244 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &enabledFeatures->shaderStorageImageMultisample}},
1245 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &enabledFeatures->shaderStorageImageExtendedFormats}},
1246 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &enabledFeatures->sampleRateShading}},
1247 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &enabledFeatures->shaderStorageImageReadWithoutFormat}},
1248 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &enabledFeatures->shaderStorageImageWriteWithoutFormat}},
1249 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &enabledFeatures->multiViewport}},
1250
1251 // XXX TODO: Descriptor indexing capability enums are not yet available in the spirv-tools we fetch.
1252#define CapabilityShaderNonUniformEXT 5301
1253#define CapabilityRuntimeDescriptorArrayEXT 5302
1254#define CapabilityInputAttachmentArrayDynamicIndexingEXT 5303
1255#define CapabilityUniformTexelBufferArrayDynamicIndexingEXT 5304
1256#define CapabilityStorageTexelBufferArrayDynamicIndexingEXT 5305
1257#define CapabilityUniformBufferArrayNonUniformIndexingEXT 5306
1258#define CapabilitySampledImageArrayNonUniformIndexingEXT 5307
1259#define CapabilityStorageBufferArrayNonUniformIndexingEXT 5308
1260#define CapabilityStorageImageArrayNonUniformIndexingEXT 5309
1261#define CapabilityInputAttachmentArrayNonUniformIndexingEXT 5310
1262#define CapabilityUniformTexelBufferArrayNonUniformIndexingEXT 5311
1263#define CapabilityStorageTexelBufferArrayNonUniformIndexingEXT 5312
1264 {CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &extensions->vk_ext_descriptor_indexing}},
1265 {CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &descriptorIndexingFeatures->runtimeDescriptorArray}},
1266 {CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &descriptorIndexingFeatures->shaderInputAttachmentArrayDynamicIndexing}},
1267 {CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &descriptorIndexingFeatures->shaderUniformTexelBufferArrayDynamicIndexing}},
1268 {CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &descriptorIndexingFeatures->shaderStorageTexelBufferArrayDynamicIndexing}},
1269 {CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderUniformBufferArrayNonUniformIndexing}},
1270 {CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderSampledImageArrayNonUniformIndexing}},
1271 {CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderStorageBufferArrayNonUniformIndexing}},
1272 {CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderStorageImageArrayNonUniformIndexing}},
1273 {CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderInputAttachmentArrayNonUniformIndexing}},
1274 {CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderUniformTexelBufferArrayNonUniformIndexing}},
1275 {CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &descriptorIndexingFeatures->shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001276
1277 // Capabilities that require an extension
Jeff Bolzfdf96072018-04-10 14:32:18 -05001278 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &extensions->vk_khr_shader_draw_parameters}},
1279 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &extensions->vk_nv_geometry_shader_passthrough}},
1280 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &extensions->vk_nv_sample_mask_override_coverage}},
1281 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &extensions->vk_ext_shader_viewport_index_layer}},
1282 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &extensions->vk_nv_viewport_array2}},
1283 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &extensions->vk_nv_viewport_array2}},
1284 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &extensions->vk_ext_shader_subgroup_ballot }},
1285 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &extensions->vk_ext_shader_subgroup_vote }},
Chris Forbes47567b72017-06-09 12:09:45 -07001286 };
1287 // clang-format on
1288
1289 for (auto insn : *src) {
1290 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001291 size_t n = capabilities.count(insn.word(1));
1292 if (1 == n) { // key occurs exactly once
1293 auto it = capabilities.find(insn.word(1));
1294 if (it != capabilities.end()) {
1295 if (it->second.feature) {
Jeff Bolzfdf96072018-04-10 14:32:18 -05001296 skip |= require_feature(report_data, *(it->second.feature), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001297 }
1298 if (it->second.extension) {
Jeff Bolzfdf96072018-04-10 14:32:18 -05001299 skip |= require_extension(report_data, *(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001300 }
Chris Forbes47567b72017-06-09 12:09:45 -07001301 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001302 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1303 bool needs_feature = false, has_feature = false;
1304 bool needs_ext = false, has_ext = false;
1305 std::string feature_names = "(one of) [ ";
1306 std::string extension_names = feature_names;
1307 auto caps = capabilities.equal_range(insn.word(1));
1308 for (auto it = caps.first; it != caps.second; ++it) {
1309 if (it->second.feature) {
1310 needs_feature = true;
Jeff Bolzfdf96072018-04-10 14:32:18 -05001311 has_feature = has_feature || *(it->second.feature);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001312 feature_names += it->second.name;
1313 feature_names += " ";
1314 }
1315 if (it->second.extension) {
1316 needs_ext = true;
Jeff Bolzfdf96072018-04-10 14:32:18 -05001317 has_ext = has_ext || *(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001318 extension_names += it->second.name;
1319 extension_names += " ";
1320 }
1321 }
1322 if (needs_feature) {
1323 feature_names += "]";
1324 skip |= require_feature(report_data, has_feature, feature_names.c_str());
1325 }
1326 if (needs_ext) {
1327 extension_names += "]";
1328 skip |= require_extension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001329 }
1330 }
1331 }
1332 }
1333
Chris Forbes349b3132018-03-07 11:38:08 -08001334 if (has_writable_descriptor) {
1335 switch (stage) {
1336 case VK_SHADER_STAGE_COMPUTE_BIT:
1337 /* No feature requirements for writes and atomics from compute
1338 * stage */
1339 break;
1340 case VK_SHADER_STAGE_FRAGMENT_BIT:
1341 skip |= require_feature(report_data, enabledFeatures->fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
1342 break;
1343 default:
1344 skip |=
1345 require_feature(report_data, enabledFeatures->vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
1346 break;
1347 }
1348 }
1349
Chris Forbes47567b72017-06-09 12:09:45 -07001350 return skip;
1351}
1352
1353static uint32_t descriptor_type_to_reqs(shader_module const *module, uint32_t type_id) {
1354 auto type = module->get_def(type_id);
1355
1356 while (true) {
1357 switch (type.opcode()) {
1358 case spv::OpTypeArray:
1359 case spv::OpTypeSampledImage:
1360 type = module->get_def(type.word(2));
1361 break;
1362 case spv::OpTypePointer:
1363 type = module->get_def(type.word(3));
1364 break;
1365 case spv::OpTypeImage: {
1366 auto dim = type.word(3);
1367 auto arrayed = type.word(5);
1368 auto msaa = type.word(6);
1369
1370 switch (dim) {
1371 case spv::Dim1D:
1372 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1373 case spv::Dim2D:
1374 return (msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE) |
Dave Houltona9df0ce2018-02-07 10:51:23 -07001375 (arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D);
Chris Forbes47567b72017-06-09 12:09:45 -07001376 case spv::Dim3D:
1377 return DESCRIPTOR_REQ_VIEW_TYPE_3D;
1378 case spv::DimCube:
1379 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1380 case spv::DimSubpassData:
1381 return msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1382 default: // buffer, etc.
1383 return 0;
1384 }
1385 }
1386 default:
1387 return 0;
1388 }
1389 }
1390}
1391
1392// For given pipelineLayout verify that the set_layout_node at slot.first
1393// has the requested binding at slot.second and return ptr to that binding
1394static VkDescriptorSetLayoutBinding const *get_descriptor_binding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1395 descriptor_slot_t slot) {
1396 if (!pipelineLayout) return nullptr;
1397
1398 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1399
1400 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1401}
1402
Chris Forbes0771b672018-03-22 21:13:46 -07001403static void process_execution_modes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
1404 auto entrypoint_id = entrypoint.word(1);
1405 bool is_point_mode = false;
1406
1407 for (auto insn : *src) {
1408 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
1409 switch (insn.word(2)) {
1410 case spv::ExecutionModePointMode:
1411 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
1412 is_point_mode = true;
1413 break;
1414
1415 case spv::ExecutionModeOutputPoints:
1416 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1417 break;
1418
1419 case spv::ExecutionModeIsolines:
1420 case spv::ExecutionModeOutputLineStrip:
1421 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
1422 break;
1423
1424 case spv::ExecutionModeTriangles:
1425 case spv::ExecutionModeQuads:
1426 case spv::ExecutionModeOutputTriangleStrip:
1427 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
1428 break;
1429 }
1430 }
1431 }
1432
1433 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1434}
1435
Dave Houltona9df0ce2018-02-07 10:51:23 -07001436static bool validate_pipeline_shader_stage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
1437 PIPELINE_STATE *pipeline, shader_module const **out_module,
1438 spirv_inst_iter *out_entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001439 bool skip = false;
1440 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1441 auto report_data = GetReportData(dev_data);
1442
1443 if (!module->has_valid_spirv) return false;
1444
1445 // Find the entrypoint
1446 auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
1447 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001448 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001449 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
1450 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001451 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1452 }
1453 }
1454
Chris Forbes47567b72017-06-09 12:09:45 -07001455 // Mark accessible ids
1456 auto accessible_ids = mark_accessible_ids(module, entrypoint);
Chris Forbes0771b672018-03-22 21:13:46 -07001457 process_execution_modes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07001458
1459 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001460 bool has_writable_descriptor = false;
1461 auto descriptor_uses = collect_interface_by_descriptor_slot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001462
Chris Forbes349b3132018-03-07 11:38:08 -08001463 // Validate shader capabilities against enabled device features
1464 skip |= validate_shader_capabilities(dev_data, module, pStage->stage, has_writable_descriptor);
1465
Chris Forbes47567b72017-06-09 12:09:45 -07001466 skip |= validate_specialization_offsets(report_data, pStage);
John Zulauff0d06392018-02-16 13:07:24 -07001467 skip |= validate_push_constant_usage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001468 pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001469
1470 // Validate descriptor use
1471 for (auto use : descriptor_uses) {
1472 // While validating shaders capture which slots are used by the pipeline
1473 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
1474 reqs = descriptor_req(reqs | descriptor_type_to_reqs(module, use.second.type_id));
1475
1476 // Verify given pipelineLayout has requested setLayout with requested binding
Chris Forbesc2f751a2017-06-21 11:34:16 -07001477 const auto &binding = get_descriptor_binding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001478 unsigned required_descriptor_count;
1479
1480 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001481 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001482 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes47567b72017-06-09 12:09:45 -07001483 "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
1484 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str());
1485 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001486 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001487 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001488 "Shader uses descriptor slot %u.%u (used as type `%s`) but descriptor not accessible from stage %s",
Chris Forbes47567b72017-06-09 12:09:45 -07001489 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1490 string_VkShaderStageFlagBits(pStage->stage));
1491 } else if (!descriptor_type_match(module, use.second.type_id, binding->descriptorType, required_descriptor_count)) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001492 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001493 kVUID_Core_Shader_DescriptorTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001494 "Type mismatch on descriptor slot %u.%u (used as type `%s`) but descriptor of type %s", use.first.first,
1495 use.first.second, describe_type(module, use.second.type_id).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001496 string_VkDescriptorType(binding->descriptorType));
1497 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001498 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001499 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001500 "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
1501 required_descriptor_count, use.first.first, use.first.second,
1502 describe_type(module, use.second.type_id).c_str(), binding->descriptorCount);
1503 }
1504 }
1505
1506 // Validate use of input attachments against subpass structure
1507 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1508 auto input_attachment_uses = collect_interface_by_input_attachment_index(module, accessible_ids);
1509
Petr Krause91f7a12017-12-14 20:57:36 +01001510 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001511 auto subpass = pipeline->graphicsPipelineCI.subpass;
1512
1513 for (auto use : input_attachment_uses) {
1514 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1515 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001516 ? input_attachments[use.first].attachment
1517 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001518
1519 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001520 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001521 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07001522 "Shader consumes input attachment index %d but not provided in subpass", use.first);
1523 } else if (!(get_format_type(rpci->pAttachments[index].format) & get_fundamental_type(module, use.second.type_id))) {
1524 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001525 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001526 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001527 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
1528 string_VkFormat(rpci->pAttachments[index].format), describe_type(module, use.second.type_id).c_str());
1529 }
1530 }
1531 }
1532
1533 return skip;
1534}
1535
1536static bool validate_interface_between_stages(debug_report_data const *report_data, shader_module const *producer,
1537 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1538 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1539 shader_stage_attributes const *consumer_stage) {
1540 bool skip = false;
1541
1542 auto outputs =
1543 collect_interface_by_location(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1544 auto inputs =
1545 collect_interface_by_location(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
1546
1547 auto a_it = outputs.begin();
1548 auto b_it = inputs.begin();
1549
1550 // Maps sorted by key (location); walk them together to find mismatches
1551 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1552 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1553 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1554 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1555 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1556
1557 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06001558 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001559 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06001560 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1561 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001562 a_it++;
1563 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06001564 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001565 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06001566 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
1567 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001568 b_it++;
1569 } else {
1570 // subtleties of arrayed interfaces:
1571 // - if is_patch, then the member is not arrayed, even though the interface may be.
1572 // - if is_block_member, then the extra array level of an arrayed interface is not
1573 // expressed in the member type -- it's expressed in the block type.
1574 if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1575 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1576 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06001577 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001578 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06001579 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
1580 describe_type(producer, a_it->second.type_id).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001581 describe_type(consumer, b_it->second.type_id).c_str());
1582 }
1583 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06001584 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001585 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001586 "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 -07001587 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1588 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1589 }
1590 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06001591 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001592 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001593 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1594 a_first.second, producer_stage->name, consumer_stage->name);
1595 }
1596 a_it++;
1597 b_it++;
1598 }
1599 }
1600
1601 return skip;
1602}
1603
1604// Validate that the shaders used by the given pipeline and store the active_slots
1605// that are actually used by the pipeline into pPipeline->active_slots
Chris Forbesa400a8a2017-07-20 13:10:24 -07001606bool validate_and_capture_pipeline_shader_state(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1607 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001608 int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1609 int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
1610 auto report_data = GetReportData(dev_data);
1611
1612 shader_module const *shaders[5];
1613 memset(shaders, 0, sizeof(shaders));
1614 spirv_inst_iter entrypoints[5];
1615 memset(entrypoints, 0, sizeof(entrypoints));
1616 bool skip = false;
1617
1618 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1619 auto pStage = &pCreateInfo->pStages[i];
1620 auto stage_id = get_shader_stage_id(pStage->stage);
Chris Forbesa400a8a2017-07-20 13:10:24 -07001621 skip |= validate_pipeline_shader_stage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id]);
Chris Forbes47567b72017-06-09 12:09:45 -07001622 }
1623
1624 // if the shader stages are no good individually, cross-stage validation is pointless.
1625 if (skip) return true;
1626
1627 auto vi = pCreateInfo->pVertexInputState;
1628
1629 if (vi) {
1630 skip |= validate_vi_consistency(report_data, vi);
1631 }
1632
1633 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
1634 skip |= validate_vi_against_vs_inputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
1635 }
1636
1637 int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1638 int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
1639
1640 while (!shaders[producer] && producer != fragment_stage) {
1641 producer++;
1642 consumer++;
1643 }
1644
1645 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1646 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001647 if (shaders[consumer]) {
1648 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
1649 skip |= validate_interface_between_stages(report_data, shaders[producer], entrypoints[producer],
1650 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1651 &shader_stage_attribs[consumer]);
1652 }
Chris Forbes47567b72017-06-09 12:09:45 -07001653
1654 producer = consumer;
1655 }
1656 }
1657
1658 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001659 skip |= validate_fs_outputs_against_render_pass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1660 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001661 }
1662
1663 return skip;
1664}
1665
Chris Forbesa400a8a2017-07-20 13:10:24 -07001666bool validate_compute_pipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1667 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001668
1669 shader_module const *module;
1670 spirv_inst_iter entrypoint;
1671
Chris Forbesa400a8a2017-07-20 13:10:24 -07001672 return validate_pipeline_shader_stage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint);
Chris Forbes47567b72017-06-09 12:09:45 -07001673}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001674
Dave Houltona9df0ce2018-02-07 10:51:23 -07001675uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001676
Dave Houltona9df0ce2018-02-07 10:51:23 -07001677static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001678 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1679 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1680 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1681 }
1682
1683 return nullptr;
1684}
1685
Chris Forbes4ae55b32017-06-09 14:42:56 -07001686bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1687 bool skip = false;
1688 spv_result_t spv_valid = SPV_SUCCESS;
1689 auto report_data = GetReportData(dev_data);
1690
1691 if (GetDisables(dev_data)->shader_validation) {
1692 return false;
1693 }
1694
Cort Strattond2742852018-05-03 13:42:10 -04001695 auto have_glsl_shader = GetDeviceExtensions(dev_data)->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07001696
1697 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houlton78d09922018-05-17 15:48:45 -06001698 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1699 "VUID-VkShaderModuleCreateInfo-pCode-01376",
1700 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
1701 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001702 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001703 auto cache = GetValidationCacheInfo(pCreateInfo);
1704 uint32_t hash = 0;
1705 if (cache) {
1706 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001707 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001708 }
1709
Chris Forbes4ae55b32017-06-09 14:42:56 -07001710 // Use SPIRV-Tools validator to try and catch any issues with the module itself
1711 spv_context ctx = spvContextCreate(SPV_ENV_VULKAN_1_0);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001712 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001713 spv_diagnostic diag = nullptr;
1714
1715 spv_valid = spvValidate(ctx, &binary, &diag);
1716 if (spv_valid != SPV_SUCCESS) {
1717 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001718 skip |=
1719 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001720 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001721 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07001722 }
Chris Forbes9a61e082017-07-24 15:35:29 -07001723 } else {
1724 if (cache) {
1725 cache->Insert(hash);
1726 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07001727 }
1728
1729 spvDiagnosticDestroy(diag);
1730 spvContextDestroy(ctx);
1731 }
1732
1733 *spirv_valid = (spv_valid == SPV_SUCCESS);
1734 return skip;
1735}