blob: c6697f90f4f9854da2fe6b79f07298f7a7cbe0fc [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,
771 spirv_inst_iter entrypoint, VkRenderPassCreateInfo const *rpci,
772 uint32_t subpass_index) {
773 std::map<uint32_t, VkFormat> color_attachments;
774 auto subpass = rpci->pSubpasses[subpass_index];
775 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
776 uint32_t attachment = subpass.pColorAttachments[i].attachment;
777 if (attachment == VK_ATTACHMENT_UNUSED) continue;
778 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
779 color_attachments[i] = rpci->pAttachments[attachment].format;
780 }
781 }
782
783 bool skip = false;
784
785 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
786
787 auto outputs = collect_interface_by_location(fs, entrypoint, spv::StorageClassOutput, false);
788
789 auto it_a = outputs.begin();
790 auto it_b = color_attachments.begin();
791
792 // Walk attachment list and outputs together
793
794 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
795 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
796 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
797
798 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
799 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
800 SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
801 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
802 it_a++;
803 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
804 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
805 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Attachment %d not written by fragment shader", it_b->first);
806 it_b++;
807 } else {
808 unsigned output_type = get_fundamental_type(fs, it_a->second.type_id);
809 unsigned att_type = get_format_type(it_b->second);
810
811 // Type checking
812 if (!(output_type & att_type)) {
813 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
814 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
815 "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
816 string_VkFormat(it_b->second), describe_type(fs, it_a->second.type_id).c_str());
817 }
818
819 // OK!
820 it_a++;
821 it_b++;
822 }
823 }
824
825 return skip;
826}
827
828// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
829// important for identifying the set of shader resources actually used by an entrypoint, for example.
830// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
831// - NOT the shader input/output interfaces.
832//
833// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
834// converting parts of this to be generated from the machine-readable spec instead.
835static std::unordered_set<uint32_t> mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint) {
836 std::unordered_set<uint32_t> ids;
837 std::unordered_set<uint32_t> worklist;
838 worklist.insert(entrypoint.word(2));
839
840 while (!worklist.empty()) {
841 auto id_iter = worklist.begin();
842 auto id = *id_iter;
843 worklist.erase(id_iter);
844
845 auto insn = src->get_def(id);
846 if (insn == src->end()) {
847 // ID is something we didn't collect in build_def_index. that's OK -- we'll stumble across all kinds of things here
848 // that we may not care about.
849 continue;
850 }
851
852 // Try to add to the output set
853 if (!ids.insert(id).second) {
854 continue; // If we already saw this id, we don't want to walk it again.
855 }
856
857 switch (insn.opcode()) {
858 case spv::OpFunction:
859 // Scan whole body of the function, enlisting anything interesting
860 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
861 switch (insn.opcode()) {
862 case spv::OpLoad:
863 case spv::OpAtomicLoad:
864 case spv::OpAtomicExchange:
865 case spv::OpAtomicCompareExchange:
866 case spv::OpAtomicCompareExchangeWeak:
867 case spv::OpAtomicIIncrement:
868 case spv::OpAtomicIDecrement:
869 case spv::OpAtomicIAdd:
870 case spv::OpAtomicISub:
871 case spv::OpAtomicSMin:
872 case spv::OpAtomicUMin:
873 case spv::OpAtomicSMax:
874 case spv::OpAtomicUMax:
875 case spv::OpAtomicAnd:
876 case spv::OpAtomicOr:
877 case spv::OpAtomicXor:
878 worklist.insert(insn.word(3)); // ptr
879 break;
880 case spv::OpStore:
881 case spv::OpAtomicStore:
882 worklist.insert(insn.word(1)); // ptr
883 break;
884 case spv::OpAccessChain:
885 case spv::OpInBoundsAccessChain:
886 worklist.insert(insn.word(3)); // base ptr
887 break;
888 case spv::OpSampledImage:
889 case spv::OpImageSampleImplicitLod:
890 case spv::OpImageSampleExplicitLod:
891 case spv::OpImageSampleDrefImplicitLod:
892 case spv::OpImageSampleDrefExplicitLod:
893 case spv::OpImageSampleProjImplicitLod:
894 case spv::OpImageSampleProjExplicitLod:
895 case spv::OpImageSampleProjDrefImplicitLod:
896 case spv::OpImageSampleProjDrefExplicitLod:
897 case spv::OpImageFetch:
898 case spv::OpImageGather:
899 case spv::OpImageDrefGather:
900 case spv::OpImageRead:
901 case spv::OpImage:
902 case spv::OpImageQueryFormat:
903 case spv::OpImageQueryOrder:
904 case spv::OpImageQuerySizeLod:
905 case spv::OpImageQuerySize:
906 case spv::OpImageQueryLod:
907 case spv::OpImageQueryLevels:
908 case spv::OpImageQuerySamples:
909 case spv::OpImageSparseSampleImplicitLod:
910 case spv::OpImageSparseSampleExplicitLod:
911 case spv::OpImageSparseSampleDrefImplicitLod:
912 case spv::OpImageSparseSampleDrefExplicitLod:
913 case spv::OpImageSparseSampleProjImplicitLod:
914 case spv::OpImageSparseSampleProjExplicitLod:
915 case spv::OpImageSparseSampleProjDrefImplicitLod:
916 case spv::OpImageSparseSampleProjDrefExplicitLod:
917 case spv::OpImageSparseFetch:
918 case spv::OpImageSparseGather:
919 case spv::OpImageSparseDrefGather:
920 case spv::OpImageTexelPointer:
921 worklist.insert(insn.word(3)); // Image or sampled image
922 break;
923 case spv::OpImageWrite:
924 worklist.insert(insn.word(1)); // Image -- different operand order to above
925 break;
926 case spv::OpFunctionCall:
927 for (uint32_t i = 3; i < insn.len(); i++) {
928 worklist.insert(insn.word(i)); // fn itself, and all args
929 }
930 break;
931
932 case spv::OpExtInst:
933 for (uint32_t i = 5; i < insn.len(); i++) {
934 worklist.insert(insn.word(i)); // Operands to ext inst
935 }
936 break;
937 }
938 }
939 break;
940 }
941 }
942
943 return ids;
944}
945
946static bool validate_push_constant_block_against_pipeline(debug_report_data const *report_data,
947 std::vector<VkPushConstantRange> const *push_constant_ranges,
948 shader_module const *src, spirv_inst_iter type,
949 VkShaderStageFlagBits stage) {
950 bool skip = false;
951
952 // Strip off ptrs etc
953 type = get_struct_type(src, type, false);
954 assert(type != src->end());
955
956 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
957 // TODO: arrays, matrices, weird sizes
958 for (auto insn : *src) {
959 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
960 if (insn.word(3) == spv::DecorationOffset) {
961 unsigned offset = insn.word(4);
962 auto size = 4; // Bytes; TODO: calculate this based on the type
963
964 bool found_range = false;
965 for (auto const &range : *push_constant_ranges) {
966 if (range.offset <= offset && range.offset + range.size >= offset + size) {
967 found_range = true;
968
969 if ((range.stageFlags & stage) == 0) {
970 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
971 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_NOT_ACCESSIBLE_FROM_STAGE, "SC",
972 "Push constant range covering variable starting at "
973 "offset %u not accessible from stage %s",
974 offset, string_VkShaderStageFlagBits(stage));
975 }
976
977 break;
978 }
979 }
980
981 if (!found_range) {
982 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
983 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_OUT_OF_RANGE, "SC",
984 "Push constant range covering variable starting at "
985 "offset %u not declared in layout",
986 offset);
987 }
988 }
989 }
990 }
991
992 return skip;
993}
994
995static bool validate_push_constant_usage(debug_report_data const *report_data,
996 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
997 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
998 bool skip = false;
999
1000 for (auto id : accessible_ids) {
1001 auto def_insn = src->get_def(id);
1002 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1003 skip |= validate_push_constant_block_against_pipeline(report_data, push_constant_ranges, src,
1004 src->get_def(def_insn.word(1)), stage);
1005 }
1006 }
1007
1008 return skip;
1009}
1010
1011// Validate that data for each specialization entry is fully contained within the buffer.
1012static bool validate_specialization_offsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
1013 bool skip = false;
1014
1015 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1016
1017 if (spec) {
1018 for (auto i = 0u; i < spec->mapEntryCount; i++) {
1019 // TODO: This is a good place for VALIDATION_ERROR_1360060a.
1020 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
1021 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1022 VALIDATION_ERROR_1360060c, "SC",
1023 "Specialization entry %u (for constant id %u) references memory outside provided "
1024 "specialization data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER
1025 " bytes provided). %s.",
1026 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1027 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize,
1028 validation_error_map[VALIDATION_ERROR_1360060c]);
1029 }
1030 }
1031 }
1032
1033 return skip;
1034}
1035
1036static bool descriptor_type_match(shader_module const *module, uint32_t type_id, VkDescriptorType descriptor_type,
1037 unsigned &descriptor_count) {
1038 auto type = module->get_def(type_id);
1039
1040 descriptor_count = 1;
1041
1042 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
1043 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
1044 if (type.opcode() == spv::OpTypeArray) {
1045 descriptor_count *= get_constant_value(module, type.word(3));
1046 type = module->get_def(type.word(2));
1047 } else {
1048 type = module->get_def(type.word(3));
1049 }
1050 }
1051
1052 switch (type.opcode()) {
1053 case spv::OpTypeStruct: {
1054 for (auto insn : *module) {
1055 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1056 if (insn.word(2) == spv::DecorationBlock) {
1057 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
1058 descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1059 } else if (insn.word(2) == spv::DecorationBufferBlock) {
1060 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
1061 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
1062 }
1063 }
1064 }
1065
1066 // Invalid
1067 return false;
1068 }
1069
1070 case spv::OpTypeSampler:
1071 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER || descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1072
1073 case spv::OpTypeSampledImage:
1074 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
1075 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1076 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1077 auto image_type = module->get_def(type.word(2));
1078 auto dim = image_type.word(3);
1079 auto sampled = image_type.word(7);
1080 return dim == spv::DimBuffer && sampled == 1;
1081 }
1082 return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1083
1084 case spv::OpTypeImage: {
1085 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1086 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1087 auto dim = type.word(3);
1088 auto sampled = type.word(7);
1089
1090 if (dim == spv::DimSubpassData) {
1091 return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
1092 } else if (dim == spv::DimBuffer) {
1093 if (sampled == 1) {
1094 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
1095 } else {
1096 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1097 }
1098 } else if (sampled == 1) {
1099 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
1100 descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1101 } else {
1102 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
1103 }
1104 }
1105
1106 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1107 default:
1108 return false; // Mismatch
1109 }
1110}
1111
1112static bool require_feature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
1113 if (!feature) {
1114 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1115 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
1116 "Shader requires VkPhysicalDeviceFeatures::%s but is not "
1117 "enabled on the device",
1118 feature_name)) {
1119 return true;
1120 }
1121 }
1122
1123 return false;
1124}
1125
1126static bool require_extension(debug_report_data const *report_data, bool extension, char const *extension_name) {
1127 if (!extension) {
1128 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1129 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
1130 "Shader requires extension %s but is not "
1131 "enabled on the device",
1132 extension_name)) {
1133 return true;
1134 }
1135 }
1136
1137 return false;
1138}
1139
1140static bool validate_shader_capabilities(layer_data *dev_data, shader_module const *src) {
1141 bool skip = false;
1142
1143 auto report_data = GetReportData(dev_data);
1144 auto const & enabledFeatures = GetEnabledFeatures(dev_data);
1145 auto const & extensions = GetEnabledExtensions(dev_data);
1146
1147 struct CapabilityInfo {
1148 char const *name;
1149 VkBool32 const VkPhysicalDeviceFeatures::*feature;
1150 bool const DeviceExtensions::*extension;
1151 };
1152
1153 using F = VkPhysicalDeviceFeatures;
1154 using E = DeviceExtensions;
1155
1156 // clang-format off
1157 static const std::unordered_map<uint32_t, CapabilityInfo> capabilities = {
1158 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1159 // feature bits.
1160 {spv::CapabilityMatrix, {nullptr}},
1161 {spv::CapabilityShader, {nullptr}},
1162 {spv::CapabilityInputAttachment, {nullptr}},
1163 {spv::CapabilitySampled1D, {nullptr}},
1164 {spv::CapabilityImage1D, {nullptr}},
1165 {spv::CapabilitySampledBuffer, {nullptr}},
1166 {spv::CapabilityImageQuery, {nullptr}},
1167 {spv::CapabilityDerivativeControl, {nullptr}},
1168
1169 // Capabilities that are optionally supported, but require a feature to
1170 // be enabled on the device
1171 {spv::CapabilityGeometry, {"geometryShader", &F::geometryShader}},
1172 {spv::CapabilityTessellation, {"tessellationShader", &F::tessellationShader}},
1173 {spv::CapabilityFloat64, {"shaderFloat64", &F::shaderFloat64}},
1174 {spv::CapabilityInt64, {"shaderInt64", &F::shaderInt64}},
1175 {spv::CapabilityTessellationPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1176 {spv::CapabilityGeometryPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1177 {spv::CapabilityImageGatherExtended, {"shaderImageGatherExtended", &F::shaderImageGatherExtended}},
1178 {spv::CapabilityStorageImageMultisample, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1179 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"shaderUniformBufferArrayDynamicIndexing", &F::shaderUniformBufferArrayDynamicIndexing}},
1180 {spv::CapabilitySampledImageArrayDynamicIndexing, {"shaderSampledImageArrayDynamicIndexing", &F::shaderSampledImageArrayDynamicIndexing}},
1181 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"shaderStorageBufferArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1182 {spv::CapabilityStorageImageArrayDynamicIndexing, {"shaderStorageImageArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1183 {spv::CapabilityClipDistance, {"shaderClipDistance", &F::shaderClipDistance}},
1184 {spv::CapabilityCullDistance, {"shaderCullDistance", &F::shaderCullDistance}},
1185 {spv::CapabilityImageCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1186 {spv::CapabilitySampleRateShading, {"sampleRateShading", &F::sampleRateShading}},
1187 {spv::CapabilitySparseResidency, {"shaderResourceResidency", &F::shaderResourceResidency}},
1188 {spv::CapabilityMinLod, {"shaderResourceMinLod", &F::shaderResourceMinLod}},
1189 {spv::CapabilitySampledCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1190 {spv::CapabilityImageMSArray, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1191 {spv::CapabilityStorageImageExtendedFormats, {"shaderStorageImageExtendedFormats", &F::shaderStorageImageExtendedFormats}},
1192 {spv::CapabilityInterpolationFunction, {"sampleRateShading", &F::sampleRateShading}},
1193 {spv::CapabilityStorageImageReadWithoutFormat, {"shaderStorageImageReadWithoutFormat", &F::shaderStorageImageReadWithoutFormat}},
1194 {spv::CapabilityStorageImageWriteWithoutFormat, {"shaderStorageImageWriteWithoutFormat", &F::shaderStorageImageWriteWithoutFormat}},
1195 {spv::CapabilityMultiViewport, {"multiViewport", &F::multiViewport}},
1196
1197 // Capabilities that require an extension
1198 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &E::vk_khr_shader_draw_parameters}},
1199 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &E::vk_nv_geometry_shader_passthrough}},
1200 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &E::vk_nv_sample_mask_override_coverage}},
1201 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1202 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1203 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_ballot }},
1204 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_vote }},
1205 };
1206 // clang-format on
1207
1208 for (auto insn : *src) {
1209 if (insn.opcode() == spv::OpCapability) {
1210 auto it = capabilities.find(insn.word(1));
1211 if (it != capabilities.end()) {
1212 if (it->second.feature) {
1213 skip |= require_feature(report_data, enabledFeatures->*(it->second.feature), it->second.name);
1214 }
1215 if (it->second.extension) {
1216 skip |= require_extension(report_data, extensions->*(it->second.extension), it->second.name);
1217 }
1218 }
1219 }
1220 }
1221
1222 return skip;
1223}
1224
1225static uint32_t descriptor_type_to_reqs(shader_module const *module, uint32_t type_id) {
1226 auto type = module->get_def(type_id);
1227
1228 while (true) {
1229 switch (type.opcode()) {
1230 case spv::OpTypeArray:
1231 case spv::OpTypeSampledImage:
1232 type = module->get_def(type.word(2));
1233 break;
1234 case spv::OpTypePointer:
1235 type = module->get_def(type.word(3));
1236 break;
1237 case spv::OpTypeImage: {
1238 auto dim = type.word(3);
1239 auto arrayed = type.word(5);
1240 auto msaa = type.word(6);
1241
1242 switch (dim) {
1243 case spv::Dim1D:
1244 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1245 case spv::Dim2D:
1246 return (msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE) |
1247 (arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D);
1248 case spv::Dim3D:
1249 return DESCRIPTOR_REQ_VIEW_TYPE_3D;
1250 case spv::DimCube:
1251 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1252 case spv::DimSubpassData:
1253 return msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1254 default: // buffer, etc.
1255 return 0;
1256 }
1257 }
1258 default:
1259 return 0;
1260 }
1261 }
1262}
1263
1264// For given pipelineLayout verify that the set_layout_node at slot.first
1265// has the requested binding at slot.second and return ptr to that binding
1266static VkDescriptorSetLayoutBinding const *get_descriptor_binding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1267 descriptor_slot_t slot) {
1268 if (!pipelineLayout) return nullptr;
1269
1270 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1271
1272 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1273}
1274
1275
1276static bool validate_pipeline_shader_stage(
1277 layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
1278 shader_module const **out_module, spirv_inst_iter *out_entrypoint) {
1279 bool skip = false;
1280 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1281 auto report_data = GetReportData(dev_data);
1282
1283 if (!module->has_valid_spirv) return false;
1284
1285 // Find the entrypoint
1286 auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
1287 if (entrypoint == module->end()) {
1288 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1289 VALIDATION_ERROR_10600586, "SC", "No entrypoint found named `%s` for stage %s. %s.", pStage->pName,
1290 string_VkShaderStageFlagBits(pStage->stage), validation_error_map[VALIDATION_ERROR_10600586])) {
1291 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1292 }
1293 }
1294
1295 // Validate shader capabilities against enabled device features
1296 skip |= validate_shader_capabilities(dev_data, module);
1297
1298 // Mark accessible ids
1299 auto accessible_ids = mark_accessible_ids(module, entrypoint);
1300
1301 // Validate descriptor set layout against what the entrypoint actually uses
1302 auto descriptor_uses = collect_interface_by_descriptor_slot(report_data, module, accessible_ids);
1303
Chris Forbes47567b72017-06-09 12:09:45 -07001304 skip |= validate_specialization_offsets(report_data, pStage);
Chris Forbesc2f751a2017-06-21 11:34:16 -07001305 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 -07001306
1307 // Validate descriptor use
1308 for (auto use : descriptor_uses) {
1309 // While validating shaders capture which slots are used by the pipeline
1310 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
1311 reqs = descriptor_req(reqs | descriptor_type_to_reqs(module, use.second.type_id));
1312
1313 // Verify given pipelineLayout has requested setLayout with requested binding
Chris Forbesc2f751a2017-06-21 11:34:16 -07001314 const auto &binding = get_descriptor_binding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001315 unsigned required_descriptor_count;
1316
1317 if (!binding) {
1318 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1319 SHADER_CHECKER_MISSING_DESCRIPTOR, "SC",
1320 "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
1321 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str());
1322 } else if (~binding->stageFlags & pStage->stage) {
1323 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1324 SHADER_CHECKER_DESCRIPTOR_NOT_ACCESSIBLE_FROM_STAGE, "SC",
1325 "Shader uses descriptor slot %u.%u (used "
1326 "as type `%s`) but descriptor not "
1327 "accessible from stage %s",
1328 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1329 string_VkShaderStageFlagBits(pStage->stage));
1330 } else if (!descriptor_type_match(module, use.second.type_id, binding->descriptorType, required_descriptor_count)) {
1331 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1332 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1333 "Type mismatch on descriptor slot "
1334 "%u.%u (used as type `%s`) but "
1335 "descriptor of type %s",
1336 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1337 string_VkDescriptorType(binding->descriptorType));
1338 } else if (binding->descriptorCount < required_descriptor_count) {
1339 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1340 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1341 "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
1342 required_descriptor_count, use.first.first, use.first.second,
1343 describe_type(module, use.second.type_id).c_str(), binding->descriptorCount);
1344 }
1345 }
1346
1347 // Validate use of input attachments against subpass structure
1348 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1349 auto input_attachment_uses = collect_interface_by_input_attachment_index(module, accessible_ids);
1350
1351 auto rpci = pipeline->render_pass_ci.ptr();
1352 auto subpass = pipeline->graphicsPipelineCI.subpass;
1353
1354 for (auto use : input_attachment_uses) {
1355 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1356 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
1357 ? input_attachments[use.first].attachment
1358 : VK_ATTACHMENT_UNUSED;
1359
1360 if (index == VK_ATTACHMENT_UNUSED) {
1361 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1362 SHADER_CHECKER_MISSING_INPUT_ATTACHMENT, "SC",
1363 "Shader consumes input attachment index %d but not provided in subpass", use.first);
1364 } else if (!(get_format_type(rpci->pAttachments[index].format) & get_fundamental_type(module, use.second.type_id))) {
1365 skip |=
1366 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1367 SHADER_CHECKER_INPUT_ATTACHMENT_TYPE_MISMATCH, "SC",
1368 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
1369 string_VkFormat(rpci->pAttachments[index].format), describe_type(module, use.second.type_id).c_str());
1370 }
1371 }
1372 }
1373
1374 return skip;
1375}
1376
1377static bool validate_interface_between_stages(debug_report_data const *report_data, shader_module const *producer,
1378 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1379 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1380 shader_stage_attributes const *consumer_stage) {
1381 bool skip = false;
1382
1383 auto outputs =
1384 collect_interface_by_location(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1385 auto inputs =
1386 collect_interface_by_location(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
1387
1388 auto a_it = outputs.begin();
1389 auto b_it = inputs.begin();
1390
1391 // Maps sorted by key (location); walk them together to find mismatches
1392 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1393 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1394 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1395 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1396 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1397
1398 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
1399 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1400 __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1401 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1402 a_first.second, consumer_stage->name);
1403 a_it++;
1404 } else if (a_at_end || a_first > b_first) {
1405 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1406 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "%s consumes input location %u.%u which is not written by %s",
1407 consumer_stage->name, b_first.first, b_first.second, producer_stage->name);
1408 b_it++;
1409 } else {
1410 // subtleties of arrayed interfaces:
1411 // - if is_patch, then the member is not arrayed, even though the interface may be.
1412 // - if is_block_member, then the extra array level of an arrayed interface is not
1413 // expressed in the member type -- it's expressed in the block type.
1414 if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1415 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1416 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
1417 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1418 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC", "Type mismatch on location %u.%u: '%s' vs '%s'",
1419 a_first.first, a_first.second, describe_type(producer, a_it->second.type_id).c_str(),
1420 describe_type(consumer, b_it->second.type_id).c_str());
1421 }
1422 if (a_it->second.is_patch != b_it->second.is_patch) {
1423 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1424 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1425 "Decoration mismatch on location %u.%u: is per-%s in %s stage but "
1426 "per-%s in %s stage",
1427 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1428 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1429 }
1430 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
1431 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1432 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1433 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1434 a_first.second, producer_stage->name, consumer_stage->name);
1435 }
1436 a_it++;
1437 b_it++;
1438 }
1439 }
1440
1441 return skip;
1442}
1443
1444// Validate that the shaders used by the given pipeline and store the active_slots
1445// that are actually used by the pipeline into pPipeline->active_slots
1446bool validate_and_capture_pipeline_shader_state(layer_data *dev_data, PIPELINE_STATE *pPipeline) {
1447 auto pCreateInfo = pPipeline->graphicsPipelineCI.ptr();
1448 int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1449 int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
1450 auto report_data = GetReportData(dev_data);
1451
1452 shader_module const *shaders[5];
1453 memset(shaders, 0, sizeof(shaders));
1454 spirv_inst_iter entrypoints[5];
1455 memset(entrypoints, 0, sizeof(entrypoints));
1456 bool skip = false;
1457
1458 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1459 auto pStage = &pCreateInfo->pStages[i];
1460 auto stage_id = get_shader_stage_id(pStage->stage);
1461 skip |= validate_pipeline_shader_stage(dev_data, pStage, pPipeline, &shaders[stage_id], &entrypoints[stage_id]);
1462 }
1463
1464 // if the shader stages are no good individually, cross-stage validation is pointless.
1465 if (skip) return true;
1466
1467 auto vi = pCreateInfo->pVertexInputState;
1468
1469 if (vi) {
1470 skip |= validate_vi_consistency(report_data, vi);
1471 }
1472
1473 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
1474 skip |= validate_vi_against_vs_inputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
1475 }
1476
1477 int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1478 int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
1479
1480 while (!shaders[producer] && producer != fragment_stage) {
1481 producer++;
1482 consumer++;
1483 }
1484
1485 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1486 assert(shaders[producer]);
1487 if (shaders[consumer] && shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
1488 skip |= validate_interface_between_stages(report_data, shaders[producer], entrypoints[producer],
1489 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1490 &shader_stage_attribs[consumer]);
1491
1492 producer = consumer;
1493 }
1494 }
1495
1496 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
1497 skip |= validate_fs_outputs_against_render_pass(report_data, shaders[fragment_stage], entrypoints[fragment_stage],
1498 pPipeline->render_pass_ci.ptr(), pCreateInfo->subpass);
1499 }
1500
1501 return skip;
1502}
1503
1504bool validate_compute_pipeline(layer_data *dev_data, PIPELINE_STATE *pPipeline) {
1505 auto pCreateInfo = pPipeline->computePipelineCI.ptr();
1506
1507 shader_module const *module;
1508 spirv_inst_iter entrypoint;
1509
1510 return validate_pipeline_shader_stage(dev_data, &pCreateInfo->stage, pPipeline, &module, &entrypoint);
1511}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001512
1513bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1514 bool skip = false;
1515 spv_result_t spv_valid = SPV_SUCCESS;
1516 auto report_data = GetReportData(dev_data);
1517
1518 if (GetDisables(dev_data)->shader_validation) {
1519 return false;
1520 }
1521
1522 auto have_glsl_shader = GetEnabledExtensions(dev_data)->vk_nv_glsl_shader;
1523
1524 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
1525 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1526 __LINE__, VALIDATION_ERROR_12a00ac0, "SC",
1527 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ". %s",
1528 pCreateInfo->codeSize, validation_error_map[VALIDATION_ERROR_12a00ac0]);
1529 } else {
1530 // Use SPIRV-Tools validator to try and catch any issues with the module itself
1531 spv_context ctx = spvContextCreate(SPV_ENV_VULKAN_1_0);
1532 spv_const_binary_t binary{ pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t) };
1533 spv_diagnostic diag = nullptr;
1534
1535 spv_valid = spvValidate(ctx, &binary, &diag);
1536 if (spv_valid != SPV_SUCCESS) {
1537 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
1538 skip |= log_msg(report_data,
1539 spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
1540 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__, SHADER_CHECKER_INCONSISTENT_SPIRV, "SC",
1541 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
1542 }
1543 }
1544
1545 spvDiagnosticDestroy(diag);
1546 spvContextDestroy(ctx);
1547 }
1548
1549 *spirv_valid = (spv_valid == SPV_SUCCESS);
1550 return skip;
1551}