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