blob: d20f60cf2c54840fedbdd9301d0d17dbb4b46c98 [file] [log] [blame]
Dave Houlton51653902018-06-22 17:32:13 -06001/* Copyright (c) 2015-2018 The Khronos Group Inc.
2 * Copyright (c) 2015-2018 Valve Corporation
3 * Copyright (c) 2015-2018 LunarG, Inc.
4 * Copyright (C) 2015-2018 Google Inc.
Chris Forbes47567b72017-06-09 12:09:45 -07005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060019 * Author: Dave Houlton <daveh@lunarg.com>
Chris Forbes47567b72017-06-09 12:09:45 -070020 */
21
22#include <cinttypes>
23#include <cassert>
24#include <vector>
25#include <unordered_map>
26#include <string>
27#include <sstream>
28#include <SPIRV/spirv.hpp>
29#include "vk_loader_platform.h"
30#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070031#include "vk_layer_data.h"
32#include "vk_layer_extension_utils.h"
33#include "vk_layer_utils.h"
34#include "core_validation.h"
35#include "core_validation_types.h"
36#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070037#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070038#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039
40enum FORMAT_TYPE {
41 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
42 FORMAT_TYPE_SINT = 2,
43 FORMAT_TYPE_UINT = 4,
44};
45
46typedef std::pair<unsigned, unsigned> location_t;
47
48struct interface_var {
49 uint32_t id;
50 uint32_t type_id;
51 uint32_t offset;
52 bool is_patch;
53 bool is_block_member;
54 bool is_relaxed_precision;
55 // TODO: collect the name, too? Isn't required to be present.
56};
57
58struct shader_stage_attributes {
59 char const *const name;
60 bool arrayed_input;
61 bool arrayed_output;
62};
63
64static shader_stage_attributes shader_stage_attribs[] = {
65 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
66 {"geometry shader", true, false}, {"fragment shader", false, false},
67};
68
69// SPIRV utility functions
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060070void shader_module::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -070071 for (auto insn : *this) {
72 switch (insn.opcode()) {
73 // Types
74 case spv::OpTypeVoid:
75 case spv::OpTypeBool:
76 case spv::OpTypeInt:
77 case spv::OpTypeFloat:
78 case spv::OpTypeVector:
79 case spv::OpTypeMatrix:
80 case spv::OpTypeImage:
81 case spv::OpTypeSampler:
82 case spv::OpTypeSampledImage:
83 case spv::OpTypeArray:
84 case spv::OpTypeRuntimeArray:
85 case spv::OpTypeStruct:
86 case spv::OpTypeOpaque:
87 case spv::OpTypePointer:
88 case spv::OpTypeFunction:
89 case spv::OpTypeEvent:
90 case spv::OpTypeDeviceEvent:
91 case spv::OpTypeReserveId:
92 case spv::OpTypeQueue:
93 case spv::OpTypePipe:
Jeff Bolz105d6492018-09-29 15:46:44 -050094 case spv::OpTypeAccelerationStructureNVX:
Chris Forbes47567b72017-06-09 12:09:45 -070095 def_index[insn.word(1)] = insn.offset();
96 break;
97
98 // Fixed constants
99 case spv::OpConstantTrue:
100 case spv::OpConstantFalse:
101 case spv::OpConstant:
102 case spv::OpConstantComposite:
103 case spv::OpConstantSampler:
104 case spv::OpConstantNull:
105 def_index[insn.word(2)] = insn.offset();
106 break;
107
108 // Specialization constants
109 case spv::OpSpecConstantTrue:
110 case spv::OpSpecConstantFalse:
111 case spv::OpSpecConstant:
112 case spv::OpSpecConstantComposite:
113 case spv::OpSpecConstantOp:
114 def_index[insn.word(2)] = insn.offset();
115 break;
116
117 // Variables
118 case spv::OpVariable:
119 def_index[insn.word(2)] = insn.offset();
120 break;
121
122 // Functions
123 case spv::OpFunction:
124 def_index[insn.word(2)] = insn.offset();
125 break;
126
127 default:
128 // We don't care about any other defs for now.
129 break;
130 }
131 }
132}
133
Jeff Bolz105d6492018-09-29 15:46:44 -0500134unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
135 switch (mode) {
136 case spv::ExecutionModelVertex:
137 return VK_SHADER_STAGE_VERTEX_BIT;
138 case spv::ExecutionModelTessellationControl:
139 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
140 case spv::ExecutionModelTessellationEvaluation:
141 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
142 case spv::ExecutionModelGeometry:
143 return VK_SHADER_STAGE_GEOMETRY_BIT;
144 case spv::ExecutionModelFragment:
145 return VK_SHADER_STAGE_FRAGMENT_BIT;
146 case spv::ExecutionModelGLCompute:
147 return VK_SHADER_STAGE_COMPUTE_BIT;
148 case spv::ExecutionModelRayGenerationNVX:
149 return VK_SHADER_STAGE_RAYGEN_BIT_NVX;
150 case spv::ExecutionModelAnyHitNVX:
151 return VK_SHADER_STAGE_ANY_HIT_BIT_NVX;
152 case spv::ExecutionModelClosestHitNVX:
153 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NVX;
154 case spv::ExecutionModelMissNVX:
155 return VK_SHADER_STAGE_MISS_BIT_NVX;
156 case spv::ExecutionModelIntersectionNVX:
157 return VK_SHADER_STAGE_INTERSECTION_BIT_NVX;
158 case spv::ExecutionModelCallableNVX:
159 return VK_SHADER_STAGE_CALLABLE_BIT_NVX;
160 case spv::ExecutionModelTaskNV:
161 return VK_SHADER_STAGE_TASK_BIT_NV;
162 case spv::ExecutionModelMeshNV:
163 return VK_SHADER_STAGE_MESH_BIT_NV;
164 default:
165 return 0;
166 }
167}
168
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600169static spirv_inst_iter FindEntrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
Chris Forbes47567b72017-06-09 12:09:45 -0700170 for (auto insn : *src) {
171 if (insn.opcode() == spv::OpEntryPoint) {
172 auto entrypointName = (char const *)&insn.word(3);
Jeff Bolz105d6492018-09-29 15:46:44 -0500173 auto executionModel = insn.word(1);
174 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
Chris Forbes47567b72017-06-09 12:09:45 -0700175
176 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
177 return insn;
178 }
179 }
180 }
181
182 return src->end();
183}
184
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600185static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700186 switch (sc) {
187 case spv::StorageClassInput:
188 return "input";
189 case spv::StorageClassOutput:
190 return "output";
191 case spv::StorageClassUniformConstant:
192 return "const uniform";
193 case spv::StorageClassUniform:
194 return "uniform";
195 case spv::StorageClassWorkgroup:
196 return "workgroup local";
197 case spv::StorageClassCrossWorkgroup:
198 return "workgroup global";
199 case spv::StorageClassPrivate:
200 return "private global";
201 case spv::StorageClassFunction:
202 return "function";
203 case spv::StorageClassGeneric:
204 return "generic";
205 case spv::StorageClassAtomicCounter:
206 return "atomic counter";
207 case spv::StorageClassImage:
208 return "image";
209 case spv::StorageClassPushConstant:
210 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800211 case spv::StorageClassStorageBuffer:
212 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700213 default:
214 return "unknown";
215 }
216}
217
218// Get the value of an integral constant
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600219unsigned GetConstantValue(shader_module const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700220 auto value = src->get_def(id);
221 assert(value != src->end());
222
223 if (value.opcode() != spv::OpConstant) {
224 // TODO: Either ensure that the specialization transform is already performed on a module we're
225 // considering here, OR -- specialize on the fly now.
226 return 1;
227 }
228
229 return value.word(3);
230}
231
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600232static void DescribeTypeInner(std::ostringstream &ss, shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700233 auto insn = src->get_def(type);
234 assert(insn != src->end());
235
236 switch (insn.opcode()) {
237 case spv::OpTypeBool:
238 ss << "bool";
239 break;
240 case spv::OpTypeInt:
241 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
242 break;
243 case spv::OpTypeFloat:
244 ss << "float" << insn.word(2);
245 break;
246 case spv::OpTypeVector:
247 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600248 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700249 break;
250 case spv::OpTypeMatrix:
251 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600252 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700253 break;
254 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600255 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
256 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700257 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700258 case spv::OpTypeRuntimeArray:
259 ss << "runtime arr[] of ";
260 DescribeTypeInner(ss, src, insn.word(2));
261 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700262 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600263 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
264 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700265 break;
266 case spv::OpTypeStruct: {
267 ss << "struct of (";
268 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600269 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700270 if (i == insn.len() - 1) {
271 ss << ")";
272 } else {
273 ss << ", ";
274 }
275 }
276 break;
277 }
278 case spv::OpTypeSampler:
279 ss << "sampler";
280 break;
281 case spv::OpTypeSampledImage:
282 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600283 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700284 break;
285 case spv::OpTypeImage:
286 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
287 break;
Jeff Bolz105d6492018-09-29 15:46:44 -0500288 case spv::OpTypeAccelerationStructureNVX:
289 ss << "accelerationStruture";
290 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700291 default:
292 ss << "oddtype";
293 break;
294 }
295}
296
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600297static std::string DescribeType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700298 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600299 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700300 return ss.str();
301}
302
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600303static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700304 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
305 return type.word(2) < 64;
306}
307
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600308static bool TypesMatch(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
309 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700310 // Walk two type trees together, and complain about differences
311 auto a_insn = a->get_def(a_type);
312 auto b_insn = b->get_def(b_type);
313 assert(a_insn != a->end());
314 assert(b_insn != b->end());
315
Chris Forbes062f1222018-08-21 15:34:15 -0700316 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
317
Chris Forbes47567b72017-06-09 12:09:45 -0700318 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600319 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700320 }
321
322 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
323 // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600324 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700325 }
326
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600327 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
328 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700329 }
330
331 if (a_insn.opcode() != b_insn.opcode()) {
332 return false;
333 }
334
335 if (a_insn.opcode() == spv::OpTypePointer) {
336 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600337 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700338 }
339
340 if (a_arrayed || b_arrayed) {
341 // If we havent resolved array-of-verts by here, we're not going to.
342 return false;
343 }
344
345 switch (a_insn.opcode()) {
346 case spv::OpTypeBool:
347 return true;
348 case spv::OpTypeInt:
349 // Match on width, signedness
350 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
351 case spv::OpTypeFloat:
352 // Match on width
353 return a_insn.word(2) == b_insn.word(2);
354 case spv::OpTypeVector:
355 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600356 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
357 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 return a_insn.word(3) >= b_insn.word(3);
359 } else {
360 return a_insn.word(3) == b_insn.word(3);
361 }
362 case spv::OpTypeMatrix:
363 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600364 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700365 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700366 case spv::OpTypeArray:
367 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
368 // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600369 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
370 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700371 case spv::OpTypeStruct:
372 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700373 {
374 if (a_insn.len() != b_insn.len()) {
375 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700376 }
Chris Forbes47567b72017-06-09 12:09:45 -0700377
Dave Houltona9df0ce2018-02-07 10:51:23 -0700378 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600379 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700380 return false;
381 }
382 }
383
384 return true;
385 }
Chris Forbes47567b72017-06-09 12:09:45 -0700386 default:
387 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
388 return false;
389 }
390}
391
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600392static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700393 auto it = map.find(id);
394 if (it == map.end())
395 return def;
396 else
397 return it->second;
398}
399
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600400static unsigned GetLocationsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700401 auto insn = src->get_def(type);
402 assert(insn != src->end());
403
404 switch (insn.opcode()) {
405 case spv::OpTypePointer:
406 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
407 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600408 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700409 case spv::OpTypeArray:
410 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600411 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700412 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700414 }
415 case spv::OpTypeMatrix:
416 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600417 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700418 case spv::OpTypeVector: {
419 auto scalar_type = src->get_def(insn.word(2));
420 auto bit_width =
421 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
422
423 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
424 return (bit_width * insn.word(3) + 127) / 128;
425 }
426 default:
427 // Everything else is just 1.
428 return 1;
429
430 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
431 }
432}
433
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600434static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700435 switch (format) {
436 case VK_FORMAT_R64G64B64A64_SFLOAT:
437 case VK_FORMAT_R64G64B64A64_SINT:
438 case VK_FORMAT_R64G64B64A64_UINT:
439 case VK_FORMAT_R64G64B64_SFLOAT:
440 case VK_FORMAT_R64G64B64_SINT:
441 case VK_FORMAT_R64G64B64_UINT:
442 return 2;
443 default:
444 return 1;
445 }
446}
447
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600448static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700449 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
450 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
451 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
452 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700453 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
454 return FORMAT_TYPE_FLOAT;
455}
456
457// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
Chris Forbes062f1222018-08-21 15:34:15 -0700458// also used for input attachments, as we statically know their format.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600459static unsigned GetFundamentalType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700460 auto insn = src->get_def(type);
461 assert(insn != src->end());
462
463 switch (insn.opcode()) {
464 case spv::OpTypeInt:
465 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
466 case spv::OpTypeFloat:
467 return FORMAT_TYPE_FLOAT;
468 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700469 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700470 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700471 case spv::OpTypeRuntimeArray:
472 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600473 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700474 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600475 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700476
477 default:
478 return 0;
479 }
480}
481
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600482static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700483 uint32_t bit_pos = uint32_t(u_ffs(stage));
484 return bit_pos - 1;
485}
486
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600487static spirv_inst_iter GetStructType(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700488 while (true) {
489 if (def.opcode() == spv::OpTypePointer) {
490 def = src->get_def(def.word(3));
491 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
492 def = src->get_def(def.word(2));
493 is_array_of_verts = false;
494 } else if (def.opcode() == spv::OpTypeStruct) {
495 return def;
496 } else {
497 return src->end();
498 }
499 }
500}
501
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600502static bool CollectInterfaceBlockMembers(shader_module const *src, std::map<location_t, interface_var> *out,
503 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts, uint32_t id,
504 uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700505 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600506 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700507 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
508 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700509 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700510 }
511
512 std::unordered_map<unsigned, unsigned> member_components;
513 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700514 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700515
516 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
517 for (auto insn : *src) {
518 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
519 unsigned member_index = insn.word(2);
520
521 if (insn.word(3) == spv::DecorationComponent) {
522 unsigned component = insn.word(4);
523 member_components[member_index] = component;
524 }
525
526 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
527 member_relaxed_precision[member_index] = 1;
528 }
Chris Forbesa313d772017-06-13 13:59:41 -0700529
530 if (insn.word(3) == spv::DecorationPatch) {
531 member_patch[member_index] = 1;
532 }
Chris Forbes47567b72017-06-09 12:09:45 -0700533 }
534 }
535
Chris Forbesa313d772017-06-13 13:59:41 -0700536 // TODO: correctly handle location assignment from outside
537
Chris Forbes47567b72017-06-09 12:09:45 -0700538 // Second pass -- produce the output, from Location decorations
539 for (auto insn : *src) {
540 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
541 unsigned member_index = insn.word(2);
542 unsigned member_type_id = type.word(2 + member_index);
543
544 if (insn.word(3) == spv::DecorationLocation) {
545 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600546 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700547 auto component_it = member_components.find(member_index);
548 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
549 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700550 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700551
552 for (unsigned int offset = 0; offset < num_locations; offset++) {
553 interface_var v = {};
554 v.id = id;
555 // TODO: member index in interface_var too?
556 v.type_id = member_type_id;
557 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700558 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700559 v.is_block_member = true;
560 v.is_relaxed_precision = is_relaxed_precision;
561 (*out)[std::make_pair(location + offset, component)] = v;
562 }
563 }
564 }
565 }
Chris Forbesa313d772017-06-13 13:59:41 -0700566
567 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700568}
569
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600570static std::map<location_t, interface_var> CollectInterfaceByLocation(shader_module const *src, spirv_inst_iter entrypoint,
571 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700572 std::unordered_map<unsigned, unsigned> var_locations;
573 std::unordered_map<unsigned, unsigned> var_builtins;
574 std::unordered_map<unsigned, unsigned> var_components;
575 std::unordered_map<unsigned, unsigned> blocks;
576 std::unordered_map<unsigned, unsigned> var_patch;
577 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
578
579 for (auto insn : *src) {
580 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
581 // fits neither model.
582 if (insn.opcode() == spv::OpDecorate) {
583 if (insn.word(2) == spv::DecorationLocation) {
584 var_locations[insn.word(1)] = insn.word(3);
585 }
586
587 if (insn.word(2) == spv::DecorationBuiltIn) {
588 var_builtins[insn.word(1)] = insn.word(3);
589 }
590
591 if (insn.word(2) == spv::DecorationComponent) {
592 var_components[insn.word(1)] = insn.word(3);
593 }
594
595 if (insn.word(2) == spv::DecorationBlock) {
596 blocks[insn.word(1)] = 1;
597 }
598
599 if (insn.word(2) == spv::DecorationPatch) {
600 var_patch[insn.word(1)] = 1;
601 }
602
603 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
604 var_relaxed_precision[insn.word(1)] = 1;
605 }
606 }
607 }
608
609 // TODO: handle grouped decorations
610 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
611
612 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
613 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
614 uint32_t word = 3;
615 while (entrypoint.word(word) & 0xff000000u) {
616 ++word;
617 }
618 ++word;
619
620 std::map<location_t, interface_var> out;
621
622 for (; word < entrypoint.len(); word++) {
623 auto insn = src->get_def(entrypoint.word(word));
624 assert(insn != src->end());
625 assert(insn.opcode() == spv::OpVariable);
626
627 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
628 unsigned id = insn.word(2);
629 unsigned type = insn.word(1);
630
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600631 int location = ValueOrDefault(var_locations, id, static_cast<unsigned>(-1));
632 int builtin = ValueOrDefault(var_builtins, id, static_cast<unsigned>(-1));
633 unsigned component = ValueOrDefault(var_components, id, 0); // Unspecified is OK, is 0
Chris Forbes47567b72017-06-09 12:09:45 -0700634 bool is_patch = var_patch.find(id) != var_patch.end();
635 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
636
Dave Houltona9df0ce2018-02-07 10:51:23 -0700637 if (builtin != -1)
638 continue;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600639 else if (!CollectInterfaceBlockMembers(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700640 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
641 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600642 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700643 for (unsigned int offset = 0; offset < num_locations; offset++) {
644 interface_var v = {};
645 v.id = id;
646 v.type_id = type;
647 v.offset = offset;
648 v.is_patch = is_patch;
649 v.is_relaxed_precision = is_relaxed_precision;
650 out[std::make_pair(location + offset, component)] = v;
651 }
Chris Forbes47567b72017-06-09 12:09:45 -0700652 }
653 }
654 }
655
656 return out;
657}
658
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600659static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Chris Forbes47567b72017-06-09 12:09:45 -0700660 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
661 std::vector<std::pair<uint32_t, interface_var>> out;
662
663 for (auto insn : *src) {
664 if (insn.opcode() == spv::OpDecorate) {
665 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
666 auto attachment_index = insn.word(3);
667 auto id = insn.word(1);
668
669 if (accessible_ids.count(id)) {
670 auto def = src->get_def(id);
671 assert(def != src->end());
672
673 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600674 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700675 for (unsigned int offset = 0; offset < num_locations; offset++) {
676 interface_var v = {};
677 v.id = id;
678 v.type_id = def.word(1);
679 v.offset = offset;
680 out.emplace_back(attachment_index + offset, v);
681 }
682 }
683 }
684 }
685 }
686 }
687
688 return out;
689}
690
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600691static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id) {
Chris Forbes8af24522018-03-07 11:37:45 -0800692 auto type = module->get_def(type_id);
693
694 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Chris Forbes062f1222018-08-21 15:34:15 -0700695 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
696 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
697 // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800698 type = module->get_def(type.word(2));
699 } else {
Chris Forbes928b2bd2018-03-14 09:28:35 -0700700 if (type.word(2) == spv::StorageClassStorageBuffer) {
701 return true;
702 }
Chris Forbes8af24522018-03-07 11:37:45 -0800703 type = module->get_def(type.word(3));
704 }
705 }
706
707 switch (type.opcode()) {
708 case spv::OpTypeImage: {
709 auto dim = type.word(3);
710 auto sampled = type.word(7);
711 return sampled == 2 && dim != spv::DimSubpassData;
712 }
713
714 case spv::OpTypeStruct:
715 for (auto insn : *module) {
716 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
717 if (insn.word(2) == spv::DecorationBufferBlock) {
718 return true;
719 }
720 }
721 }
722 }
723
724 return false;
725}
726
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600727static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800728 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
729 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700730 std::unordered_map<unsigned, unsigned> var_sets;
731 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800732 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700733
734 for (auto insn : *src) {
735 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
736 // DecorationDescriptorSet and DecorationBinding.
737 if (insn.opcode() == spv::OpDecorate) {
738 if (insn.word(2) == spv::DecorationDescriptorSet) {
739 var_sets[insn.word(1)] = insn.word(3);
740 }
741
742 if (insn.word(2) == spv::DecorationBinding) {
743 var_bindings[insn.word(1)] = insn.word(3);
744 }
Chris Forbes8af24522018-03-07 11:37:45 -0800745
746 if (insn.word(2) == spv::DecorationNonWritable) {
747 var_nonwritable[insn.word(1)] = 1;
748 }
Chris Forbes47567b72017-06-09 12:09:45 -0700749 }
750 }
751
752 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
753
754 for (auto id : accessible_ids) {
755 auto insn = src->get_def(id);
756 assert(insn != src->end());
757
758 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800759 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
760 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600761 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
762 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700763
764 interface_var v = {};
765 v.id = insn.word(2);
766 v.type_id = insn.word(1);
767 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800768
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600769 if (var_nonwritable.find(id) == var_nonwritable.end() && IsWritableDescriptorType(src, insn.word(1))) {
Chris Forbes8af24522018-03-07 11:37:45 -0800770 *has_writable_descriptor = true;
771 }
Chris Forbes47567b72017-06-09 12:09:45 -0700772 }
773 }
774
775 return out;
776}
777
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600778static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700779 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
780 // be specified only once.
781 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
782 bool skip = false;
783
784 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
785 auto desc = &vi->pVertexBindingDescriptions[i];
786 auto &binding = bindings[desc->binding];
787 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600788 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600789 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -0600790 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700791 desc->binding);
792 } else {
793 binding = desc;
794 }
795 }
796
797 return skip;
798}
799
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600800static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
801 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700802 bool skip = false;
803
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600804 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700805
806 // Build index by location
807 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
808 if (vi) {
809 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600810 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700811 for (auto j = 0u; j < num_locations; j++) {
812 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
813 }
814 }
815 }
816
817 auto it_a = attribs.begin();
818 auto it_b = inputs.begin();
819 bool used = false;
820
821 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
822 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
823 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
824 auto a_first = a_at_end ? 0 : it_a->first;
825 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600826
Chris Forbes47567b72017-06-09 12:09:45 -0700827 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600828 if (!used &&
829 log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600830 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600831 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700832 skip = true;
833 }
834 used = false;
835 it_a++;
836 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600837 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600838 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600839 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700840 it_b++;
841 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600842 unsigned attrib_type = GetFormatType(it_a->second->format);
843 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700844
845 // Type checking
846 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600847 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600848 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700849 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600850 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700851 }
852
853 // OK!
854 used = true;
855 it_b++;
856 }
857 }
858
859 return skip;
860}
861
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600862static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
863 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100864 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700865
Chris Forbes47567b72017-06-09 12:09:45 -0700866 std::map<uint32_t, VkFormat> color_attachments;
867 auto subpass = rpci->pSubpasses[subpass_index];
868 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
869 uint32_t attachment = subpass.pColorAttachments[i].attachment;
870 if (attachment == VK_ATTACHMENT_UNUSED) continue;
871 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
872 color_attachments[i] = rpci->pAttachments[attachment].format;
873 }
874 }
875
876 bool skip = false;
877
878 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
879
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600880 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700881
882 auto it_a = outputs.begin();
883 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600884 bool used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700885
886 // Walk attachment list and outputs together
887
888 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
889 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
890 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
891
892 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600893 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600894 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Chris Forbes47567b72017-06-09 12:09:45 -0700895 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
896 it_a++;
897 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700898 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
899 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600900 if (!used) {
901 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700902 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600903 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Chris Forbescfe4dca2018-10-05 10:15:00 -0700904 "Attachment %d not written by fragment shader; undefined values will be written to attachment",
905 it_b->first);
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600906 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700907 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600908 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700909 it_b++;
910 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600911 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
912 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700913
914 // Type checking
915 if (!(output_type & att_type)) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700916 skip |= log_msg(
917 report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
918 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
919 "Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
920 it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700921 }
922
923 // OK!
924 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600925 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700926 }
927 }
928
929 return skip;
930}
931
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600932// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
933// This function examines instructions in the static call tree for a write to this variable.
934static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
935 auto type = builtin_instr.opcode();
936 uint32_t target_id = builtin_instr.word(1);
937 bool init_complete = false;
938
939 if (type == spv::OpMemberDecorate) {
940 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
941 auto insn = entrypoint;
942 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
943 switch (insn.opcode()) {
944 case spv::OpTypePointer:
945 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
946 target_id = insn.word(1);
947 }
948 break;
949 case spv::OpVariable:
950 if (insn.word(1) == target_id) {
951 target_id = insn.word(2);
952 init_complete = true;
953 }
954 break;
955 }
956 insn++;
957 }
958 }
959
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -0600960 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
961
962 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600963 std::unordered_set<uint32_t> worklist;
964 worklist.insert(entrypoint.word(2));
965
966 // Follow instructions in call graph looking for writes to target
967 while (!worklist.empty() && !found_write) {
968 auto id_iter = worklist.begin();
969 auto id = *id_iter;
970 worklist.erase(id_iter);
971
972 auto insn = src->get_def(id);
973 if (insn == src->end()) {
974 continue;
975 }
976
977 if (insn.opcode() == spv::OpFunction) {
978 // Scan body of function looking for other function calls or items in our ID chain
979 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
980 switch (insn.opcode()) {
981 case spv::OpAccessChain:
982 if (insn.word(3) == target_id) {
983 if (type == spv::OpMemberDecorate) {
984 auto value = GetConstantValue(src, insn.word(4));
985 if (value == builtin_instr.word(2)) {
986 target_id = insn.word(2);
987 }
988 } else {
989 target_id = insn.word(2);
990 }
991 }
992 break;
993 case spv::OpStore:
994 if (insn.word(1) == target_id) {
995 found_write = true;
996 }
997 break;
998 case spv::OpFunctionCall:
999 worklist.insert(insn.word(3));
1000 break;
1001 }
1002 }
1003 }
1004 }
1005 return found_write;
1006}
1007
Chris Forbes47567b72017-06-09 12:09:45 -07001008// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1009// important for identifying the set of shader resources actually used by an entrypoint, for example.
1010// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1011// - NOT the shader input/output interfaces.
1012//
1013// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1014// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001015static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001016 std::unordered_set<uint32_t> ids;
1017 std::unordered_set<uint32_t> worklist;
1018 worklist.insert(entrypoint.word(2));
1019
1020 while (!worklist.empty()) {
1021 auto id_iter = worklist.begin();
1022 auto id = *id_iter;
1023 worklist.erase(id_iter);
1024
1025 auto insn = src->get_def(id);
1026 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001027 // ID is something we didn't collect in BuildDefIndex. that's OK -- we'll stumble across all kinds of things here
Chris Forbes47567b72017-06-09 12:09:45 -07001028 // that we may not care about.
1029 continue;
1030 }
1031
1032 // Try to add to the output set
1033 if (!ids.insert(id).second) {
1034 continue; // If we already saw this id, we don't want to walk it again.
1035 }
1036
1037 switch (insn.opcode()) {
1038 case spv::OpFunction:
1039 // Scan whole body of the function, enlisting anything interesting
1040 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1041 switch (insn.opcode()) {
1042 case spv::OpLoad:
1043 case spv::OpAtomicLoad:
1044 case spv::OpAtomicExchange:
1045 case spv::OpAtomicCompareExchange:
1046 case spv::OpAtomicCompareExchangeWeak:
1047 case spv::OpAtomicIIncrement:
1048 case spv::OpAtomicIDecrement:
1049 case spv::OpAtomicIAdd:
1050 case spv::OpAtomicISub:
1051 case spv::OpAtomicSMin:
1052 case spv::OpAtomicUMin:
1053 case spv::OpAtomicSMax:
1054 case spv::OpAtomicUMax:
1055 case spv::OpAtomicAnd:
1056 case spv::OpAtomicOr:
1057 case spv::OpAtomicXor:
1058 worklist.insert(insn.word(3)); // ptr
1059 break;
1060 case spv::OpStore:
1061 case spv::OpAtomicStore:
1062 worklist.insert(insn.word(1)); // ptr
1063 break;
1064 case spv::OpAccessChain:
1065 case spv::OpInBoundsAccessChain:
1066 worklist.insert(insn.word(3)); // base ptr
1067 break;
1068 case spv::OpSampledImage:
1069 case spv::OpImageSampleImplicitLod:
1070 case spv::OpImageSampleExplicitLod:
1071 case spv::OpImageSampleDrefImplicitLod:
1072 case spv::OpImageSampleDrefExplicitLod:
1073 case spv::OpImageSampleProjImplicitLod:
1074 case spv::OpImageSampleProjExplicitLod:
1075 case spv::OpImageSampleProjDrefImplicitLod:
1076 case spv::OpImageSampleProjDrefExplicitLod:
1077 case spv::OpImageFetch:
1078 case spv::OpImageGather:
1079 case spv::OpImageDrefGather:
1080 case spv::OpImageRead:
1081 case spv::OpImage:
1082 case spv::OpImageQueryFormat:
1083 case spv::OpImageQueryOrder:
1084 case spv::OpImageQuerySizeLod:
1085 case spv::OpImageQuerySize:
1086 case spv::OpImageQueryLod:
1087 case spv::OpImageQueryLevels:
1088 case spv::OpImageQuerySamples:
1089 case spv::OpImageSparseSampleImplicitLod:
1090 case spv::OpImageSparseSampleExplicitLod:
1091 case spv::OpImageSparseSampleDrefImplicitLod:
1092 case spv::OpImageSparseSampleDrefExplicitLod:
1093 case spv::OpImageSparseSampleProjImplicitLod:
1094 case spv::OpImageSparseSampleProjExplicitLod:
1095 case spv::OpImageSparseSampleProjDrefImplicitLod:
1096 case spv::OpImageSparseSampleProjDrefExplicitLod:
1097 case spv::OpImageSparseFetch:
1098 case spv::OpImageSparseGather:
1099 case spv::OpImageSparseDrefGather:
1100 case spv::OpImageTexelPointer:
1101 worklist.insert(insn.word(3)); // Image or sampled image
1102 break;
1103 case spv::OpImageWrite:
1104 worklist.insert(insn.word(1)); // Image -- different operand order to above
1105 break;
1106 case spv::OpFunctionCall:
1107 for (uint32_t i = 3; i < insn.len(); i++) {
1108 worklist.insert(insn.word(i)); // fn itself, and all args
1109 }
1110 break;
1111
1112 case spv::OpExtInst:
1113 for (uint32_t i = 5; i < insn.len(); i++) {
1114 worklist.insert(insn.word(i)); // Operands to ext inst
1115 }
1116 break;
1117 }
1118 }
1119 break;
1120 }
1121 }
1122
1123 return ids;
1124}
1125
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001126static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1127 std::vector<VkPushConstantRange> const *push_constant_ranges,
1128 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001129 bool skip = false;
1130
1131 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001132 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001133 assert(type != src->end());
1134
1135 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1136 // TODO: arrays, matrices, weird sizes
1137 for (auto insn : *src) {
1138 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1139 if (insn.word(3) == spv::DecorationOffset) {
1140 unsigned offset = insn.word(4);
1141 auto size = 4; // Bytes; TODO: calculate this based on the type
1142
1143 bool found_range = false;
1144 for (auto const &range : *push_constant_ranges) {
1145 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1146 found_range = true;
1147
1148 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001149 skip |=
1150 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001151 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001152 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1153 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001154 }
1155
1156 break;
1157 }
1158 }
1159
1160 if (!found_range) {
1161 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001162 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001163 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001164 }
1165 }
1166 }
1167 }
1168
1169 return skip;
1170}
1171
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001172static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1173 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1174 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001175 bool skip = false;
1176
1177 for (auto id : accessible_ids) {
1178 auto def_insn = src->get_def(id);
1179 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001180 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1181 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001182 }
1183 }
1184
1185 return skip;
1186}
1187
1188// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001189static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001190 bool skip = false;
1191
1192 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1193
1194 if (spec) {
1195 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001196 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001197 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001198 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001199 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001200 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001201 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001202 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001203 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001204 }
1205 }
1206 }
1207
1208 return skip;
1209}
1210
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001211// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001212static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001213 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001214 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001215 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001216 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001217
1218 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Jeff Bolzfdf96072018-04-10 14:32:18 -05001219 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1220 if (type.opcode() == spv::OpTypeRuntimeArray) {
1221 descriptor_count = 0;
1222 type = module->get_def(type.word(2));
1223 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001224 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001225 type = module->get_def(type.word(2));
1226 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001227 if (type.word(2) == spv::StorageClassStorageBuffer) {
1228 is_storage_buffer = true;
1229 }
Chris Forbes47567b72017-06-09 12:09:45 -07001230 type = module->get_def(type.word(3));
1231 }
1232 }
1233
1234 switch (type.opcode()) {
1235 case spv::OpTypeStruct: {
1236 for (auto insn : *module) {
1237 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1238 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001239 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001240 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1241 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1242 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001243 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001244 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1245 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1246 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1247 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001248 }
Chris Forbes47567b72017-06-09 12:09:45 -07001249 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001250 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1251 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1252 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001253 }
1254 }
1255 }
1256
1257 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001258 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001259 }
1260
1261 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001262 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1263 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1264 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001265
Chris Forbes73c00bf2018-06-22 16:28:06 -07001266 case spv::OpTypeSampledImage: {
1267 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1268 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1269 auto image_type = module->get_def(type.word(2));
1270 auto dim = image_type.word(3);
1271 auto sampled = image_type.word(7);
1272 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001273 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1274 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001275 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001276 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001277 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1278 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001279
1280 case spv::OpTypeImage: {
1281 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1282 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1283 auto dim = type.word(3);
1284 auto sampled = type.word(7);
1285
1286 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001287 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1288 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001289 } else if (dim == spv::DimBuffer) {
1290 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001291 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1292 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001293 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001294 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1295 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001296 }
1297 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001298 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1299 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1300 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001301 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001302 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1303 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001304 }
1305 }
Jeff Bolz105d6492018-09-29 15:46:44 -05001306 case spv::OpTypeAccelerationStructureNVX:
1307 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NVX);
1308 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001309
1310 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1311 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001312 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001313 }
1314}
1315
Jeff Bolze54ae892018-09-08 12:16:29 -05001316static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001317 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001318 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1319 if (ss.tellp()) ss << ", ";
1320 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001321 }
1322 return ss.str();
1323}
1324
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001325static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001326 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001327 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001328 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001329 return true;
1330 }
1331 }
1332
1333 return false;
1334}
1335
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001336static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001337 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001338 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001339 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001340 extension_name)) {
1341 return true;
1342 }
1343 }
1344
1345 return false;
1346}
1347
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001348static bool ValidateShaderCapabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1349 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001350 bool skip = false;
1351
1352 auto report_data = GetReportData(dev_data);
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001353 auto const &features = GetEnabledFeatures(dev_data);
Cort Strattond2742852018-05-03 13:42:10 -04001354 auto const &extensions = GetDeviceExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001355
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001356 struct FeaturePointer {
1357 // Callable object to test if this feature is enabled in the given aggregate feature struct
1358 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1359
1360 // Test if feature pointer is populated
1361 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1362
1363 // Default and nullptr constructor to create an empty FeaturePointer
1364 FeaturePointer() : IsEnabled(nullptr) {}
1365 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1366
1367 // Constructors to populate FeaturePointer based on given pointer to member
1368 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1369 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1370 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1371 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1372 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1373 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
1374 };
1375
Chris Forbes47567b72017-06-09 12:09:45 -07001376 struct CapabilityInfo {
1377 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001378 FeaturePointer feature;
1379 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001380 };
1381
Chris Forbes47567b72017-06-09 12:09:45 -07001382 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001383 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001384 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1385 // feature bits.
1386 {spv::CapabilityMatrix, {nullptr}},
1387 {spv::CapabilityShader, {nullptr}},
1388 {spv::CapabilityInputAttachment, {nullptr}},
1389 {spv::CapabilitySampled1D, {nullptr}},
1390 {spv::CapabilityImage1D, {nullptr}},
1391 {spv::CapabilitySampledBuffer, {nullptr}},
1392 {spv::CapabilityImageQuery, {nullptr}},
1393 {spv::CapabilityDerivativeControl, {nullptr}},
1394
1395 // Capabilities that are optionally supported, but require a feature to
1396 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001397 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1398 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1399 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1400 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1401 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1402 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1403 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1404 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1405 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1406 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1407 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1408 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1409 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1410 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1411 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1412 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1413 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1414 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1415 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1416 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1417 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1418 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1419 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1420 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1421 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001422
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001423 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1424 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1425 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1426 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1427 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1428 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1429 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1430 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1431 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1432 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1433 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1434 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001435
1436 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001437 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1438 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1439 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1440 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1441 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1442 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1443 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1444 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001445
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001446 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1447 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1448 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Chris Forbes47567b72017-06-09 12:09:45 -07001449 };
1450 // clang-format on
1451
1452 for (auto insn : *src) {
1453 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001454 size_t n = capabilities.count(insn.word(1));
1455 if (1 == n) { // key occurs exactly once
1456 auto it = capabilities.find(insn.word(1));
1457 if (it != capabilities.end()) {
1458 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001459 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001460 }
1461 if (it->second.extension) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001462 skip |= RequireExtension(report_data, extensions->*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001463 }
Chris Forbes47567b72017-06-09 12:09:45 -07001464 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001465 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1466 bool needs_feature = false, has_feature = false;
1467 bool needs_ext = false, has_ext = false;
1468 std::string feature_names = "(one of) [ ";
1469 std::string extension_names = feature_names;
1470 auto caps = capabilities.equal_range(insn.word(1));
1471 for (auto it = caps.first; it != caps.second; ++it) {
1472 if (it->second.feature) {
1473 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001474 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001475 feature_names += it->second.name;
1476 feature_names += " ";
1477 }
1478 if (it->second.extension) {
1479 needs_ext = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001480 has_ext = has_ext || extensions->*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001481 extension_names += it->second.name;
1482 extension_names += " ";
1483 }
1484 }
1485 if (needs_feature) {
1486 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001487 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001488 }
1489 if (needs_ext) {
1490 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001491 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001492 }
1493 }
1494 }
1495 }
1496
Chris Forbes349b3132018-03-07 11:38:08 -08001497 if (has_writable_descriptor) {
1498 switch (stage) {
1499 case VK_SHADER_STAGE_COMPUTE_BIT:
1500 /* No feature requirements for writes and atomics from compute
1501 * stage */
1502 break;
1503 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001504 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001505 break;
1506 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001507 skip |=
1508 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001509 break;
1510 }
1511 }
1512
Chris Forbes47567b72017-06-09 12:09:45 -07001513 return skip;
1514}
1515
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001516static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07001517 auto type = module->get_def(type_id);
1518
1519 while (true) {
1520 switch (type.opcode()) {
1521 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07001522 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07001523 case spv::OpTypeSampledImage:
1524 type = module->get_def(type.word(2));
1525 break;
1526 case spv::OpTypePointer:
1527 type = module->get_def(type.word(3));
1528 break;
1529 case spv::OpTypeImage: {
1530 auto dim = type.word(3);
1531 auto arrayed = type.word(5);
1532 auto msaa = type.word(6);
1533
Chris Forbes74ba2232018-08-27 15:19:27 -07001534 uint32_t bits = 0;
1535 switch (GetFundamentalType(module, type.word(2))) {
1536 case FORMAT_TYPE_FLOAT:
1537 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1538 break;
1539 case FORMAT_TYPE_UINT:
1540 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1541 break;
1542 case FORMAT_TYPE_SINT:
1543 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1544 break;
1545 default:
1546 break;
1547 }
1548
Chris Forbes47567b72017-06-09 12:09:45 -07001549 switch (dim) {
1550 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001551 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1552 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001553 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001554 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1555 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1556 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001557 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001558 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1559 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001560 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07001561 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1562 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001563 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07001564 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1565 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001566 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07001567 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001568 }
1569 }
1570 default:
1571 return 0;
1572 }
1573 }
1574}
1575
1576// For given pipelineLayout verify that the set_layout_node at slot.first
1577// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001578static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1579 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07001580 if (!pipelineLayout) return nullptr;
1581
1582 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1583
1584 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1585}
1586
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001587static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05001588 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07001589 bool is_point_mode = false;
1590
1591 for (auto insn : *src) {
1592 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
1593 switch (insn.word(2)) {
1594 case spv::ExecutionModePointMode:
1595 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
1596 is_point_mode = true;
1597 break;
1598
1599 case spv::ExecutionModeOutputPoints:
1600 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1601 break;
1602
1603 case spv::ExecutionModeIsolines:
1604 case spv::ExecutionModeOutputLineStrip:
1605 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
1606 break;
1607
1608 case spv::ExecutionModeTriangles:
1609 case spv::ExecutionModeQuads:
1610 case spv::ExecutionModeOutputTriangleStrip:
1611 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
1612 break;
1613 }
1614 }
1615 }
1616
1617 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1618}
1619
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001620// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
1621// o If there is only a vertex shader : gl_PointSize must be written when using points
1622// o If there is a geometry or tessellation shader:
1623// - If shaderTessellationAndGeometryPointSize feature is enabled:
1624// * gl_PointSize must be written in the final geometry stage
1625// - If shaderTessellationAndGeometryPointSize feature is disabled:
1626// * gl_PointSize must NOT be written and a default of 1.0 is assumed
1627bool ValidatePointListShaderState(const layer_data *dev_data, const PIPELINE_STATE *pipeline, shader_module const *src,
1628 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) {
1629 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1630 return false;
1631 }
1632
1633 bool pointsize_written = false;
1634 bool skip = false;
1635
1636 // Search for PointSize built-in decorations
1637 std::vector<uint32_t> pointsize_builtin_offsets;
1638 spirv_inst_iter insn = entrypoint;
1639 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
1640 if (insn.opcode() == spv::OpMemberDecorate) {
1641 if (insn.word(3) == spv::DecorationBuiltIn) {
1642 if (insn.word(4) == spv::BuiltInPointSize) {
1643 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1644 }
1645 }
1646 } else if (insn.opcode() == spv::OpDecorate) {
1647 if (insn.word(2) == spv::DecorationBuiltIn) {
1648 if (insn.word(3) == spv::BuiltInPointSize) {
1649 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1650 }
1651 }
1652 }
1653
1654 insn++;
1655 }
1656
1657 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
1658 !GetEnabledFeatures(dev_data)->core.shaderTessellationAndGeometryPointSize) {
1659 if (pointsize_written) {
1660 skip |= log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1661 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
1662 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
1663 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
1664 }
1665 } else if (!pointsize_written) {
1666 skip |=
1667 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1668 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
1669 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
1670 string_VkShaderStageFlagBits(stage));
1671 }
1672 return skip;
1673}
1674
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001675static bool ValidatePipelineShaderStage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001676 PIPELINE_STATE *pipeline, shader_module const **out_module, spirv_inst_iter *out_entrypoint,
1677 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07001678 bool skip = false;
1679 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1680 auto report_data = GetReportData(dev_data);
1681
1682 if (!module->has_valid_spirv) return false;
1683
1684 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001685 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001686 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001687 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001688 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
1689 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001690 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1691 }
1692 }
1693
Chris Forbes47567b72017-06-09 12:09:45 -07001694 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001695 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
1696 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07001697
1698 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001699 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001700 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001701
Chris Forbes349b3132018-03-07 11:38:08 -08001702 // Validate shader capabilities against enabled device features
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001703 skip |= ValidateShaderCapabilities(dev_data, module, pStage->stage, has_writable_descriptor);
Chris Forbes349b3132018-03-07 11:38:08 -08001704
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001705 skip |= ValidateSpecializationOffsets(report_data, pStage);
1706 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
1707 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05001708 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001709 skip |= ValidatePointListShaderState(dev_data, pipeline, module, entrypoint, pStage->stage);
1710 }
Chris Forbes47567b72017-06-09 12:09:45 -07001711
1712 // Validate descriptor use
1713 for (auto use : descriptor_uses) {
1714 // While validating shaders capture which slots are used by the pipeline
1715 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001716 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07001717
1718 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001719 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001720 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05001721 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07001722
1723 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001724 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001725 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001726 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05001727 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001728 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001729 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001730 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001731 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
1732 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05001733 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001734 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001735 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001736 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05001737 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001738 string_VkDescriptorType(binding->descriptorType));
1739 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001740 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001741 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001742 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
1743 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07001744 }
1745 }
1746
1747 // Validate use of input attachments against subpass structure
1748 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001749 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07001750
Petr Krause91f7a12017-12-14 20:57:36 +01001751 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001752 auto subpass = pipeline->graphicsPipelineCI.subpass;
1753
1754 for (auto use : input_attachment_uses) {
1755 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1756 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001757 ? input_attachments[use.first].attachment
1758 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001759
1760 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001761 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001762 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07001763 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001764 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001765 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001766 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001767 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001768 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001769 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001770 }
1771 }
1772 }
1773
1774 return skip;
1775}
1776
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001777static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
1778 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1779 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1780 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001781 bool skip = false;
1782
1783 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001784 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1785 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07001786
1787 auto a_it = outputs.begin();
1788 auto b_it = inputs.begin();
1789
1790 // Maps sorted by key (location); walk them together to find mismatches
1791 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1792 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1793 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1794 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1795 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1796
1797 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06001798 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001799 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06001800 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1801 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001802 a_it++;
1803 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06001804 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001805 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06001806 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
1807 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001808 b_it++;
1809 } else {
1810 // subtleties of arrayed interfaces:
1811 // - if is_patch, then the member is not arrayed, even though the interface may be.
1812 // - if is_block_member, then the extra array level of an arrayed interface is not
1813 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001814 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1815 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1816 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06001817 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001818 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06001819 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001820 DescribeType(producer, a_it->second.type_id).c_str(),
1821 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001822 }
1823 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06001824 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001825 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001826 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
Chris Forbes47567b72017-06-09 12:09:45 -07001827 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1828 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1829 }
1830 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06001831 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001832 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001833 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1834 a_first.second, producer_stage->name, consumer_stage->name);
1835 }
1836 a_it++;
1837 b_it++;
1838 }
1839 }
1840
1841 return skip;
1842}
1843
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001844static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
1845 uint32_t stage_mask = 0;
1846 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1847 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1848 stage_mask |= pCreateInfo->pStages[i].stage;
1849 }
1850 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05001851 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
1852 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
1853 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001854 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
1855 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
1856 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
1857 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
1858 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001859 }
1860 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001861 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001862}
1863
Chris Forbes47567b72017-06-09 12:09:45 -07001864// Validate that the shaders used by the given pipeline and store the active_slots
1865// that are actually used by the pipeline into pPipeline->active_slots
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001866bool ValidateAndCapturePipelineShaderState(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001867 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001868 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1869 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001870 auto report_data = GetReportData(dev_data);
1871
Jeff Bolz7e35c392018-09-04 15:30:41 -05001872 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001873 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05001874 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001875 memset(entrypoints, 0, sizeof(entrypoints));
1876 bool skip = false;
1877
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001878 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
1879
Chris Forbes47567b72017-06-09 12:09:45 -07001880 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1881 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001882 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001883 skip |= ValidatePipelineShaderStage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
1884 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001885 }
1886
1887 // if the shader stages are no good individually, cross-stage validation is pointless.
1888 if (skip) return true;
1889
1890 auto vi = pCreateInfo->pVertexInputState;
1891
1892 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001893 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07001894 }
1895
1896 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001897 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07001898 }
1899
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001900 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1901 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001902
1903 while (!shaders[producer] && producer != fragment_stage) {
1904 producer++;
1905 consumer++;
1906 }
1907
1908 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1909 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001910 if (shaders[consumer]) {
1911 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001912 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
1913 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1914 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001915 }
Chris Forbes47567b72017-06-09 12:09:45 -07001916
1917 producer = consumer;
1918 }
1919 }
1920
1921 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001922 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1923 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001924 }
1925
1926 return skip;
1927}
1928
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001929bool ValidateComputePipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001930 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001931
1932 shader_module const *module;
1933 spirv_inst_iter entrypoint;
1934
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001935 return ValidatePipelineShaderStage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001936}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001937
Jeff Bolzfbe51582018-09-13 10:01:35 -05001938bool ValidateRaytracingPipelineNVX(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1939 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
1940
1941 shader_module const *module;
1942 spirv_inst_iter entrypoint;
1943
1944 return ValidatePipelineShaderStage(dev_data, pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
1945}
1946
Dave Houltona9df0ce2018-02-07 10:51:23 -07001947uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001948
Dave Houltona9df0ce2018-02-07 10:51:23 -07001949static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001950 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1951 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1952 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1953 }
1954
1955 return nullptr;
1956}
1957
Chris Forbes4ae55b32017-06-09 14:42:56 -07001958bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1959 bool skip = false;
1960 spv_result_t spv_valid = SPV_SUCCESS;
1961 auto report_data = GetReportData(dev_data);
1962
1963 if (GetDisables(dev_data)->shader_validation) {
1964 return false;
1965 }
1966
Cort Strattond2742852018-05-03 13:42:10 -04001967 auto have_glsl_shader = GetDeviceExtensions(dev_data)->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07001968
1969 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houlton78d09922018-05-17 15:48:45 -06001970 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1971 "VUID-VkShaderModuleCreateInfo-pCode-01376",
1972 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
1973 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001974 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001975 auto cache = GetValidationCacheInfo(pCreateInfo);
1976 uint32_t hash = 0;
1977 if (cache) {
1978 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001979 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001980 }
1981
Chris Forbes4ae55b32017-06-09 14:42:56 -07001982 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06001983 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
1984 if (GetApiVersion(dev_data) >= VK_API_VERSION_1_1) {
1985 spirv_environment = SPV_ENV_VULKAN_1_1;
1986 }
1987 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001988 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001989 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06001990 spv_validator_options options = spvValidatorOptionsCreate();
1991 if (GetDeviceExtensions(dev_data)->vk_khr_relaxed_block_layout) {
1992 spvValidatorOptionsSetRelaxBlockLayout(options, true);
1993 }
1994 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001995 if (spv_valid != SPV_SUCCESS) {
1996 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001997 skip |=
1998 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001999 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002000 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07002001 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002002 } else {
2003 if (cache) {
2004 cache->Insert(hash);
2005 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002006 }
2007
Karl Schultzfda1b382018-08-08 18:56:11 -06002008 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002009 spvDiagnosticDestroy(diag);
2010 spvContextDestroy(ctx);
2011 }
2012
2013 *spirv_valid = (spv_valid == SPV_SUCCESS);
2014 return skip;
2015}