blob: fb9fb30ac4bd3a28d8b87834efd8f890bea09e2b [file] [log] [blame]
Karl Schultz7b024b42018-08-30 16:18:18 -06001/* Copyright (c) 2015-2019 The Khronos Group Inc.
2 * Copyright (c) 2015-2019 Valve Corporation
3 * Copyright (c) 2015-2019 LunarG, Inc.
4 * Copyright (C) 2015-2019 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>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020024#include <chrono>
Chris Forbes47567b72017-06-09 12:09:45 -070025#include <vector>
26#include <unordered_map>
27#include <string>
28#include <sstream>
29#include <SPIRV/spirv.hpp>
30#include "vk_loader_platform.h"
31#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070032#include "vk_layer_data.h"
33#include "vk_layer_extension_utils.h"
34#include "vk_layer_utils.h"
35#include "core_validation.h"
36#include "core_validation_types.h"
37#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070038#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070039#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040
Mark Lobodzinski01734072019-02-13 17:39:15 -070041namespace core_validation {
42extern unordered_map<void *, layer_data *> layer_data_map;
43extern unordered_map<void *, instance_layer_data *> instance_layer_data_map;
44}; // namespace core_validation
45
46using core_validation::instance_layer_data_map;
47using core_validation::layer_data_map;
48
Chris Forbes47567b72017-06-09 12:09:45 -070049enum FORMAT_TYPE {
50 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
51 FORMAT_TYPE_SINT = 2,
52 FORMAT_TYPE_UINT = 4,
53};
54
55typedef std::pair<unsigned, unsigned> location_t;
56
57struct interface_var {
58 uint32_t id;
59 uint32_t type_id;
60 uint32_t offset;
61 bool is_patch;
62 bool is_block_member;
63 bool is_relaxed_precision;
64 // TODO: collect the name, too? Isn't required to be present.
65};
66
67struct shader_stage_attributes {
68 char const *const name;
69 bool arrayed_input;
70 bool arrayed_output;
71};
72
73static shader_stage_attributes shader_stage_attribs[] = {
74 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
75 {"geometry shader", true, false}, {"fragment shader", false, false},
76};
77
78// SPIRV utility functions
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060079void shader_module::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -070080 for (auto insn : *this) {
81 switch (insn.opcode()) {
82 // Types
83 case spv::OpTypeVoid:
84 case spv::OpTypeBool:
85 case spv::OpTypeInt:
86 case spv::OpTypeFloat:
87 case spv::OpTypeVector:
88 case spv::OpTypeMatrix:
89 case spv::OpTypeImage:
90 case spv::OpTypeSampler:
91 case spv::OpTypeSampledImage:
92 case spv::OpTypeArray:
93 case spv::OpTypeRuntimeArray:
94 case spv::OpTypeStruct:
95 case spv::OpTypeOpaque:
96 case spv::OpTypePointer:
97 case spv::OpTypeFunction:
98 case spv::OpTypeEvent:
99 case spv::OpTypeDeviceEvent:
100 case spv::OpTypeReserveId:
101 case spv::OpTypeQueue:
102 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600103 case spv::OpTypeAccelerationStructureNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700104 def_index[insn.word(1)] = insn.offset();
105 break;
106
107 // Fixed constants
108 case spv::OpConstantTrue:
109 case spv::OpConstantFalse:
110 case spv::OpConstant:
111 case spv::OpConstantComposite:
112 case spv::OpConstantSampler:
113 case spv::OpConstantNull:
114 def_index[insn.word(2)] = insn.offset();
115 break;
116
117 // Specialization constants
118 case spv::OpSpecConstantTrue:
119 case spv::OpSpecConstantFalse:
120 case spv::OpSpecConstant:
121 case spv::OpSpecConstantComposite:
122 case spv::OpSpecConstantOp:
123 def_index[insn.word(2)] = insn.offset();
124 break;
125
126 // Variables
127 case spv::OpVariable:
128 def_index[insn.word(2)] = insn.offset();
129 break;
130
131 // Functions
132 case spv::OpFunction:
133 def_index[insn.word(2)] = insn.offset();
134 break;
135
136 default:
137 // We don't care about any other defs for now.
138 break;
139 }
140 }
141}
142
Jeff Bolz105d6492018-09-29 15:46:44 -0500143unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
144 switch (mode) {
145 case spv::ExecutionModelVertex:
146 return VK_SHADER_STAGE_VERTEX_BIT;
147 case spv::ExecutionModelTessellationControl:
148 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
149 case spv::ExecutionModelTessellationEvaluation:
150 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
151 case spv::ExecutionModelGeometry:
152 return VK_SHADER_STAGE_GEOMETRY_BIT;
153 case spv::ExecutionModelFragment:
154 return VK_SHADER_STAGE_FRAGMENT_BIT;
155 case spv::ExecutionModelGLCompute:
156 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600157 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700158 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600159 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700160 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600161 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700162 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600163 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700164 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600165 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700166 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600167 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700168 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500169 case spv::ExecutionModelTaskNV:
170 return VK_SHADER_STAGE_TASK_BIT_NV;
171 case spv::ExecutionModelMeshNV:
172 return VK_SHADER_STAGE_MESH_BIT_NV;
173 default:
174 return 0;
175 }
176}
177
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600178static spirv_inst_iter FindEntrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
Chris Forbes47567b72017-06-09 12:09:45 -0700179 for (auto insn : *src) {
180 if (insn.opcode() == spv::OpEntryPoint) {
181 auto entrypointName = (char const *)&insn.word(3);
Jeff Bolz105d6492018-09-29 15:46:44 -0500182 auto executionModel = insn.word(1);
183 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
Chris Forbes47567b72017-06-09 12:09:45 -0700184
185 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
186 return insn;
187 }
188 }
189 }
190
191 return src->end();
192}
193
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600194static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700195 switch (sc) {
196 case spv::StorageClassInput:
197 return "input";
198 case spv::StorageClassOutput:
199 return "output";
200 case spv::StorageClassUniformConstant:
201 return "const uniform";
202 case spv::StorageClassUniform:
203 return "uniform";
204 case spv::StorageClassWorkgroup:
205 return "workgroup local";
206 case spv::StorageClassCrossWorkgroup:
207 return "workgroup global";
208 case spv::StorageClassPrivate:
209 return "private global";
210 case spv::StorageClassFunction:
211 return "function";
212 case spv::StorageClassGeneric:
213 return "generic";
214 case spv::StorageClassAtomicCounter:
215 return "atomic counter";
216 case spv::StorageClassImage:
217 return "image";
218 case spv::StorageClassPushConstant:
219 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800220 case spv::StorageClassStorageBuffer:
221 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700222 default:
223 return "unknown";
224 }
225}
226
227// Get the value of an integral constant
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600228unsigned GetConstantValue(shader_module const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700229 auto value = src->get_def(id);
230 assert(value != src->end());
231
232 if (value.opcode() != spv::OpConstant) {
233 // TODO: Either ensure that the specialization transform is already performed on a module we're
234 // considering here, OR -- specialize on the fly now.
235 return 1;
236 }
237
238 return value.word(3);
239}
240
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600241static void DescribeTypeInner(std::ostringstream &ss, shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700242 auto insn = src->get_def(type);
243 assert(insn != src->end());
244
245 switch (insn.opcode()) {
246 case spv::OpTypeBool:
247 ss << "bool";
248 break;
249 case spv::OpTypeInt:
250 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
251 break;
252 case spv::OpTypeFloat:
253 ss << "float" << insn.word(2);
254 break;
255 case spv::OpTypeVector:
256 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600257 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700258 break;
259 case spv::OpTypeMatrix:
260 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600261 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700262 break;
263 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600264 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
265 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700266 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700267 case spv::OpTypeRuntimeArray:
268 ss << "runtime arr[] of ";
269 DescribeTypeInner(ss, src, insn.word(2));
270 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700271 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600272 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
273 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700274 break;
275 case spv::OpTypeStruct: {
276 ss << "struct of (";
277 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600278 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700279 if (i == insn.len() - 1) {
280 ss << ")";
281 } else {
282 ss << ", ";
283 }
284 }
285 break;
286 }
287 case spv::OpTypeSampler:
288 ss << "sampler";
289 break;
290 case spv::OpTypeSampledImage:
291 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600292 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700293 break;
294 case spv::OpTypeImage:
295 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
296 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600297 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500298 ss << "accelerationStruture";
299 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700300 default:
301 ss << "oddtype";
302 break;
303 }
304}
305
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600306static std::string DescribeType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700307 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600308 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700309 return ss.str();
310}
311
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600312static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700313 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
314 return type.word(2) < 64;
315}
316
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600317static bool TypesMatch(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
318 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700319 // Walk two type trees together, and complain about differences
320 auto a_insn = a->get_def(a_type);
321 auto b_insn = b->get_def(b_type);
322 assert(a_insn != a->end());
323 assert(b_insn != b->end());
324
Chris Forbes062f1222018-08-21 15:34:15 -0700325 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
326
Chris Forbes47567b72017-06-09 12:09:45 -0700327 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600328 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700329 }
330
331 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
332 // 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 -0600333 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700334 }
335
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600336 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
337 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700338 }
339
340 if (a_insn.opcode() != b_insn.opcode()) {
341 return false;
342 }
343
344 if (a_insn.opcode() == spv::OpTypePointer) {
345 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600346 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700347 }
348
349 if (a_arrayed || b_arrayed) {
350 // If we havent resolved array-of-verts by here, we're not going to.
351 return false;
352 }
353
354 switch (a_insn.opcode()) {
355 case spv::OpTypeBool:
356 return true;
357 case spv::OpTypeInt:
358 // Match on width, signedness
359 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
360 case spv::OpTypeFloat:
361 // Match on width
362 return a_insn.word(2) == b_insn.word(2);
363 case spv::OpTypeVector:
364 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600365 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
366 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700367 return a_insn.word(3) >= b_insn.word(3);
368 } else {
369 return a_insn.word(3) == b_insn.word(3);
370 }
371 case spv::OpTypeMatrix:
372 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600373 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700374 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700375 case spv::OpTypeArray:
376 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
377 // 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 -0600378 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
379 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700380 case spv::OpTypeStruct:
381 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700382 {
383 if (a_insn.len() != b_insn.len()) {
384 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700385 }
Chris Forbes47567b72017-06-09 12:09:45 -0700386
Dave Houltona9df0ce2018-02-07 10:51:23 -0700387 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600388 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700389 return false;
390 }
391 }
392
393 return true;
394 }
Chris Forbes47567b72017-06-09 12:09:45 -0700395 default:
396 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
397 return false;
398 }
399}
400
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600401static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700402 auto it = map.find(id);
403 if (it == map.end())
404 return def;
405 else
406 return it->second;
407}
408
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600409static unsigned GetLocationsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700410 auto insn = src->get_def(type);
411 assert(insn != src->end());
412
413 switch (insn.opcode()) {
414 case spv::OpTypePointer:
415 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
416 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600417 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700418 case spv::OpTypeArray:
419 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600420 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700421 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600422 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700423 }
424 case spv::OpTypeMatrix:
425 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600426 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700427 case spv::OpTypeVector: {
428 auto scalar_type = src->get_def(insn.word(2));
429 auto bit_width =
430 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
431
432 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
433 return (bit_width * insn.word(3) + 127) / 128;
434 }
435 default:
436 // Everything else is just 1.
437 return 1;
438
439 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
440 }
441}
442
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200443static unsigned GetComponentsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
444 auto insn = src->get_def(type);
445 assert(insn != src->end());
446
447 switch (insn.opcode()) {
448 case spv::OpTypePointer:
449 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
450 // pointers around.
451 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
452 case spv::OpTypeStruct: {
453 uint32_t sum = 0;
454 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
455 sum += GetComponentsConsumedByType(src, insn.word(i), false);
456 }
457 return sum;
458 }
459 case spv::OpTypeArray: {
460 uint32_t sum = 0;
461 for (uint32_t i = 2; i < insn.len(); i++) {
462 sum += GetComponentsConsumedByType(src, insn.word(i), false);
463 }
464 return sum;
465 }
466 case spv::OpTypeMatrix:
467 // Num locations is the dimension * element size
468 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
469 case spv::OpTypeVector: {
470 auto scalar_type = src->get_def(insn.word(2));
471 auto bit_width =
472 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
473 // One component is 32-bit
474 return (bit_width * insn.word(3) + 31) / 32;
475 }
476 case spv::OpTypeFloat: {
477 auto bit_width = insn.word(2);
478 return (bit_width + 31) / 32;
479 }
480 case spv::OpTypeInt: {
481 auto bit_width = insn.word(2);
482 return (bit_width + 31) / 32;
483 }
484 case spv::OpConstant:
485 return GetComponentsConsumedByType(src, insn.word(1), false);
486 default:
487 return 0;
488 }
489}
490
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600491static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700492 switch (format) {
493 case VK_FORMAT_R64G64B64A64_SFLOAT:
494 case VK_FORMAT_R64G64B64A64_SINT:
495 case VK_FORMAT_R64G64B64A64_UINT:
496 case VK_FORMAT_R64G64B64_SFLOAT:
497 case VK_FORMAT_R64G64B64_SINT:
498 case VK_FORMAT_R64G64B64_UINT:
499 return 2;
500 default:
501 return 1;
502 }
503}
504
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600505static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700506 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
507 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
508 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
509 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700510 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
511 return FORMAT_TYPE_FLOAT;
512}
513
514// 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 -0700515// also used for input attachments, as we statically know their format.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600516static unsigned GetFundamentalType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700517 auto insn = src->get_def(type);
518 assert(insn != src->end());
519
520 switch (insn.opcode()) {
521 case spv::OpTypeInt:
522 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
523 case spv::OpTypeFloat:
524 return FORMAT_TYPE_FLOAT;
525 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700526 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700527 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700528 case spv::OpTypeRuntimeArray:
529 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600530 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700531 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600532 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700533
534 default:
535 return 0;
536 }
537}
538
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600539static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700540 uint32_t bit_pos = uint32_t(u_ffs(stage));
541 return bit_pos - 1;
542}
543
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600544static spirv_inst_iter GetStructType(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700545 while (true) {
546 if (def.opcode() == spv::OpTypePointer) {
547 def = src->get_def(def.word(3));
548 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
549 def = src->get_def(def.word(2));
550 is_array_of_verts = false;
551 } else if (def.opcode() == spv::OpTypeStruct) {
552 return def;
553 } else {
554 return src->end();
555 }
556 }
557}
558
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600559static bool CollectInterfaceBlockMembers(shader_module const *src, std::map<location_t, interface_var> *out,
560 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts, uint32_t id,
561 uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700562 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600563 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700564 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
565 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700566 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700567 }
568
569 std::unordered_map<unsigned, unsigned> member_components;
570 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700571 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700572
573 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
574 for (auto insn : *src) {
575 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
576 unsigned member_index = insn.word(2);
577
578 if (insn.word(3) == spv::DecorationComponent) {
579 unsigned component = insn.word(4);
580 member_components[member_index] = component;
581 }
582
583 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
584 member_relaxed_precision[member_index] = 1;
585 }
Chris Forbesa313d772017-06-13 13:59:41 -0700586
587 if (insn.word(3) == spv::DecorationPatch) {
588 member_patch[member_index] = 1;
589 }
Chris Forbes47567b72017-06-09 12:09:45 -0700590 }
591 }
592
Chris Forbesa313d772017-06-13 13:59:41 -0700593 // TODO: correctly handle location assignment from outside
594
Chris Forbes47567b72017-06-09 12:09:45 -0700595 // Second pass -- produce the output, from Location decorations
596 for (auto insn : *src) {
597 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
598 unsigned member_index = insn.word(2);
599 unsigned member_type_id = type.word(2 + member_index);
600
601 if (insn.word(3) == spv::DecorationLocation) {
602 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600603 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700604 auto component_it = member_components.find(member_index);
605 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
606 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700607 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700608
609 for (unsigned int offset = 0; offset < num_locations; offset++) {
610 interface_var v = {};
611 v.id = id;
612 // TODO: member index in interface_var too?
613 v.type_id = member_type_id;
614 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700615 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700616 v.is_block_member = true;
617 v.is_relaxed_precision = is_relaxed_precision;
618 (*out)[std::make_pair(location + offset, component)] = v;
619 }
620 }
621 }
622 }
Chris Forbesa313d772017-06-13 13:59:41 -0700623
624 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700625}
626
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600627static std::map<location_t, interface_var> CollectInterfaceByLocation(shader_module const *src, spirv_inst_iter entrypoint,
628 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700629 std::unordered_map<unsigned, unsigned> var_locations;
630 std::unordered_map<unsigned, unsigned> var_builtins;
631 std::unordered_map<unsigned, unsigned> var_components;
632 std::unordered_map<unsigned, unsigned> blocks;
633 std::unordered_map<unsigned, unsigned> var_patch;
634 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
635
636 for (auto insn : *src) {
637 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
638 // fits neither model.
639 if (insn.opcode() == spv::OpDecorate) {
640 if (insn.word(2) == spv::DecorationLocation) {
641 var_locations[insn.word(1)] = insn.word(3);
642 }
643
644 if (insn.word(2) == spv::DecorationBuiltIn) {
645 var_builtins[insn.word(1)] = insn.word(3);
646 }
647
648 if (insn.word(2) == spv::DecorationComponent) {
649 var_components[insn.word(1)] = insn.word(3);
650 }
651
652 if (insn.word(2) == spv::DecorationBlock) {
653 blocks[insn.word(1)] = 1;
654 }
655
656 if (insn.word(2) == spv::DecorationPatch) {
657 var_patch[insn.word(1)] = 1;
658 }
659
660 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
661 var_relaxed_precision[insn.word(1)] = 1;
662 }
663 }
664 }
665
666 // TODO: handle grouped decorations
667 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
668
669 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
670 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
671 uint32_t word = 3;
672 while (entrypoint.word(word) & 0xff000000u) {
673 ++word;
674 }
675 ++word;
676
677 std::map<location_t, interface_var> out;
678
679 for (; word < entrypoint.len(); word++) {
680 auto insn = src->get_def(entrypoint.word(word));
681 assert(insn != src->end());
682 assert(insn.opcode() == spv::OpVariable);
683
684 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
685 unsigned id = insn.word(2);
686 unsigned type = insn.word(1);
687
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600688 int location = ValueOrDefault(var_locations, id, static_cast<unsigned>(-1));
689 int builtin = ValueOrDefault(var_builtins, id, static_cast<unsigned>(-1));
690 unsigned component = ValueOrDefault(var_components, id, 0); // Unspecified is OK, is 0
Chris Forbes47567b72017-06-09 12:09:45 -0700691 bool is_patch = var_patch.find(id) != var_patch.end();
692 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
693
Dave Houltona9df0ce2018-02-07 10:51:23 -0700694 if (builtin != -1)
695 continue;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600696 else if (!CollectInterfaceBlockMembers(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700697 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
698 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600699 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700700 for (unsigned int offset = 0; offset < num_locations; offset++) {
701 interface_var v = {};
702 v.id = id;
703 v.type_id = type;
704 v.offset = offset;
705 v.is_patch = is_patch;
706 v.is_relaxed_precision = is_relaxed_precision;
707 out[std::make_pair(location + offset, component)] = v;
708 }
Chris Forbes47567b72017-06-09 12:09:45 -0700709 }
710 }
711 }
712
713 return out;
714}
715
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600716static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Chris Forbes47567b72017-06-09 12:09:45 -0700717 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
718 std::vector<std::pair<uint32_t, interface_var>> out;
719
720 for (auto insn : *src) {
721 if (insn.opcode() == spv::OpDecorate) {
722 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
723 auto attachment_index = insn.word(3);
724 auto id = insn.word(1);
725
726 if (accessible_ids.count(id)) {
727 auto def = src->get_def(id);
728 assert(def != src->end());
729
730 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600731 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700732 for (unsigned int offset = 0; offset < num_locations; offset++) {
733 interface_var v = {};
734 v.id = id;
735 v.type_id = def.word(1);
736 v.offset = offset;
737 out.emplace_back(attachment_index + offset, v);
738 }
739 }
740 }
741 }
742 }
743 }
744
745 return out;
746}
747
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700748static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800749 auto type = module->get_def(type_id);
750
751 // 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 -0700752 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
753 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700754 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800755 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700756 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800757 }
758 }
759
760 switch (type.opcode()) {
761 case spv::OpTypeImage: {
762 auto dim = type.word(3);
763 auto sampled = type.word(7);
764 return sampled == 2 && dim != spv::DimSubpassData;
765 }
766
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700767 case spv::OpTypeStruct: {
768 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8af24522018-03-07 11:37:45 -0800769 for (auto insn : *module) {
770 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
771 if (insn.word(2) == spv::DecorationBufferBlock) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700772 // Legacy storage block in the Uniform storage class
773 // has its struct type decorated with BufferBlock.
774 is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800775 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700776 } else if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
777 insn.word(3) == spv::DecorationNonWritable) {
778 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800779 }
780 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700781
782 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
783 // as nonwritable.
784 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
785 }
Chris Forbes8af24522018-03-07 11:37:45 -0800786 }
787
788 return false;
789}
790
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600791static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800792 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
793 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700794 std::unordered_map<unsigned, unsigned> var_sets;
795 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800796 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700797
798 for (auto insn : *src) {
799 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
800 // DecorationDescriptorSet and DecorationBinding.
801 if (insn.opcode() == spv::OpDecorate) {
802 if (insn.word(2) == spv::DecorationDescriptorSet) {
803 var_sets[insn.word(1)] = insn.word(3);
804 }
805
806 if (insn.word(2) == spv::DecorationBinding) {
807 var_bindings[insn.word(1)] = insn.word(3);
808 }
Chris Forbes8af24522018-03-07 11:37:45 -0800809
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700810 // Note: do toplevel DecorationNonWritable out here; it applies to
811 // the OpVariable rather than the type.
Chris Forbes8af24522018-03-07 11:37:45 -0800812 if (insn.word(2) == spv::DecorationNonWritable) {
813 var_nonwritable[insn.word(1)] = 1;
814 }
Chris Forbes47567b72017-06-09 12:09:45 -0700815 }
816 }
817
818 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
819
820 for (auto id : accessible_ids) {
821 auto insn = src->get_def(id);
822 assert(insn != src->end());
823
824 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800825 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
826 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600827 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
828 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700829
830 interface_var v = {};
831 v.id = insn.word(2);
832 v.type_id = insn.word(1);
833 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800834
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700835 if (var_nonwritable.find(id) == var_nonwritable.end() &&
836 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800837 *has_writable_descriptor = true;
838 }
Chris Forbes47567b72017-06-09 12:09:45 -0700839 }
840 }
841
842 return out;
843}
844
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600845static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700846 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
847 // be specified only once.
848 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
849 bool skip = false;
850
851 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
852 auto desc = &vi->pVertexBindingDescriptions[i];
853 auto &binding = bindings[desc->binding];
854 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600855 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600856 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 -0600857 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700858 desc->binding);
859 } else {
860 binding = desc;
861 }
862 }
863
864 return skip;
865}
866
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600867static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
868 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700869 bool skip = false;
870
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600871 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700872
873 // Build index by location
874 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
875 if (vi) {
876 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600877 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700878 for (auto j = 0u; j < num_locations; j++) {
879 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
880 }
881 }
882 }
883
884 auto it_a = attribs.begin();
885 auto it_b = inputs.begin();
886 bool used = false;
887
888 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
889 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
890 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
891 auto a_first = a_at_end ? 0 : it_a->first;
892 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600893
Chris Forbes47567b72017-06-09 12:09:45 -0700894 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600895 if (!used &&
896 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 -0600897 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600898 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700899 skip = true;
900 }
901 used = false;
902 it_a++;
903 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600904 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 -0600905 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600906 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700907 it_b++;
908 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600909 unsigned attrib_type = GetFormatType(it_a->second->format);
910 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700911
912 // Type checking
913 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600914 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 -0600915 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700916 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600917 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700918 }
919
920 // OK!
921 used = true;
922 it_b++;
923 }
924 }
925
926 return skip;
927}
928
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600929static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
930 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100931 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700932
Chris Forbes47567b72017-06-09 12:09:45 -0700933 std::map<uint32_t, VkFormat> color_attachments;
934 auto subpass = rpci->pSubpasses[subpass_index];
935 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
936 uint32_t attachment = subpass.pColorAttachments[i].attachment;
937 if (attachment == VK_ATTACHMENT_UNUSED) continue;
938 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
939 color_attachments[i] = rpci->pAttachments[attachment].format;
940 }
941 }
942
943 bool skip = false;
944
945 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
946
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600947 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700948
949 auto it_a = outputs.begin();
950 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600951 bool used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700952
953 // Walk attachment list and outputs together
954
955 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
956 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
957 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
958
959 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600960 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 -0600961 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Chris Forbes47567b72017-06-09 12:09:45 -0700962 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
963 it_a++;
964 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700965 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
966 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600967 if (!used) {
968 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700969 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 -0600970 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Chris Forbescfe4dca2018-10-05 10:15:00 -0700971 "Attachment %d not written by fragment shader; undefined values will be written to attachment",
972 it_b->first);
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600973 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700974 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600975 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700976 it_b++;
977 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600978 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
979 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700980
981 // Type checking
982 if (!(output_type & att_type)) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700983 skip |= log_msg(
984 report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
985 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
986 "Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
987 it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700988 }
989
990 // OK!
991 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600992 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700993 }
994 }
995
996 return skip;
997}
998
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600999// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1000// This function examines instructions in the static call tree for a write to this variable.
1001static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
1002 auto type = builtin_instr.opcode();
1003 uint32_t target_id = builtin_instr.word(1);
1004 bool init_complete = false;
1005
1006 if (type == spv::OpMemberDecorate) {
1007 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1008 auto insn = entrypoint;
1009 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1010 switch (insn.opcode()) {
1011 case spv::OpTypePointer:
1012 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1013 target_id = insn.word(1);
1014 }
1015 break;
1016 case spv::OpVariable:
1017 if (insn.word(1) == target_id) {
1018 target_id = insn.word(2);
1019 init_complete = true;
1020 }
1021 break;
1022 }
1023 insn++;
1024 }
1025 }
1026
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001027 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1028
1029 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001030 std::unordered_set<uint32_t> worklist;
1031 worklist.insert(entrypoint.word(2));
1032
1033 // Follow instructions in call graph looking for writes to target
1034 while (!worklist.empty() && !found_write) {
1035 auto id_iter = worklist.begin();
1036 auto id = *id_iter;
1037 worklist.erase(id_iter);
1038
1039 auto insn = src->get_def(id);
1040 if (insn == src->end()) {
1041 continue;
1042 }
1043
1044 if (insn.opcode() == spv::OpFunction) {
1045 // Scan body of function looking for other function calls or items in our ID chain
1046 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1047 switch (insn.opcode()) {
1048 case spv::OpAccessChain:
1049 if (insn.word(3) == target_id) {
1050 if (type == spv::OpMemberDecorate) {
1051 auto value = GetConstantValue(src, insn.word(4));
1052 if (value == builtin_instr.word(2)) {
1053 target_id = insn.word(2);
1054 }
1055 } else {
1056 target_id = insn.word(2);
1057 }
1058 }
1059 break;
1060 case spv::OpStore:
1061 if (insn.word(1) == target_id) {
1062 found_write = true;
1063 }
1064 break;
1065 case spv::OpFunctionCall:
1066 worklist.insert(insn.word(3));
1067 break;
1068 }
1069 }
1070 }
1071 }
1072 return found_write;
1073}
1074
Chris Forbes47567b72017-06-09 12:09:45 -07001075// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1076// important for identifying the set of shader resources actually used by an entrypoint, for example.
1077// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1078// - NOT the shader input/output interfaces.
1079//
1080// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1081// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001082static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001083 std::unordered_set<uint32_t> ids;
1084 std::unordered_set<uint32_t> worklist;
1085 worklist.insert(entrypoint.word(2));
1086
1087 while (!worklist.empty()) {
1088 auto id_iter = worklist.begin();
1089 auto id = *id_iter;
1090 worklist.erase(id_iter);
1091
1092 auto insn = src->get_def(id);
1093 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001094 // 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 -07001095 // that we may not care about.
1096 continue;
1097 }
1098
1099 // Try to add to the output set
1100 if (!ids.insert(id).second) {
1101 continue; // If we already saw this id, we don't want to walk it again.
1102 }
1103
1104 switch (insn.opcode()) {
1105 case spv::OpFunction:
1106 // Scan whole body of the function, enlisting anything interesting
1107 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1108 switch (insn.opcode()) {
1109 case spv::OpLoad:
1110 case spv::OpAtomicLoad:
1111 case spv::OpAtomicExchange:
1112 case spv::OpAtomicCompareExchange:
1113 case spv::OpAtomicCompareExchangeWeak:
1114 case spv::OpAtomicIIncrement:
1115 case spv::OpAtomicIDecrement:
1116 case spv::OpAtomicIAdd:
1117 case spv::OpAtomicISub:
1118 case spv::OpAtomicSMin:
1119 case spv::OpAtomicUMin:
1120 case spv::OpAtomicSMax:
1121 case spv::OpAtomicUMax:
1122 case spv::OpAtomicAnd:
1123 case spv::OpAtomicOr:
1124 case spv::OpAtomicXor:
1125 worklist.insert(insn.word(3)); // ptr
1126 break;
1127 case spv::OpStore:
1128 case spv::OpAtomicStore:
1129 worklist.insert(insn.word(1)); // ptr
1130 break;
1131 case spv::OpAccessChain:
1132 case spv::OpInBoundsAccessChain:
1133 worklist.insert(insn.word(3)); // base ptr
1134 break;
1135 case spv::OpSampledImage:
1136 case spv::OpImageSampleImplicitLod:
1137 case spv::OpImageSampleExplicitLod:
1138 case spv::OpImageSampleDrefImplicitLod:
1139 case spv::OpImageSampleDrefExplicitLod:
1140 case spv::OpImageSampleProjImplicitLod:
1141 case spv::OpImageSampleProjExplicitLod:
1142 case spv::OpImageSampleProjDrefImplicitLod:
1143 case spv::OpImageSampleProjDrefExplicitLod:
1144 case spv::OpImageFetch:
1145 case spv::OpImageGather:
1146 case spv::OpImageDrefGather:
1147 case spv::OpImageRead:
1148 case spv::OpImage:
1149 case spv::OpImageQueryFormat:
1150 case spv::OpImageQueryOrder:
1151 case spv::OpImageQuerySizeLod:
1152 case spv::OpImageQuerySize:
1153 case spv::OpImageQueryLod:
1154 case spv::OpImageQueryLevels:
1155 case spv::OpImageQuerySamples:
1156 case spv::OpImageSparseSampleImplicitLod:
1157 case spv::OpImageSparseSampleExplicitLod:
1158 case spv::OpImageSparseSampleDrefImplicitLod:
1159 case spv::OpImageSparseSampleDrefExplicitLod:
1160 case spv::OpImageSparseSampleProjImplicitLod:
1161 case spv::OpImageSparseSampleProjExplicitLod:
1162 case spv::OpImageSparseSampleProjDrefImplicitLod:
1163 case spv::OpImageSparseSampleProjDrefExplicitLod:
1164 case spv::OpImageSparseFetch:
1165 case spv::OpImageSparseGather:
1166 case spv::OpImageSparseDrefGather:
1167 case spv::OpImageTexelPointer:
1168 worklist.insert(insn.word(3)); // Image or sampled image
1169 break;
1170 case spv::OpImageWrite:
1171 worklist.insert(insn.word(1)); // Image -- different operand order to above
1172 break;
1173 case spv::OpFunctionCall:
1174 for (uint32_t i = 3; i < insn.len(); i++) {
1175 worklist.insert(insn.word(i)); // fn itself, and all args
1176 }
1177 break;
1178
1179 case spv::OpExtInst:
1180 for (uint32_t i = 5; i < insn.len(); i++) {
1181 worklist.insert(insn.word(i)); // Operands to ext inst
1182 }
1183 break;
1184 }
1185 }
1186 break;
1187 }
1188 }
1189
1190 return ids;
1191}
1192
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001193static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1194 std::vector<VkPushConstantRange> const *push_constant_ranges,
1195 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001196 bool skip = false;
1197
1198 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001199 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001200 assert(type != src->end());
1201
1202 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1203 // TODO: arrays, matrices, weird sizes
1204 for (auto insn : *src) {
1205 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1206 if (insn.word(3) == spv::DecorationOffset) {
1207 unsigned offset = insn.word(4);
1208 auto size = 4; // Bytes; TODO: calculate this based on the type
1209
1210 bool found_range = false;
1211 for (auto const &range : *push_constant_ranges) {
1212 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1213 found_range = true;
1214
1215 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001216 skip |=
1217 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 -06001218 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001219 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1220 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001221 }
1222
1223 break;
1224 }
1225 }
1226
1227 if (!found_range) {
1228 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 -06001229 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001230 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001231 }
1232 }
1233 }
1234 }
1235
1236 return skip;
1237}
1238
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001239static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1240 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1241 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001242 bool skip = false;
1243
1244 for (auto id : accessible_ids) {
1245 auto def_insn = src->get_def(id);
1246 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001247 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1248 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001249 }
1250 }
1251
1252 return skip;
1253}
1254
1255// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001256static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001257 bool skip = false;
1258
1259 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1260
1261 if (spec) {
1262 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001263 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001264 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001265 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 -06001266 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001267 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001268 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001269 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001270 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001271 }
1272 }
1273 }
1274
1275 return skip;
1276}
1277
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001278// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001279static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001280 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001281 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001282 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001283 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001284
1285 // 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 -05001286 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1287 if (type.opcode() == spv::OpTypeRuntimeArray) {
1288 descriptor_count = 0;
1289 type = module->get_def(type.word(2));
1290 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001291 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001292 type = module->get_def(type.word(2));
1293 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001294 if (type.word(2) == spv::StorageClassStorageBuffer) {
1295 is_storage_buffer = true;
1296 }
Chris Forbes47567b72017-06-09 12:09:45 -07001297 type = module->get_def(type.word(3));
1298 }
1299 }
1300
1301 switch (type.opcode()) {
1302 case spv::OpTypeStruct: {
1303 for (auto insn : *module) {
1304 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1305 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001306 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001307 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1308 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1309 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001310 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001311 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1312 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1313 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1314 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001315 }
Chris Forbes47567b72017-06-09 12:09:45 -07001316 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001317 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1318 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1319 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001320 }
1321 }
1322 }
1323
1324 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001325 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001326 }
1327
1328 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001329 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1330 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1331 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001332
Chris Forbes73c00bf2018-06-22 16:28:06 -07001333 case spv::OpTypeSampledImage: {
1334 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1335 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1336 auto image_type = module->get_def(type.word(2));
1337 auto dim = image_type.word(3);
1338 auto sampled = image_type.word(7);
1339 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001340 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1341 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001342 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001343 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001344 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1345 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001346
1347 case spv::OpTypeImage: {
1348 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1349 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1350 auto dim = type.word(3);
1351 auto sampled = type.word(7);
1352
1353 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001354 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1355 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001356 } else if (dim == spv::DimBuffer) {
1357 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001358 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1359 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001360 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001361 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1362 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001363 }
1364 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001365 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1366 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1367 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001368 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001369 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1370 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001371 }
1372 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001373 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001374 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001375 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001376
1377 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1378 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001379 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001380 }
1381}
1382
Jeff Bolze54ae892018-09-08 12:16:29 -05001383static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001384 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001385 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1386 if (ss.tellp()) ss << ", ";
1387 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001388 }
1389 return ss.str();
1390}
1391
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001392static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001393 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001394 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 -06001395 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001396 return true;
1397 }
1398 }
1399
1400 return false;
1401}
1402
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001403static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001404 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001405 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 -06001406 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001407 extension_name)) {
1408 return true;
1409 }
1410 }
1411
1412 return false;
1413}
1414
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001415static bool ValidateShaderCapabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1416 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001417 bool skip = false;
1418
1419 auto report_data = GetReportData(dev_data);
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001420 auto const &features = GetEnabledFeatures(dev_data);
Cort Strattond2742852018-05-03 13:42:10 -04001421 auto const &extensions = GetDeviceExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001422
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001423 struct FeaturePointer {
1424 // Callable object to test if this feature is enabled in the given aggregate feature struct
1425 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1426
1427 // Test if feature pointer is populated
1428 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1429
1430 // Default and nullptr constructor to create an empty FeaturePointer
1431 FeaturePointer() : IsEnabled(nullptr) {}
1432 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1433
1434 // Constructors to populate FeaturePointer based on given pointer to member
1435 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1436 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1437 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1438 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1439 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1440 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001441 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1442 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001443 FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
1444 : IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
Tobias Hector6a0ece72018-12-10 12:24:05 +00001445 FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
1446 : IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001447 };
1448
Chris Forbes47567b72017-06-09 12:09:45 -07001449 struct CapabilityInfo {
1450 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001451 FeaturePointer feature;
1452 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001453 };
1454
Chris Forbes47567b72017-06-09 12:09:45 -07001455 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001456 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001457 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1458 // feature bits.
1459 {spv::CapabilityMatrix, {nullptr}},
1460 {spv::CapabilityShader, {nullptr}},
1461 {spv::CapabilityInputAttachment, {nullptr}},
1462 {spv::CapabilitySampled1D, {nullptr}},
1463 {spv::CapabilityImage1D, {nullptr}},
1464 {spv::CapabilitySampledBuffer, {nullptr}},
1465 {spv::CapabilityImageQuery, {nullptr}},
1466 {spv::CapabilityDerivativeControl, {nullptr}},
1467
1468 // Capabilities that are optionally supported, but require a feature to
1469 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001470 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1471 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1472 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1473 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1474 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1475 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1476 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1477 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1478 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1479 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1480 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1481 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1482 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1483 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1484 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1485 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1486 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1487 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1488 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1489 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1490 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1491 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1492 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1493 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1494 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001495
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001496 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1497 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1498 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1499 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1500 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1501 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1502 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1503 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1504 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1505 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1506 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1507 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001508
1509 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001510 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1511 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1512 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1513 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1514 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1515 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1516 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1517 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
aqnuep7033c702018-09-11 18:03:29 +02001518 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001519
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001520 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1521 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1522 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001523
1524 {spv::CapabilityTransformFeedback , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001525 {spv::CapabilityGeometryStreams , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
1526
1527 {spv::CapabilityFloat16 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1528 {spv::CapabilityInt8 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Chris Forbes47567b72017-06-09 12:09:45 -07001529 };
1530 // clang-format on
1531
1532 for (auto insn : *src) {
1533 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001534 size_t n = capabilities.count(insn.word(1));
1535 if (1 == n) { // key occurs exactly once
1536 auto it = capabilities.find(insn.word(1));
1537 if (it != capabilities.end()) {
1538 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001539 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001540 }
1541 if (it->second.extension) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001542 skip |= RequireExtension(report_data, extensions->*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001543 }
Chris Forbes47567b72017-06-09 12:09:45 -07001544 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001545 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1546 bool needs_feature = false, has_feature = false;
1547 bool needs_ext = false, has_ext = false;
1548 std::string feature_names = "(one of) [ ";
1549 std::string extension_names = feature_names;
1550 auto caps = capabilities.equal_range(insn.word(1));
1551 for (auto it = caps.first; it != caps.second; ++it) {
1552 if (it->second.feature) {
1553 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001554 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001555 feature_names += it->second.name;
1556 feature_names += " ";
1557 }
1558 if (it->second.extension) {
1559 needs_ext = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001560 has_ext = has_ext || extensions->*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001561 extension_names += it->second.name;
1562 extension_names += " ";
1563 }
1564 }
1565 if (needs_feature) {
1566 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001567 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001568 }
1569 if (needs_ext) {
1570 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001571 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001572 }
1573 }
1574 }
1575 }
1576
Chris Forbes349b3132018-03-07 11:38:08 -08001577 if (has_writable_descriptor) {
1578 switch (stage) {
1579 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001580 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1581 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1582 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1583 case VK_SHADER_STAGE_MISS_BIT_NV:
1584 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1585 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1586 case VK_SHADER_STAGE_TASK_BIT_NV:
1587 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001588 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001589 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001590 break;
1591 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001592 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001593 break;
1594 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001595 skip |=
1596 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001597 break;
1598 }
1599 }
1600
Chris Forbes47567b72017-06-09 12:09:45 -07001601 return skip;
1602}
1603
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001604static bool VariableIsBuiltIn(shader_module const *src, const uint32_t ID, std::vector<uint32_t> const &builtInBlockIDs,
1605 std::vector<uint32_t> const &builtInIDs) {
1606 auto insn = src->get_def(ID);
1607
1608 switch (insn.opcode()) {
1609 case spv::OpVariable: {
1610 // First check if the variable is a "pure" built-in type, e.g. gl_ViewportIndex
1611 uint32_t ID = insn.word(2);
1612 for (auto builtInID : builtInIDs) {
1613 if (ID == builtInID) {
1614 return true;
1615 }
1616 }
1617
1618 VariableIsBuiltIn(src, insn.word(1), builtInBlockIDs, builtInIDs);
1619 break;
1620 }
1621 case spv::OpTypePointer:
1622 VariableIsBuiltIn(src, insn.word(3), builtInBlockIDs, builtInIDs);
1623 break;
1624 case spv::OpTypeArray:
1625 VariableIsBuiltIn(src, insn.word(2), builtInBlockIDs, builtInIDs);
1626 break;
1627 case spv::OpTypeStruct: {
1628 uint32_t ID = insn.word(1); // We only need to check the first member as either all will be, or none will be built-in
1629 for (auto builtInBlockID : builtInBlockIDs) {
1630 if (ID == builtInBlockID) {
1631 return true;
1632 }
1633 }
1634 return false;
1635 }
1636 default:
1637 return false;
1638 }
1639
1640 return false;
1641}
1642
1643static bool ValidateShaderStageInputOutputLimits(layer_data *dev_data, shader_module const *src,
1644 VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline) {
1645 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1646 pStage->stage == VK_SHADER_STAGE_ALL) {
1647 return false;
1648 }
1649
1650 bool skip = false;
1651 auto const &properties = GetPhysDevProperties(dev_data);
1652 auto const report_data = GetReportData(dev_data);
1653
1654 std::vector<uint32_t> builtInBlockIDs;
1655 std::vector<uint32_t> builtInIDs;
1656 struct Variable {
1657 uint32_t baseTypePtrID;
1658 uint32_t ID;
1659 uint32_t storageClass;
1660 };
1661 std::vector<Variable> variables;
1662
1663 for (auto insn : *src) {
1664 switch (insn.opcode()) {
1665 // Find all built-in member decorations
1666 case spv::OpMemberDecorate:
1667 if (insn.word(3) == spv::DecorationBuiltIn) {
1668 builtInBlockIDs.push_back(insn.word(1));
1669 }
1670 break;
1671 // Find all built-in decorations
1672 case spv::OpDecorate:
1673 switch (insn.word(2)) {
1674 case spv::DecorationBlock: {
1675 uint32_t blockID = insn.word(1);
1676 for (auto builtInBlockID : builtInBlockIDs) {
1677 // Check if one of the members of the block are built-in -> the block is built-in
1678 if (blockID == builtInBlockID) {
1679 builtInIDs.push_back(blockID);
1680 break;
1681 }
1682 }
1683 break;
1684 }
1685 case spv::DecorationBuiltIn:
1686 builtInIDs.push_back(insn.word(1));
1687 break;
1688 default:
1689 break;
1690 }
1691 break;
1692 // Find all input and output variables
1693 case spv::OpVariable: {
1694 Variable var = {};
1695 var.storageClass = insn.word(3);
1696 if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
1697 var.baseTypePtrID = insn.word(1);
1698 var.ID = insn.word(2);
1699 variables.push_back(var);
1700 }
1701 break;
1702 }
1703 default:
1704 break;
1705 }
1706 }
1707
1708 uint32_t numCompIn = 0, numCompOut = 0;
1709 for (auto &var : variables) {
1710 // Check the variable's ID
1711 if (VariableIsBuiltIn(src, var.ID, builtInBlockIDs, builtInIDs)) {
1712 continue;
1713 }
1714 // Check the variable's type's ID - e.g. gl_PerVertex is made of basic types, not built-in types
1715 if (VariableIsBuiltIn(src, src->get_def(var.baseTypePtrID).word(3), builtInBlockIDs, builtInIDs)) {
1716 continue;
1717 }
1718
1719 if (var.storageClass == spv::StorageClassInput) {
1720 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1721 } else { // var.storageClass == spv::StorageClassOutput
1722 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1723 }
1724 }
1725
1726 switch (pStage->stage) {
1727 case VK_SHADER_STAGE_VERTEX_BIT:
1728 if (numCompOut > properties->properties.limits.maxVertexOutputComponents) {
1729 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1730 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1731 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1732 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
1733 "components by %u components",
1734 properties->properties.limits.maxVertexOutputComponents,
1735 numCompOut - properties->properties.limits.maxVertexOutputComponents);
1736 }
1737 break;
1738
1739 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
1740 if (numCompIn > properties->properties.limits.maxTessellationControlPerVertexInputComponents) {
1741 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1742 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1743 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1744 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
1745 "components by %u components",
1746 properties->properties.limits.maxTessellationControlPerVertexInputComponents,
1747 numCompIn - properties->properties.limits.maxTessellationControlPerVertexInputComponents);
1748 }
1749 if (numCompOut > properties->properties.limits.maxTessellationControlPerVertexOutputComponents) {
1750 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1751 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1752 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1753 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
1754 "components by %u components",
1755 properties->properties.limits.maxTessellationControlPerVertexOutputComponents,
1756 numCompOut - properties->properties.limits.maxTessellationControlPerVertexOutputComponents);
1757 }
1758 break;
1759
1760 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
1761 if (numCompIn > properties->properties.limits.maxTessellationEvaluationInputComponents) {
1762 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1763 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1764 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1765 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
1766 "components by %u components",
1767 properties->properties.limits.maxTessellationEvaluationInputComponents,
1768 numCompIn - properties->properties.limits.maxTessellationEvaluationInputComponents);
1769 }
1770 if (numCompOut > properties->properties.limits.maxTessellationEvaluationOutputComponents) {
1771 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1772 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1773 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1774 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
1775 "components by %u components",
1776 properties->properties.limits.maxTessellationEvaluationOutputComponents,
1777 numCompOut - properties->properties.limits.maxTessellationEvaluationOutputComponents);
1778 }
1779 break;
1780
1781 case VK_SHADER_STAGE_GEOMETRY_BIT:
1782 if (numCompIn > properties->properties.limits.maxGeometryInputComponents) {
1783 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1784 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1785 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1786 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
1787 "components by %u components",
1788 properties->properties.limits.maxGeometryInputComponents,
1789 numCompIn - properties->properties.limits.maxGeometryInputComponents);
1790 }
1791 if (numCompOut > properties->properties.limits.maxGeometryOutputComponents) {
1792 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1793 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1794 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1795 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
1796 "components by %u components",
1797 properties->properties.limits.maxGeometryOutputComponents,
1798 numCompOut - properties->properties.limits.maxGeometryOutputComponents);
1799 }
1800 break;
1801
1802 case VK_SHADER_STAGE_FRAGMENT_BIT:
1803 if (numCompIn > properties->properties.limits.maxFragmentInputComponents) {
1804 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1805 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1806 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
1807 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
1808 "components by %u components",
1809 properties->properties.limits.maxFragmentInputComponents,
1810 numCompIn - properties->properties.limits.maxFragmentInputComponents);
1811 }
1812 break;
1813
Jeff Bolz148d94e2018-12-13 21:25:56 -06001814 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1815 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1816 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1817 case VK_SHADER_STAGE_MISS_BIT_NV:
1818 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1819 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1820 case VK_SHADER_STAGE_TASK_BIT_NV:
1821 case VK_SHADER_STAGE_MESH_BIT_NV:
1822 break;
1823
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001824 default:
1825 assert(false); // This should never happen
1826 }
1827 return skip;
1828}
1829
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001830static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07001831 auto type = module->get_def(type_id);
1832
1833 while (true) {
1834 switch (type.opcode()) {
1835 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07001836 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07001837 case spv::OpTypeSampledImage:
1838 type = module->get_def(type.word(2));
1839 break;
1840 case spv::OpTypePointer:
1841 type = module->get_def(type.word(3));
1842 break;
1843 case spv::OpTypeImage: {
1844 auto dim = type.word(3);
1845 auto arrayed = type.word(5);
1846 auto msaa = type.word(6);
1847
Chris Forbes74ba2232018-08-27 15:19:27 -07001848 uint32_t bits = 0;
1849 switch (GetFundamentalType(module, type.word(2))) {
1850 case FORMAT_TYPE_FLOAT:
1851 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1852 break;
1853 case FORMAT_TYPE_UINT:
1854 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1855 break;
1856 case FORMAT_TYPE_SINT:
1857 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1858 break;
1859 default:
1860 break;
1861 }
1862
Chris Forbes47567b72017-06-09 12:09:45 -07001863 switch (dim) {
1864 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001865 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1866 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001867 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001868 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1869 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1870 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001871 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001872 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1873 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001874 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07001875 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1876 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001877 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07001878 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1879 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001880 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07001881 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001882 }
1883 }
1884 default:
1885 return 0;
1886 }
1887 }
1888}
1889
1890// For given pipelineLayout verify that the set_layout_node at slot.first
1891// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001892static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1893 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07001894 if (!pipelineLayout) return nullptr;
1895
1896 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1897
1898 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1899}
1900
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001901static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05001902 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07001903 bool is_point_mode = false;
1904
1905 for (auto insn : *src) {
1906 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
1907 switch (insn.word(2)) {
1908 case spv::ExecutionModePointMode:
1909 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
1910 is_point_mode = true;
1911 break;
1912
1913 case spv::ExecutionModeOutputPoints:
1914 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1915 break;
1916
1917 case spv::ExecutionModeIsolines:
1918 case spv::ExecutionModeOutputLineStrip:
1919 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
1920 break;
1921
1922 case spv::ExecutionModeTriangles:
1923 case spv::ExecutionModeQuads:
1924 case spv::ExecutionModeOutputTriangleStrip:
1925 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
1926 break;
1927 }
1928 }
1929 }
1930
1931 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1932}
1933
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001934// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
1935// o If there is only a vertex shader : gl_PointSize must be written when using points
1936// o If there is a geometry or tessellation shader:
1937// - If shaderTessellationAndGeometryPointSize feature is enabled:
1938// * gl_PointSize must be written in the final geometry stage
1939// - If shaderTessellationAndGeometryPointSize feature is disabled:
1940// * gl_PointSize must NOT be written and a default of 1.0 is assumed
1941bool ValidatePointListShaderState(const layer_data *dev_data, const PIPELINE_STATE *pipeline, shader_module const *src,
1942 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) {
1943 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1944 return false;
1945 }
1946
1947 bool pointsize_written = false;
1948 bool skip = false;
1949
1950 // Search for PointSize built-in decorations
1951 std::vector<uint32_t> pointsize_builtin_offsets;
1952 spirv_inst_iter insn = entrypoint;
1953 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
1954 if (insn.opcode() == spv::OpMemberDecorate) {
1955 if (insn.word(3) == spv::DecorationBuiltIn) {
1956 if (insn.word(4) == spv::BuiltInPointSize) {
1957 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1958 }
1959 }
1960 } else if (insn.opcode() == spv::OpDecorate) {
1961 if (insn.word(2) == spv::DecorationBuiltIn) {
1962 if (insn.word(3) == spv::BuiltInPointSize) {
1963 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1964 }
1965 }
1966 }
1967
1968 insn++;
1969 }
1970
1971 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
1972 !GetEnabledFeatures(dev_data)->core.shaderTessellationAndGeometryPointSize) {
1973 if (pointsize_written) {
1974 skip |= log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1975 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
1976 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
1977 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
1978 }
1979 } else if (!pointsize_written) {
1980 skip |=
1981 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1982 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
1983 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
1984 string_VkShaderStageFlagBits(stage));
1985 }
1986 return skip;
1987}
1988
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001989static bool ValidatePipelineShaderStage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001990 PIPELINE_STATE *pipeline, shader_module const **out_module, spirv_inst_iter *out_entrypoint,
1991 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07001992 bool skip = false;
1993 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1994 auto report_data = GetReportData(dev_data);
1995
1996 if (!module->has_valid_spirv) return false;
1997
1998 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001999 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07002000 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002001 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 -06002002 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2003 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002004 return true; // no point continuing beyond here, any analysis is just going to be garbage.
2005 }
2006 }
2007
Chris Forbes47567b72017-06-09 12:09:45 -07002008 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002009 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
2010 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002011
2012 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08002013 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002014 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07002015
Chris Forbes349b3132018-03-07 11:38:08 -08002016 // Validate shader capabilities against enabled device features
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002017 skip |= ValidateShaderCapabilities(dev_data, module, pStage->stage, has_writable_descriptor);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002018 skip |= ValidateShaderStageInputOutputLimits(dev_data, module, pStage, pipeline);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002019 skip |= ValidateSpecializationOffsets(report_data, pStage);
2020 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
2021 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002022 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002023 skip |= ValidatePointListShaderState(dev_data, pipeline, module, entrypoint, pStage->stage);
2024 }
Chris Forbes47567b72017-06-09 12:09:45 -07002025
2026 // Validate descriptor use
2027 for (auto use : descriptor_uses) {
2028 // While validating shaders capture which slots are used by the pipeline
2029 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002030 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07002031
2032 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002033 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002034 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002035 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002036
2037 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002038 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 -06002039 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002040 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05002041 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002042 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002043 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 -06002044 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002045 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
2046 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05002047 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002048 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 -06002049 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002050 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05002051 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07002052 string_VkDescriptorType(binding->descriptorType));
2053 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002054 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 -06002055 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002056 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
2057 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07002058 }
2059 }
2060
2061 // Validate use of input attachments against subpass structure
2062 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002063 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07002064
Petr Krause91f7a12017-12-14 20:57:36 +01002065 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002066 auto subpass = pipeline->graphicsPipelineCI.subpass;
2067
2068 for (auto use : input_attachment_uses) {
2069 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
2070 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07002071 ? input_attachments[use.first].attachment
2072 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07002073
2074 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002075 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 -06002076 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07002077 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002078 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002079 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002080 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 -06002081 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002082 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002083 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002084 }
2085 }
2086 }
2087
2088 return skip;
2089}
2090
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002091static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
2092 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
2093 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
2094 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07002095 bool skip = false;
2096
2097 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002098 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
2099 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07002100
2101 auto a_it = outputs.begin();
2102 auto b_it = inputs.begin();
2103
2104 // Maps sorted by key (location); walk them together to find mismatches
2105 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
2106 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
2107 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
2108 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
2109 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
2110
2111 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06002112 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 -06002113 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06002114 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
2115 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002116 a_it++;
2117 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06002118 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 -06002119 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06002120 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
2121 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002122 b_it++;
2123 } else {
2124 // subtleties of arrayed interfaces:
2125 // - if is_patch, then the member is not arrayed, even though the interface may be.
2126 // - if is_block_member, then the extra array level of an arrayed interface is not
2127 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002128 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
2129 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
2130 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06002131 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 -06002132 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06002133 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002134 DescribeType(producer, a_it->second.type_id).c_str(),
2135 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002136 }
2137 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06002138 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 -06002139 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002140 "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 -07002141 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
2142 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
2143 }
2144 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06002145 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 -06002146 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002147 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
2148 a_first.second, producer_stage->name, consumer_stage->name);
2149 }
2150 a_it++;
2151 b_it++;
2152 }
2153 }
2154
2155 return skip;
2156}
2157
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002158static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
2159 uint32_t stage_mask = 0;
2160 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2161 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2162 stage_mask |= pCreateInfo->pStages[i].stage;
2163 }
2164 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05002165 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
2166 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
2167 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002168 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
2169 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
2170 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2171 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
2172 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002173 }
2174 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002175 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002176}
2177
Chris Forbes47567b72017-06-09 12:09:45 -07002178// Validate that the shaders used by the given pipeline and store the active_slots
2179// that are actually used by the pipeline into pPipeline->active_slots
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002180bool ValidateAndCapturePipelineShaderState(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002181 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002182 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2183 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002184 auto report_data = GetReportData(dev_data);
2185
Jeff Bolz7e35c392018-09-04 15:30:41 -05002186 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002187 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002188 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002189 memset(entrypoints, 0, sizeof(entrypoints));
2190 bool skip = false;
2191
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002192 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
2193
Chris Forbes47567b72017-06-09 12:09:45 -07002194 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2195 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002196 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002197 skip |= ValidatePipelineShaderStage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
2198 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002199 }
2200
2201 // if the shader stages are no good individually, cross-stage validation is pointless.
2202 if (skip) return true;
2203
2204 auto vi = pCreateInfo->pVertexInputState;
2205
2206 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002207 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07002208 }
2209
2210 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002211 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07002212 }
2213
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002214 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2215 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002216
2217 while (!shaders[producer] && producer != fragment_stage) {
2218 producer++;
2219 consumer++;
2220 }
2221
2222 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
2223 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002224 if (shaders[consumer]) {
2225 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002226 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
2227 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
2228 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002229 }
Chris Forbes47567b72017-06-09 12:09:45 -07002230
2231 producer = consumer;
2232 }
2233 }
2234
2235 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002236 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
2237 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07002238 }
2239
2240 return skip;
2241}
2242
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002243bool ValidateComputePipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002244 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002245
2246 shader_module const *module;
2247 spirv_inst_iter entrypoint;
2248
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002249 return ValidatePipelineShaderStage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07002250}
Chris Forbes4ae55b32017-06-09 14:42:56 -07002251
Eric Werness30127fd2018-10-31 21:01:03 -07002252bool ValidateRayTracingPipelineNV(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Jeff Bolzfbe51582018-09-13 10:01:35 -05002253 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
2254
2255 shader_module const *module;
2256 spirv_inst_iter entrypoint;
2257
2258 return ValidatePipelineShaderStage(dev_data, pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
2259}
2260
Dave Houltona9df0ce2018-02-07 10:51:23 -07002261uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07002262
Dave Houltona9df0ce2018-02-07 10:51:23 -07002263static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07002264 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
2265 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
2266 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
2267 }
2268
2269 return nullptr;
2270}
2271
Mark Lobodzinski01734072019-02-13 17:39:15 -07002272bool PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2273 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
2274 layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map);
2275
Chris Forbes4ae55b32017-06-09 14:42:56 -07002276 bool skip = false;
2277 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002278
Mark Lobodzinski01734072019-02-13 17:39:15 -07002279 if (GetDisables(device_data)->shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002280 return false;
2281 }
2282
Mark Lobodzinski01734072019-02-13 17:39:15 -07002283 auto have_glsl_shader = GetDeviceExtensions(device_data)->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002284
2285 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07002286 skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06002287 "VUID-VkShaderModuleCreateInfo-pCode-01376",
2288 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
2289 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002290 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07002291 auto cache = GetValidationCacheInfo(pCreateInfo);
2292 uint32_t hash = 0;
2293 if (cache) {
2294 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002295 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07002296 }
2297
Chris Forbes4ae55b32017-06-09 14:42:56 -07002298 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06002299 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Mark Lobodzinski01734072019-02-13 17:39:15 -07002300 if (GetApiVersion(device_data) >= VK_API_VERSION_1_1) {
Dave Houlton0ea2d012018-06-21 14:00:26 -06002301 spirv_environment = SPV_ENV_VULKAN_1_1;
2302 }
2303 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002304 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07002305 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06002306 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinski01734072019-02-13 17:39:15 -07002307 if (GetDeviceExtensions(device_data)->vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06002308 spvValidatorOptionsSetRelaxBlockLayout(options, true);
2309 }
Mark Lobodzinski01734072019-02-13 17:39:15 -07002310 if (GetDeviceExtensions(device_data)->vk_ext_scalar_block_layout &&
2311 GetEnabledFeatures(device_data)->scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00002312 spvValidatorOptionsSetScalarBlockLayout(options, true);
2313 }
Karl Schultzfda1b382018-08-08 18:56:11 -06002314 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002315 if (spv_valid != SPV_SUCCESS) {
2316 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07002317 skip |= log_msg(device_data->report_data,
2318 spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
2319 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
2320 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07002321 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002322 } else {
2323 if (cache) {
2324 cache->Insert(hash);
2325 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002326 }
2327
Karl Schultzfda1b382018-08-08 18:56:11 -06002328 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002329 spvDiagnosticDestroy(diag);
2330 spvContextDestroy(ctx);
2331 }
2332
Chris Forbes4ae55b32017-06-09 14:42:56 -07002333 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07002334}
2335
2336void PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2337 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
2338 create_shader_module_api_state *csm_state) {
2339 layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), core_validation::layer_data_map);
2340
2341 if (GetEnables(device_data)->gpu_validation) {
2342 GpuPreCallCreateShaderModule(device_data, pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
2343 &csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
2344 }
2345}
2346
2347void PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2348 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule, VkResult result,
2349 create_shader_module_api_state *csm_state) {
2350 layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), core_validation::layer_data_map);
2351 if (VK_SUCCESS != result) return;
2352
2353 spv_target_env spirv_environment =
2354 ((GetApiVersion(device_data) >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
2355 bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
2356 std::unique_ptr<shader_module> new_shader_module(
2357 is_spirv ? new shader_module(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
2358 : new shader_module());
2359 device_data->shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
2360}