blob: ab743e92a145cf65b8926ffec23176adc1786fd5 [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"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070035#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070036#include "core_validation.h"
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070038#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070039#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040
41enum FORMAT_TYPE {
42 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
43 FORMAT_TYPE_SINT = 2,
44 FORMAT_TYPE_UINT = 4,
45};
46
47typedef std::pair<unsigned, unsigned> location_t;
48
49struct interface_var {
50 uint32_t id;
51 uint32_t type_id;
52 uint32_t offset;
53 bool is_patch;
54 bool is_block_member;
55 bool is_relaxed_precision;
56 // TODO: collect the name, too? Isn't required to be present.
57};
58
59struct shader_stage_attributes {
60 char const *const name;
61 bool arrayed_input;
62 bool arrayed_output;
63};
64
65static shader_stage_attributes shader_stage_attribs[] = {
66 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
67 {"geometry shader", true, false}, {"fragment shader", false, false},
68};
69
70// SPIRV utility functions
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060071void shader_module::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -070072 for (auto insn : *this) {
73 switch (insn.opcode()) {
74 // Types
75 case spv::OpTypeVoid:
76 case spv::OpTypeBool:
77 case spv::OpTypeInt:
78 case spv::OpTypeFloat:
79 case spv::OpTypeVector:
80 case spv::OpTypeMatrix:
81 case spv::OpTypeImage:
82 case spv::OpTypeSampler:
83 case spv::OpTypeSampledImage:
84 case spv::OpTypeArray:
85 case spv::OpTypeRuntimeArray:
86 case spv::OpTypeStruct:
87 case spv::OpTypeOpaque:
88 case spv::OpTypePointer:
89 case spv::OpTypeFunction:
90 case spv::OpTypeEvent:
91 case spv::OpTypeDeviceEvent:
92 case spv::OpTypeReserveId:
93 case spv::OpTypeQueue:
94 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -060095 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -060096 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -070097 def_index[insn.word(1)] = insn.offset();
98 break;
99
100 // Fixed constants
101 case spv::OpConstantTrue:
102 case spv::OpConstantFalse:
103 case spv::OpConstant:
104 case spv::OpConstantComposite:
105 case spv::OpConstantSampler:
106 case spv::OpConstantNull:
107 def_index[insn.word(2)] = insn.offset();
108 break;
109
110 // Specialization constants
111 case spv::OpSpecConstantTrue:
112 case spv::OpSpecConstantFalse:
113 case spv::OpSpecConstant:
114 case spv::OpSpecConstantComposite:
115 case spv::OpSpecConstantOp:
116 def_index[insn.word(2)] = insn.offset();
117 break;
118
119 // Variables
120 case spv::OpVariable:
121 def_index[insn.word(2)] = insn.offset();
122 break;
123
124 // Functions
125 case spv::OpFunction:
126 def_index[insn.word(2)] = insn.offset();
127 break;
128
129 default:
130 // We don't care about any other defs for now.
131 break;
132 }
133 }
134}
135
Jeff Bolz105d6492018-09-29 15:46:44 -0500136unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
137 switch (mode) {
138 case spv::ExecutionModelVertex:
139 return VK_SHADER_STAGE_VERTEX_BIT;
140 case spv::ExecutionModelTessellationControl:
141 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
142 case spv::ExecutionModelTessellationEvaluation:
143 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
144 case spv::ExecutionModelGeometry:
145 return VK_SHADER_STAGE_GEOMETRY_BIT;
146 case spv::ExecutionModelFragment:
147 return VK_SHADER_STAGE_FRAGMENT_BIT;
148 case spv::ExecutionModelGLCompute:
149 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600150 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700151 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600152 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700153 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600154 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700155 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600156 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700157 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600158 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700159 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600160 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700161 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500162 case spv::ExecutionModelTaskNV:
163 return VK_SHADER_STAGE_TASK_BIT_NV;
164 case spv::ExecutionModelMeshNV:
165 return VK_SHADER_STAGE_MESH_BIT_NV;
166 default:
167 return 0;
168 }
169}
170
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600171static spirv_inst_iter FindEntrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
Chris Forbes47567b72017-06-09 12:09:45 -0700172 for (auto insn : *src) {
173 if (insn.opcode() == spv::OpEntryPoint) {
174 auto entrypointName = (char const *)&insn.word(3);
Jeff Bolz105d6492018-09-29 15:46:44 -0500175 auto executionModel = insn.word(1);
176 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
Chris Forbes47567b72017-06-09 12:09:45 -0700177
178 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
179 return insn;
180 }
181 }
182 }
183
184 return src->end();
185}
186
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600187static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700188 switch (sc) {
189 case spv::StorageClassInput:
190 return "input";
191 case spv::StorageClassOutput:
192 return "output";
193 case spv::StorageClassUniformConstant:
194 return "const uniform";
195 case spv::StorageClassUniform:
196 return "uniform";
197 case spv::StorageClassWorkgroup:
198 return "workgroup local";
199 case spv::StorageClassCrossWorkgroup:
200 return "workgroup global";
201 case spv::StorageClassPrivate:
202 return "private global";
203 case spv::StorageClassFunction:
204 return "function";
205 case spv::StorageClassGeneric:
206 return "generic";
207 case spv::StorageClassAtomicCounter:
208 return "atomic counter";
209 case spv::StorageClassImage:
210 return "image";
211 case spv::StorageClassPushConstant:
212 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800213 case spv::StorageClassStorageBuffer:
214 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700215 default:
216 return "unknown";
217 }
218}
219
220// Get the value of an integral constant
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600221unsigned GetConstantValue(shader_module const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700222 auto value = src->get_def(id);
223 assert(value != src->end());
224
225 if (value.opcode() != spv::OpConstant) {
226 // TODO: Either ensure that the specialization transform is already performed on a module we're
227 // considering here, OR -- specialize on the fly now.
228 return 1;
229 }
230
231 return value.word(3);
232}
233
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600234static void DescribeTypeInner(std::ostringstream &ss, shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700235 auto insn = src->get_def(type);
236 assert(insn != src->end());
237
238 switch (insn.opcode()) {
239 case spv::OpTypeBool:
240 ss << "bool";
241 break;
242 case spv::OpTypeInt:
243 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
244 break;
245 case spv::OpTypeFloat:
246 ss << "float" << insn.word(2);
247 break;
248 case spv::OpTypeVector:
249 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600250 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700251 break;
252 case spv::OpTypeMatrix:
253 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600254 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700255 break;
256 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600257 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
258 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700259 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700260 case spv::OpTypeRuntimeArray:
261 ss << "runtime arr[] of ";
262 DescribeTypeInner(ss, src, insn.word(2));
263 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700264 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600265 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
266 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700267 break;
268 case spv::OpTypeStruct: {
269 ss << "struct of (";
270 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600271 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700272 if (i == insn.len() - 1) {
273 ss << ")";
274 } else {
275 ss << ", ";
276 }
277 }
278 break;
279 }
280 case spv::OpTypeSampler:
281 ss << "sampler";
282 break;
283 case spv::OpTypeSampledImage:
284 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600285 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700286 break;
287 case spv::OpTypeImage:
288 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
289 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600290 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500291 ss << "accelerationStruture";
292 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700293 default:
294 ss << "oddtype";
295 break;
296 }
297}
298
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600299static std::string DescribeType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700300 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600301 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700302 return ss.str();
303}
304
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600305static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700306 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
307 return type.word(2) < 64;
308}
309
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600310static bool TypesMatch(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
311 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700312 // Walk two type trees together, and complain about differences
313 auto a_insn = a->get_def(a_type);
314 auto b_insn = b->get_def(b_type);
315 assert(a_insn != a->end());
316 assert(b_insn != b->end());
317
Chris Forbes062f1222018-08-21 15:34:15 -0700318 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
319
Chris Forbes47567b72017-06-09 12:09:45 -0700320 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600321 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700322 }
323
324 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
325 // 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 -0600326 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700327 }
328
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600329 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
330 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700331 }
332
333 if (a_insn.opcode() != b_insn.opcode()) {
334 return false;
335 }
336
337 if (a_insn.opcode() == spv::OpTypePointer) {
338 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600339 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700340 }
341
342 if (a_arrayed || b_arrayed) {
343 // If we havent resolved array-of-verts by here, we're not going to.
344 return false;
345 }
346
347 switch (a_insn.opcode()) {
348 case spv::OpTypeBool:
349 return true;
350 case spv::OpTypeInt:
351 // Match on width, signedness
352 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
353 case spv::OpTypeFloat:
354 // Match on width
355 return a_insn.word(2) == b_insn.word(2);
356 case spv::OpTypeVector:
357 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600358 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
359 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700360 return a_insn.word(3) >= b_insn.word(3);
361 } else {
362 return a_insn.word(3) == b_insn.word(3);
363 }
364 case spv::OpTypeMatrix:
365 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600366 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700367 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700368 case spv::OpTypeArray:
369 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
370 // 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 -0600371 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
372 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700373 case spv::OpTypeStruct:
374 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700375 {
376 if (a_insn.len() != b_insn.len()) {
377 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700378 }
Chris Forbes47567b72017-06-09 12:09:45 -0700379
Dave Houltona9df0ce2018-02-07 10:51:23 -0700380 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600381 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700382 return false;
383 }
384 }
385
386 return true;
387 }
Chris Forbes47567b72017-06-09 12:09:45 -0700388 default:
389 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
390 return false;
391 }
392}
393
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600394static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700395 auto it = map.find(id);
396 if (it == map.end())
397 return def;
398 else
399 return it->second;
400}
401
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600402static unsigned GetLocationsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700403 auto insn = src->get_def(type);
404 assert(insn != src->end());
405
406 switch (insn.opcode()) {
407 case spv::OpTypePointer:
408 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
409 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600410 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700411 case spv::OpTypeArray:
412 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700414 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600415 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700416 }
417 case spv::OpTypeMatrix:
418 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600419 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700420 case spv::OpTypeVector: {
421 auto scalar_type = src->get_def(insn.word(2));
422 auto bit_width =
423 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
424
425 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
426 return (bit_width * insn.word(3) + 127) / 128;
427 }
428 default:
429 // Everything else is just 1.
430 return 1;
431
432 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
433 }
434}
435
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200436static unsigned GetComponentsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
437 auto insn = src->get_def(type);
438 assert(insn != src->end());
439
440 switch (insn.opcode()) {
441 case spv::OpTypePointer:
442 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
443 // pointers around.
444 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
445 case spv::OpTypeStruct: {
446 uint32_t sum = 0;
447 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
448 sum += GetComponentsConsumedByType(src, insn.word(i), false);
449 }
450 return sum;
451 }
452 case spv::OpTypeArray: {
453 uint32_t sum = 0;
454 for (uint32_t i = 2; i < insn.len(); i++) {
455 sum += GetComponentsConsumedByType(src, insn.word(i), false);
456 }
457 return sum;
458 }
459 case spv::OpTypeMatrix:
460 // Num locations is the dimension * element size
461 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
462 case spv::OpTypeVector: {
463 auto scalar_type = src->get_def(insn.word(2));
464 auto bit_width =
465 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
466 // One component is 32-bit
467 return (bit_width * insn.word(3) + 31) / 32;
468 }
469 case spv::OpTypeFloat: {
470 auto bit_width = insn.word(2);
471 return (bit_width + 31) / 32;
472 }
473 case spv::OpTypeInt: {
474 auto bit_width = insn.word(2);
475 return (bit_width + 31) / 32;
476 }
477 case spv::OpConstant:
478 return GetComponentsConsumedByType(src, insn.word(1), false);
479 default:
480 return 0;
481 }
482}
483
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600484static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700485 switch (format) {
486 case VK_FORMAT_R64G64B64A64_SFLOAT:
487 case VK_FORMAT_R64G64B64A64_SINT:
488 case VK_FORMAT_R64G64B64A64_UINT:
489 case VK_FORMAT_R64G64B64_SFLOAT:
490 case VK_FORMAT_R64G64B64_SINT:
491 case VK_FORMAT_R64G64B64_UINT:
492 return 2;
493 default:
494 return 1;
495 }
496}
497
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600498static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700499 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
500 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
501 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
502 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700503 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
504 return FORMAT_TYPE_FLOAT;
505}
506
507// 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 -0700508// also used for input attachments, as we statically know their format.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600509static unsigned GetFundamentalType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700510 auto insn = src->get_def(type);
511 assert(insn != src->end());
512
513 switch (insn.opcode()) {
514 case spv::OpTypeInt:
515 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
516 case spv::OpTypeFloat:
517 return FORMAT_TYPE_FLOAT;
518 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700519 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700520 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700521 case spv::OpTypeRuntimeArray:
522 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600523 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700524 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600525 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700526
527 default:
528 return 0;
529 }
530}
531
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600532static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700533 uint32_t bit_pos = uint32_t(u_ffs(stage));
534 return bit_pos - 1;
535}
536
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600537static spirv_inst_iter GetStructType(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700538 while (true) {
539 if (def.opcode() == spv::OpTypePointer) {
540 def = src->get_def(def.word(3));
541 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
542 def = src->get_def(def.word(2));
543 is_array_of_verts = false;
544 } else if (def.opcode() == spv::OpTypeStruct) {
545 return def;
546 } else {
547 return src->end();
548 }
549 }
550}
551
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600552static bool CollectInterfaceBlockMembers(shader_module const *src, std::map<location_t, interface_var> *out,
553 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts, uint32_t id,
554 uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700555 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600556 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700557 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
558 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700559 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700560 }
561
562 std::unordered_map<unsigned, unsigned> member_components;
563 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700564 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700565
566 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
567 for (auto insn : *src) {
568 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
569 unsigned member_index = insn.word(2);
570
571 if (insn.word(3) == spv::DecorationComponent) {
572 unsigned component = insn.word(4);
573 member_components[member_index] = component;
574 }
575
576 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
577 member_relaxed_precision[member_index] = 1;
578 }
Chris Forbesa313d772017-06-13 13:59:41 -0700579
580 if (insn.word(3) == spv::DecorationPatch) {
581 member_patch[member_index] = 1;
582 }
Chris Forbes47567b72017-06-09 12:09:45 -0700583 }
584 }
585
Chris Forbesa313d772017-06-13 13:59:41 -0700586 // TODO: correctly handle location assignment from outside
587
Chris Forbes47567b72017-06-09 12:09:45 -0700588 // Second pass -- produce the output, from Location decorations
589 for (auto insn : *src) {
590 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
591 unsigned member_index = insn.word(2);
592 unsigned member_type_id = type.word(2 + member_index);
593
594 if (insn.word(3) == spv::DecorationLocation) {
595 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600596 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700597 auto component_it = member_components.find(member_index);
598 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
599 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700600 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700601
602 for (unsigned int offset = 0; offset < num_locations; offset++) {
603 interface_var v = {};
604 v.id = id;
605 // TODO: member index in interface_var too?
606 v.type_id = member_type_id;
607 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700608 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700609 v.is_block_member = true;
610 v.is_relaxed_precision = is_relaxed_precision;
611 (*out)[std::make_pair(location + offset, component)] = v;
612 }
613 }
614 }
615 }
Chris Forbesa313d772017-06-13 13:59:41 -0700616
617 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700618}
619
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600620static std::map<location_t, interface_var> CollectInterfaceByLocation(shader_module const *src, spirv_inst_iter entrypoint,
621 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700622 std::unordered_map<unsigned, unsigned> var_locations;
623 std::unordered_map<unsigned, unsigned> var_builtins;
624 std::unordered_map<unsigned, unsigned> var_components;
625 std::unordered_map<unsigned, unsigned> blocks;
626 std::unordered_map<unsigned, unsigned> var_patch;
627 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
628
629 for (auto insn : *src) {
630 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
631 // fits neither model.
632 if (insn.opcode() == spv::OpDecorate) {
633 if (insn.word(2) == spv::DecorationLocation) {
634 var_locations[insn.word(1)] = insn.word(3);
635 }
636
637 if (insn.word(2) == spv::DecorationBuiltIn) {
638 var_builtins[insn.word(1)] = insn.word(3);
639 }
640
641 if (insn.word(2) == spv::DecorationComponent) {
642 var_components[insn.word(1)] = insn.word(3);
643 }
644
645 if (insn.word(2) == spv::DecorationBlock) {
646 blocks[insn.word(1)] = 1;
647 }
648
649 if (insn.word(2) == spv::DecorationPatch) {
650 var_patch[insn.word(1)] = 1;
651 }
652
653 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
654 var_relaxed_precision[insn.word(1)] = 1;
655 }
656 }
657 }
658
659 // TODO: handle grouped decorations
660 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
661
662 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
663 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
664 uint32_t word = 3;
665 while (entrypoint.word(word) & 0xff000000u) {
666 ++word;
667 }
668 ++word;
669
670 std::map<location_t, interface_var> out;
671
672 for (; word < entrypoint.len(); word++) {
673 auto insn = src->get_def(entrypoint.word(word));
674 assert(insn != src->end());
675 assert(insn.opcode() == spv::OpVariable);
676
677 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
678 unsigned id = insn.word(2);
679 unsigned type = insn.word(1);
680
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600681 int location = ValueOrDefault(var_locations, id, static_cast<unsigned>(-1));
682 int builtin = ValueOrDefault(var_builtins, id, static_cast<unsigned>(-1));
683 unsigned component = ValueOrDefault(var_components, id, 0); // Unspecified is OK, is 0
Chris Forbes47567b72017-06-09 12:09:45 -0700684 bool is_patch = var_patch.find(id) != var_patch.end();
685 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
686
Dave Houltona9df0ce2018-02-07 10:51:23 -0700687 if (builtin != -1)
688 continue;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600689 else if (!CollectInterfaceBlockMembers(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700690 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
691 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600692 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700693 for (unsigned int offset = 0; offset < num_locations; offset++) {
694 interface_var v = {};
695 v.id = id;
696 v.type_id = type;
697 v.offset = offset;
698 v.is_patch = is_patch;
699 v.is_relaxed_precision = is_relaxed_precision;
700 out[std::make_pair(location + offset, component)] = v;
701 }
Chris Forbes47567b72017-06-09 12:09:45 -0700702 }
703 }
704 }
705
706 return out;
707}
708
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600709static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Chris Forbes47567b72017-06-09 12:09:45 -0700710 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
711 std::vector<std::pair<uint32_t, interface_var>> out;
712
713 for (auto insn : *src) {
714 if (insn.opcode() == spv::OpDecorate) {
715 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
716 auto attachment_index = insn.word(3);
717 auto id = insn.word(1);
718
719 if (accessible_ids.count(id)) {
720 auto def = src->get_def(id);
721 assert(def != src->end());
722
723 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600724 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700725 for (unsigned int offset = 0; offset < num_locations; offset++) {
726 interface_var v = {};
727 v.id = id;
728 v.type_id = def.word(1);
729 v.offset = offset;
730 out.emplace_back(attachment_index + offset, v);
731 }
732 }
733 }
734 }
735 }
736 }
737
738 return out;
739}
740
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700741static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800742 auto type = module->get_def(type_id);
743
744 // 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 -0700745 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
746 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700747 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800748 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700749 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800750 }
751 }
752
753 switch (type.opcode()) {
754 case spv::OpTypeImage: {
755 auto dim = type.word(3);
756 auto sampled = type.word(7);
757 return sampled == 2 && dim != spv::DimSubpassData;
758 }
759
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700760 case spv::OpTypeStruct: {
761 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8af24522018-03-07 11:37:45 -0800762 for (auto insn : *module) {
763 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
764 if (insn.word(2) == spv::DecorationBufferBlock) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700765 // Legacy storage block in the Uniform storage class
766 // has its struct type decorated with BufferBlock.
767 is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800768 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700769 } else if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
770 insn.word(3) == spv::DecorationNonWritable) {
771 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800772 }
773 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700774
775 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
776 // as nonwritable.
777 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
778 }
Chris Forbes8af24522018-03-07 11:37:45 -0800779 }
780
781 return false;
782}
783
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600784static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800785 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
786 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700787 std::unordered_map<unsigned, unsigned> var_sets;
788 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800789 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700790
791 for (auto insn : *src) {
792 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
793 // DecorationDescriptorSet and DecorationBinding.
794 if (insn.opcode() == spv::OpDecorate) {
795 if (insn.word(2) == spv::DecorationDescriptorSet) {
796 var_sets[insn.word(1)] = insn.word(3);
797 }
798
799 if (insn.word(2) == spv::DecorationBinding) {
800 var_bindings[insn.word(1)] = insn.word(3);
801 }
Chris Forbes8af24522018-03-07 11:37:45 -0800802
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700803 // Note: do toplevel DecorationNonWritable out here; it applies to
804 // the OpVariable rather than the type.
Chris Forbes8af24522018-03-07 11:37:45 -0800805 if (insn.word(2) == spv::DecorationNonWritable) {
806 var_nonwritable[insn.word(1)] = 1;
807 }
Chris Forbes47567b72017-06-09 12:09:45 -0700808 }
809 }
810
811 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
812
813 for (auto id : accessible_ids) {
814 auto insn = src->get_def(id);
815 assert(insn != src->end());
816
817 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800818 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
819 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600820 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
821 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700822
823 interface_var v = {};
824 v.id = insn.word(2);
825 v.type_id = insn.word(1);
826 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800827
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700828 if (var_nonwritable.find(id) == var_nonwritable.end() &&
829 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800830 *has_writable_descriptor = true;
831 }
Chris Forbes47567b72017-06-09 12:09:45 -0700832 }
833 }
834
835 return out;
836}
837
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600838static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700839 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
840 // be specified only once.
841 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
842 bool skip = false;
843
844 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
845 auto desc = &vi->pVertexBindingDescriptions[i];
846 auto &binding = bindings[desc->binding];
847 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600848 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600849 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 -0600850 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700851 desc->binding);
852 } else {
853 binding = desc;
854 }
855 }
856
857 return skip;
858}
859
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600860static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
861 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700862 bool skip = false;
863
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600864 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700865
866 // Build index by location
867 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
868 if (vi) {
869 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600870 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700871 for (auto j = 0u; j < num_locations; j++) {
872 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
873 }
874 }
875 }
876
877 auto it_a = attribs.begin();
878 auto it_b = inputs.begin();
879 bool used = false;
880
881 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
882 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
883 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
884 auto a_first = a_at_end ? 0 : it_a->first;
885 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600886
Chris Forbes47567b72017-06-09 12:09:45 -0700887 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600888 if (!used &&
889 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 -0600890 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600891 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700892 skip = true;
893 }
894 used = false;
895 it_a++;
896 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600897 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 -0600898 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600899 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700900 it_b++;
901 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600902 unsigned attrib_type = GetFormatType(it_a->second->format);
903 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700904
905 // Type checking
906 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600907 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 -0600908 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700909 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600910 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700911 }
912
913 // OK!
914 used = true;
915 it_b++;
916 }
917 }
918
919 return skip;
920}
921
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600922static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
923 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100924 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700925
Chris Forbes47567b72017-06-09 12:09:45 -0700926 std::map<uint32_t, VkFormat> color_attachments;
927 auto subpass = rpci->pSubpasses[subpass_index];
928 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
929 uint32_t attachment = subpass.pColorAttachments[i].attachment;
930 if (attachment == VK_ATTACHMENT_UNUSED) continue;
931 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
932 color_attachments[i] = rpci->pAttachments[attachment].format;
933 }
934 }
935
936 bool skip = false;
937
938 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
939
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600940 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700941
942 auto it_a = outputs.begin();
943 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600944 bool used = false;
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200945 bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
946 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
947 bool locationZeroHasAlpha = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700948
949 // Walk attachment list and outputs together
950
951 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
952 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
953 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
954
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200955 if (!a_at_end && it_a->first.first == 0 && fs->get_def(it_a->second.type_id) != fs->end() &&
956 GetComponentsConsumedByType(fs, it_a->second.type_id, false) == 4)
957 locationZeroHasAlpha = true;
958
Chris Forbes47567b72017-06-09 12:09:45 -0700959 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200960 if (!alphaToCoverageEnabled || it_a->first.first != 0) {
961 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
962 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
963 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
964 }
Chris Forbes47567b72017-06-09 12:09:45 -0700965 it_a++;
966 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700967 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
968 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600969 if (!used) {
970 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700971 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 -0600972 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Chris Forbescfe4dca2018-10-05 10:15:00 -0700973 "Attachment %d not written by fragment shader; undefined values will be written to attachment",
974 it_b->first);
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600975 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700976 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600977 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700978 it_b++;
979 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600980 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
981 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700982
983 // Type checking
984 if (!(output_type & att_type)) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700985 skip |= log_msg(
986 report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
987 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
988 "Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
989 it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700990 }
991
992 // OK!
993 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600994 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700995 }
996 }
997
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200998 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
999 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1000 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1001 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
1002 }
1003
Chris Forbes47567b72017-06-09 12:09:45 -07001004 return skip;
1005}
1006
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001007// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1008// This function examines instructions in the static call tree for a write to this variable.
1009static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
1010 auto type = builtin_instr.opcode();
1011 uint32_t target_id = builtin_instr.word(1);
1012 bool init_complete = false;
1013
1014 if (type == spv::OpMemberDecorate) {
1015 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1016 auto insn = entrypoint;
1017 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1018 switch (insn.opcode()) {
1019 case spv::OpTypePointer:
1020 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1021 target_id = insn.word(1);
1022 }
1023 break;
1024 case spv::OpVariable:
1025 if (insn.word(1) == target_id) {
1026 target_id = insn.word(2);
1027 init_complete = true;
1028 }
1029 break;
1030 }
1031 insn++;
1032 }
1033 }
1034
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001035 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1036
1037 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001038 std::unordered_set<uint32_t> worklist;
1039 worklist.insert(entrypoint.word(2));
1040
1041 // Follow instructions in call graph looking for writes to target
1042 while (!worklist.empty() && !found_write) {
1043 auto id_iter = worklist.begin();
1044 auto id = *id_iter;
1045 worklist.erase(id_iter);
1046
1047 auto insn = src->get_def(id);
1048 if (insn == src->end()) {
1049 continue;
1050 }
1051
1052 if (insn.opcode() == spv::OpFunction) {
1053 // Scan body of function looking for other function calls or items in our ID chain
1054 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1055 switch (insn.opcode()) {
1056 case spv::OpAccessChain:
1057 if (insn.word(3) == target_id) {
1058 if (type == spv::OpMemberDecorate) {
1059 auto value = GetConstantValue(src, insn.word(4));
1060 if (value == builtin_instr.word(2)) {
1061 target_id = insn.word(2);
1062 }
1063 } else {
1064 target_id = insn.word(2);
1065 }
1066 }
1067 break;
1068 case spv::OpStore:
1069 if (insn.word(1) == target_id) {
1070 found_write = true;
1071 }
1072 break;
1073 case spv::OpFunctionCall:
1074 worklist.insert(insn.word(3));
1075 break;
1076 }
1077 }
1078 }
1079 }
1080 return found_write;
1081}
1082
Chris Forbes47567b72017-06-09 12:09:45 -07001083// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1084// important for identifying the set of shader resources actually used by an entrypoint, for example.
1085// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1086// - NOT the shader input/output interfaces.
1087//
1088// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1089// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001090static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001091 std::unordered_set<uint32_t> ids;
1092 std::unordered_set<uint32_t> worklist;
1093 worklist.insert(entrypoint.word(2));
1094
1095 while (!worklist.empty()) {
1096 auto id_iter = worklist.begin();
1097 auto id = *id_iter;
1098 worklist.erase(id_iter);
1099
1100 auto insn = src->get_def(id);
1101 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001102 // 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 -07001103 // that we may not care about.
1104 continue;
1105 }
1106
1107 // Try to add to the output set
1108 if (!ids.insert(id).second) {
1109 continue; // If we already saw this id, we don't want to walk it again.
1110 }
1111
1112 switch (insn.opcode()) {
1113 case spv::OpFunction:
1114 // Scan whole body of the function, enlisting anything interesting
1115 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1116 switch (insn.opcode()) {
1117 case spv::OpLoad:
1118 case spv::OpAtomicLoad:
1119 case spv::OpAtomicExchange:
1120 case spv::OpAtomicCompareExchange:
1121 case spv::OpAtomicCompareExchangeWeak:
1122 case spv::OpAtomicIIncrement:
1123 case spv::OpAtomicIDecrement:
1124 case spv::OpAtomicIAdd:
1125 case spv::OpAtomicISub:
1126 case spv::OpAtomicSMin:
1127 case spv::OpAtomicUMin:
1128 case spv::OpAtomicSMax:
1129 case spv::OpAtomicUMax:
1130 case spv::OpAtomicAnd:
1131 case spv::OpAtomicOr:
1132 case spv::OpAtomicXor:
1133 worklist.insert(insn.word(3)); // ptr
1134 break;
1135 case spv::OpStore:
1136 case spv::OpAtomicStore:
1137 worklist.insert(insn.word(1)); // ptr
1138 break;
1139 case spv::OpAccessChain:
1140 case spv::OpInBoundsAccessChain:
1141 worklist.insert(insn.word(3)); // base ptr
1142 break;
1143 case spv::OpSampledImage:
1144 case spv::OpImageSampleImplicitLod:
1145 case spv::OpImageSampleExplicitLod:
1146 case spv::OpImageSampleDrefImplicitLod:
1147 case spv::OpImageSampleDrefExplicitLod:
1148 case spv::OpImageSampleProjImplicitLod:
1149 case spv::OpImageSampleProjExplicitLod:
1150 case spv::OpImageSampleProjDrefImplicitLod:
1151 case spv::OpImageSampleProjDrefExplicitLod:
1152 case spv::OpImageFetch:
1153 case spv::OpImageGather:
1154 case spv::OpImageDrefGather:
1155 case spv::OpImageRead:
1156 case spv::OpImage:
1157 case spv::OpImageQueryFormat:
1158 case spv::OpImageQueryOrder:
1159 case spv::OpImageQuerySizeLod:
1160 case spv::OpImageQuerySize:
1161 case spv::OpImageQueryLod:
1162 case spv::OpImageQueryLevels:
1163 case spv::OpImageQuerySamples:
1164 case spv::OpImageSparseSampleImplicitLod:
1165 case spv::OpImageSparseSampleExplicitLod:
1166 case spv::OpImageSparseSampleDrefImplicitLod:
1167 case spv::OpImageSparseSampleDrefExplicitLod:
1168 case spv::OpImageSparseSampleProjImplicitLod:
1169 case spv::OpImageSparseSampleProjExplicitLod:
1170 case spv::OpImageSparseSampleProjDrefImplicitLod:
1171 case spv::OpImageSparseSampleProjDrefExplicitLod:
1172 case spv::OpImageSparseFetch:
1173 case spv::OpImageSparseGather:
1174 case spv::OpImageSparseDrefGather:
1175 case spv::OpImageTexelPointer:
1176 worklist.insert(insn.word(3)); // Image or sampled image
1177 break;
1178 case spv::OpImageWrite:
1179 worklist.insert(insn.word(1)); // Image -- different operand order to above
1180 break;
1181 case spv::OpFunctionCall:
1182 for (uint32_t i = 3; i < insn.len(); i++) {
1183 worklist.insert(insn.word(i)); // fn itself, and all args
1184 }
1185 break;
1186
1187 case spv::OpExtInst:
1188 for (uint32_t i = 5; i < insn.len(); i++) {
1189 worklist.insert(insn.word(i)); // Operands to ext inst
1190 }
1191 break;
1192 }
1193 }
1194 break;
1195 }
1196 }
1197
1198 return ids;
1199}
1200
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001201static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1202 std::vector<VkPushConstantRange> const *push_constant_ranges,
1203 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001204 bool skip = false;
1205
1206 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001207 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001208 assert(type != src->end());
1209
1210 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1211 // TODO: arrays, matrices, weird sizes
1212 for (auto insn : *src) {
1213 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1214 if (insn.word(3) == spv::DecorationOffset) {
1215 unsigned offset = insn.word(4);
1216 auto size = 4; // Bytes; TODO: calculate this based on the type
1217
1218 bool found_range = false;
1219 for (auto const &range : *push_constant_ranges) {
1220 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1221 found_range = true;
1222
1223 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001224 skip |=
1225 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 -06001226 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001227 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1228 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001229 }
1230
1231 break;
1232 }
1233 }
1234
1235 if (!found_range) {
1236 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 -06001237 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001238 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001239 }
1240 }
1241 }
1242 }
1243
1244 return skip;
1245}
1246
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001247static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1248 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1249 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001250 bool skip = false;
1251
1252 for (auto id : accessible_ids) {
1253 auto def_insn = src->get_def(id);
1254 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001255 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1256 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001257 }
1258 }
1259
1260 return skip;
1261}
1262
1263// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001264static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001265 bool skip = false;
1266
1267 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1268
1269 if (spec) {
1270 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001271 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001272 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001273 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 -06001274 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001275 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001276 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001277 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001278 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001279 }
1280 }
1281 }
1282
1283 return skip;
1284}
1285
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001286// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001287static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001288 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001289 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001290 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001291 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001292
1293 // 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 -05001294 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1295 if (type.opcode() == spv::OpTypeRuntimeArray) {
1296 descriptor_count = 0;
1297 type = module->get_def(type.word(2));
1298 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001299 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001300 type = module->get_def(type.word(2));
1301 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001302 if (type.word(2) == spv::StorageClassStorageBuffer) {
1303 is_storage_buffer = true;
1304 }
Chris Forbes47567b72017-06-09 12:09:45 -07001305 type = module->get_def(type.word(3));
1306 }
1307 }
1308
1309 switch (type.opcode()) {
1310 case spv::OpTypeStruct: {
1311 for (auto insn : *module) {
1312 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1313 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001314 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001315 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1316 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1317 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001318 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001319 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1320 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1321 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1322 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001323 }
Chris Forbes47567b72017-06-09 12:09:45 -07001324 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001325 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1326 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1327 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001328 }
1329 }
1330 }
1331
1332 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001333 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001334 }
1335
1336 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001337 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1338 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1339 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001340
Chris Forbes73c00bf2018-06-22 16:28:06 -07001341 case spv::OpTypeSampledImage: {
1342 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1343 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1344 auto image_type = module->get_def(type.word(2));
1345 auto dim = image_type.word(3);
1346 auto sampled = image_type.word(7);
1347 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001348 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1349 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001350 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001351 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001352 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1353 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001354
1355 case spv::OpTypeImage: {
1356 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1357 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1358 auto dim = type.word(3);
1359 auto sampled = type.word(7);
1360
1361 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001362 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1363 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001364 } else if (dim == spv::DimBuffer) {
1365 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001366 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
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_TEXEL_BUFFER);
1370 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001371 }
1372 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001373 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1374 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1375 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001376 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001377 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1378 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001379 }
1380 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001381 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001382 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001383 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001384
1385 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1386 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001387 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001388 }
1389}
1390
Jeff Bolze54ae892018-09-08 12:16:29 -05001391static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001392 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001393 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1394 if (ss.tellp()) ss << ", ";
1395 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001396 }
1397 return ss.str();
1398}
1399
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001400static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001401 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001402 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 -06001403 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001404 return true;
1405 }
1406 }
1407
1408 return false;
1409}
1410
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001411static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001412 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001413 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 -06001414 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001415 extension_name)) {
1416 return true;
1417 }
1418 }
1419
1420 return false;
1421}
1422
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001423bool CoreChecks::ValidateShaderCapabilities(shader_module const *src, VkShaderStageFlagBits stage, bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001424 bool skip = false;
1425
Mark Lobodzinski60e79032019-03-07 10:22:31 -07001426 auto const &features = GetEnabledFeatures();
1427 auto const &extensions = GetDeviceExtensions();
Chris Forbes47567b72017-06-09 12:09:45 -07001428
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001429 struct FeaturePointer {
1430 // Callable object to test if this feature is enabled in the given aggregate feature struct
1431 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1432
1433 // Test if feature pointer is populated
1434 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1435
1436 // Default and nullptr constructor to create an empty FeaturePointer
1437 FeaturePointer() : IsEnabled(nullptr) {}
1438 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1439
1440 // Constructors to populate FeaturePointer based on given pointer to member
1441 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1442 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1443 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1444 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1445 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1446 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001447 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1448 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001449 FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
1450 : IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
Tobias Hector6a0ece72018-12-10 12:24:05 +00001451 FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
1452 : IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001453 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1454 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001455 };
1456
Chris Forbes47567b72017-06-09 12:09:45 -07001457 struct CapabilityInfo {
1458 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001459 FeaturePointer feature;
1460 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001461 };
1462
Chris Forbes47567b72017-06-09 12:09:45 -07001463 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001464 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001465 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1466 // feature bits.
1467 {spv::CapabilityMatrix, {nullptr}},
1468 {spv::CapabilityShader, {nullptr}},
1469 {spv::CapabilityInputAttachment, {nullptr}},
1470 {spv::CapabilitySampled1D, {nullptr}},
1471 {spv::CapabilityImage1D, {nullptr}},
1472 {spv::CapabilitySampledBuffer, {nullptr}},
1473 {spv::CapabilityImageQuery, {nullptr}},
1474 {spv::CapabilityDerivativeControl, {nullptr}},
1475
1476 // Capabilities that are optionally supported, but require a feature to
1477 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001478 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1479 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1480 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1481 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1482 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1483 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1484 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1485 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1486 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1487 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1488 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1489 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1490 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1491 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1492 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1493 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1494 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1495 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1496 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1497 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1498 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1499 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1500 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1501 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1502 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001503
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001504 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1505 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1506 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1507 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1508 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1509 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1510 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1511 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1512 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1513 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1514 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1515 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001516
1517 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001518 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1519 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1520 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1521 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1522 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1523 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1524 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1525 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
aqnuep7033c702018-09-11 18:03:29 +02001526 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001527
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001528 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1529 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1530 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001531
1532 {spv::CapabilityTransformFeedback , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001533 {spv::CapabilityGeometryStreams , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
1534
1535 {spv::CapabilityFloat16 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1536 {spv::CapabilityInt8 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001537
1538 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Chris Forbes47567b72017-06-09 12:09:45 -07001539 };
1540 // clang-format on
1541
1542 for (auto insn : *src) {
1543 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001544 size_t n = capabilities.count(insn.word(1));
1545 if (1 == n) { // key occurs exactly once
1546 auto it = capabilities.find(insn.word(1));
1547 if (it != capabilities.end()) {
1548 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001549 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001550 }
1551 if (it->second.extension) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001552 skip |= RequireExtension(report_data, extensions->*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001553 }
Chris Forbes47567b72017-06-09 12:09:45 -07001554 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001555 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1556 bool needs_feature = false, has_feature = false;
1557 bool needs_ext = false, has_ext = false;
1558 std::string feature_names = "(one of) [ ";
1559 std::string extension_names = feature_names;
1560 auto caps = capabilities.equal_range(insn.word(1));
1561 for (auto it = caps.first; it != caps.second; ++it) {
1562 if (it->second.feature) {
1563 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001564 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001565 feature_names += it->second.name;
1566 feature_names += " ";
1567 }
1568 if (it->second.extension) {
1569 needs_ext = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001570 has_ext = has_ext || extensions->*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001571 extension_names += it->second.name;
1572 extension_names += " ";
1573 }
1574 }
1575 if (needs_feature) {
1576 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001577 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001578 }
1579 if (needs_ext) {
1580 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001581 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001582 }
1583 }
1584 }
1585 }
1586
Chris Forbes349b3132018-03-07 11:38:08 -08001587 if (has_writable_descriptor) {
1588 switch (stage) {
1589 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001590 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1591 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1592 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1593 case VK_SHADER_STAGE_MISS_BIT_NV:
1594 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1595 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1596 case VK_SHADER_STAGE_TASK_BIT_NV:
1597 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001598 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001599 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001600 break;
1601 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001602 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001603 break;
1604 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001605 skip |=
1606 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001607 break;
1608 }
1609 }
1610
Chris Forbes47567b72017-06-09 12:09:45 -07001611 return skip;
1612}
1613
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001614static bool VariableIsBuiltIn(shader_module const *src, const uint32_t ID, std::vector<uint32_t> const &builtInBlockIDs,
1615 std::vector<uint32_t> const &builtInIDs) {
1616 auto insn = src->get_def(ID);
1617
1618 switch (insn.opcode()) {
1619 case spv::OpVariable: {
1620 // First check if the variable is a "pure" built-in type, e.g. gl_ViewportIndex
1621 uint32_t ID = insn.word(2);
1622 for (auto builtInID : builtInIDs) {
1623 if (ID == builtInID) {
1624 return true;
1625 }
1626 }
1627
1628 VariableIsBuiltIn(src, insn.word(1), builtInBlockIDs, builtInIDs);
1629 break;
1630 }
1631 case spv::OpTypePointer:
1632 VariableIsBuiltIn(src, insn.word(3), builtInBlockIDs, builtInIDs);
1633 break;
1634 case spv::OpTypeArray:
1635 VariableIsBuiltIn(src, insn.word(2), builtInBlockIDs, builtInIDs);
1636 break;
1637 case spv::OpTypeStruct: {
1638 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
1639 for (auto builtInBlockID : builtInBlockIDs) {
1640 if (ID == builtInBlockID) {
1641 return true;
1642 }
1643 }
1644 return false;
1645 }
1646 default:
1647 return false;
1648 }
1649
1650 return false;
1651}
1652
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001653bool CoreChecks::ValidateShaderStageInputOutputLimits(shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1654 PIPELINE_STATE *pipeline) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001655 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1656 pStage->stage == VK_SHADER_STAGE_ALL) {
1657 return false;
1658 }
1659
1660 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001661 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001662
1663 std::vector<uint32_t> builtInBlockIDs;
1664 std::vector<uint32_t> builtInIDs;
1665 struct Variable {
1666 uint32_t baseTypePtrID;
1667 uint32_t ID;
1668 uint32_t storageClass;
1669 };
1670 std::vector<Variable> variables;
1671
1672 for (auto insn : *src) {
1673 switch (insn.opcode()) {
1674 // Find all built-in member decorations
1675 case spv::OpMemberDecorate:
1676 if (insn.word(3) == spv::DecorationBuiltIn) {
1677 builtInBlockIDs.push_back(insn.word(1));
1678 }
1679 break;
1680 // Find all built-in decorations
1681 case spv::OpDecorate:
1682 switch (insn.word(2)) {
1683 case spv::DecorationBlock: {
1684 uint32_t blockID = insn.word(1);
1685 for (auto builtInBlockID : builtInBlockIDs) {
1686 // Check if one of the members of the block are built-in -> the block is built-in
1687 if (blockID == builtInBlockID) {
1688 builtInIDs.push_back(blockID);
1689 break;
1690 }
1691 }
1692 break;
1693 }
1694 case spv::DecorationBuiltIn:
1695 builtInIDs.push_back(insn.word(1));
1696 break;
1697 default:
1698 break;
1699 }
1700 break;
1701 // Find all input and output variables
1702 case spv::OpVariable: {
1703 Variable var = {};
1704 var.storageClass = insn.word(3);
1705 if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
1706 var.baseTypePtrID = insn.word(1);
1707 var.ID = insn.word(2);
1708 variables.push_back(var);
1709 }
1710 break;
1711 }
1712 default:
1713 break;
1714 }
1715 }
1716
1717 uint32_t numCompIn = 0, numCompOut = 0;
1718 for (auto &var : variables) {
1719 // Check the variable's ID
1720 if (VariableIsBuiltIn(src, var.ID, builtInBlockIDs, builtInIDs)) {
1721 continue;
1722 }
1723 // Check the variable's type's ID - e.g. gl_PerVertex is made of basic types, not built-in types
1724 if (VariableIsBuiltIn(src, src->get_def(var.baseTypePtrID).word(3), builtInBlockIDs, builtInIDs)) {
1725 continue;
1726 }
1727
1728 if (var.storageClass == spv::StorageClassInput) {
1729 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1730 } else { // var.storageClass == spv::StorageClassOutput
1731 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1732 }
1733 }
1734
1735 switch (pStage->stage) {
1736 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001737 if (numCompOut > limits.maxVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001738 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1739 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1740 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1741 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
1742 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001743 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001744 }
1745 break;
1746
1747 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001748 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001749 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1750 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1751 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1752 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
1753 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001754 limits.maxTessellationControlPerVertexInputComponents,
1755 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001756 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001757 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001758 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1759 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1760 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1761 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
1762 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001763 limits.maxTessellationControlPerVertexOutputComponents,
1764 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001765 }
1766 break;
1767
1768 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001769 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001770 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1771 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1772 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1773 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
1774 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001775 limits.maxTessellationEvaluationInputComponents,
1776 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001777 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001778 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001779 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1780 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1781 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1782 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
1783 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001784 limits.maxTessellationEvaluationOutputComponents,
1785 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001786 }
1787 break;
1788
1789 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001790 if (numCompIn > limits.maxGeometryInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001791 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1792 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1793 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1794 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
1795 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001796 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001797 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001798 if (numCompOut > limits.maxGeometryOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001799 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1800 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1801 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1802 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
1803 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001804 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001805 }
1806 break;
1807
1808 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001809 if (numCompIn > limits.maxFragmentInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001810 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1811 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1812 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
1813 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
1814 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001815 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001816 }
1817 break;
1818
Jeff Bolz148d94e2018-12-13 21:25:56 -06001819 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1820 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1821 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1822 case VK_SHADER_STAGE_MISS_BIT_NV:
1823 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1824 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1825 case VK_SHADER_STAGE_TASK_BIT_NV:
1826 case VK_SHADER_STAGE_MESH_BIT_NV:
1827 break;
1828
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001829 default:
1830 assert(false); // This should never happen
1831 }
1832 return skip;
1833}
1834
Jeff Bolze4356752019-03-07 11:23:46 -06001835// copy the specialization constant value into buf, if it is present
1836void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
1837 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
1838
1839 if (spec && spec_id < spec->mapEntryCount) {
1840 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
1841 }
1842}
1843
1844// Fill in value with the constant or specialization constant value, if available.
1845// Returns true if the value has been accurately filled out.
1846static bool GetIntConstantValue(spirv_inst_iter insn, shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1847 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
1848 auto type_id = src->get_def(insn.word(1));
1849 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
1850 return false;
1851 }
1852 switch (insn.opcode()) {
1853 case spv::OpSpecConstant:
1854 *value = insn.word(3);
1855 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
1856 return true;
1857 case spv::OpConstant:
1858 *value = insn.word(3);
1859 return true;
1860 default:
1861 return false;
1862 }
1863}
1864
1865// Map SPIR-V type to VK_COMPONENT_TYPE enum
1866VkComponentTypeNV GetComponentType(spirv_inst_iter insn, shader_module const *src) {
1867 switch (insn.opcode()) {
1868 case spv::OpTypeInt:
1869 switch (insn.word(2)) {
1870 case 8:
1871 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
1872 case 16:
1873 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
1874 case 32:
1875 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
1876 case 64:
1877 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
1878 default:
1879 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1880 }
1881 case spv::OpTypeFloat:
1882 switch (insn.word(2)) {
1883 case 16:
1884 return VK_COMPONENT_TYPE_FLOAT16_NV;
1885 case 32:
1886 return VK_COMPONENT_TYPE_FLOAT32_NV;
1887 case 64:
1888 return VK_COMPONENT_TYPE_FLOAT64_NV;
1889 default:
1890 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1891 }
1892 default:
1893 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1894 }
1895}
1896
1897// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
1898// in SPIRV-Tools (e.g. due to specialization constant usage).
1899bool CoreChecks::ValidateCooperativeMatrix(shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1900 PIPELINE_STATE *pipeline) {
1901 bool skip = false;
1902
1903 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
1904 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
1905 // Map SPIR-V result ID to the ID of its type.
1906 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
1907
1908 struct CoopMatType {
1909 uint32_t scope, rows, cols;
1910 VkComponentTypeNV component_type;
1911 bool all_constant;
1912
1913 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
1914
1915 void Init(uint32_t id, shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1916 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
1917 spirv_inst_iter insn = src->get_def(id);
1918 uint32_t component_type_id = insn.word(2);
1919 uint32_t scope_id = insn.word(3);
1920 uint32_t rows_id = insn.word(4);
1921 uint32_t cols_id = insn.word(5);
1922 auto component_type_iter = src->get_def(component_type_id);
1923 auto scope_iter = src->get_def(scope_id);
1924 auto rows_iter = src->get_def(rows_id);
1925 auto cols_iter = src->get_def(cols_id);
1926
1927 all_constant = true;
1928 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
1929 all_constant = false;
1930 }
1931 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
1932 all_constant = false;
1933 }
1934 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
1935 all_constant = false;
1936 }
1937 component_type = GetComponentType(component_type_iter, src);
1938 }
1939 };
1940
1941 bool seen_coopmat_capability = false;
1942
1943 for (auto insn : *src) {
1944 // Whitelist instructions whose result can be a cooperative matrix type, and
1945 // keep track of their types. It would be nice if SPIRV-Headers generated code
1946 // to identify which instructions have a result type and result id. Lacking that,
1947 // this whitelist is based on the set of instructions that
1948 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
1949 switch (insn.opcode()) {
1950 case spv::OpLoad:
1951 case spv::OpCooperativeMatrixLoadNV:
1952 case spv::OpCooperativeMatrixMulAddNV:
1953 case spv::OpSNegate:
1954 case spv::OpFNegate:
1955 case spv::OpIAdd:
1956 case spv::OpFAdd:
1957 case spv::OpISub:
1958 case spv::OpFSub:
1959 case spv::OpFDiv:
1960 case spv::OpSDiv:
1961 case spv::OpUDiv:
1962 case spv::OpMatrixTimesScalar:
1963 case spv::OpConstantComposite:
1964 case spv::OpCompositeConstruct:
1965 case spv::OpConvertFToU:
1966 case spv::OpConvertFToS:
1967 case spv::OpConvertSToF:
1968 case spv::OpConvertUToF:
1969 case spv::OpUConvert:
1970 case spv::OpSConvert:
1971 case spv::OpFConvert:
1972 id_to_type_id[insn.word(2)] = insn.word(1);
1973 break;
1974 default:
1975 break;
1976 }
1977
1978 switch (insn.opcode()) {
1979 case spv::OpDecorate:
1980 if (insn.word(2) == spv::DecorationSpecId) {
1981 id_to_spec_id[insn.word(1)] = insn.word(3);
1982 }
1983 break;
1984 case spv::OpCapability:
1985 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
1986 seen_coopmat_capability = true;
1987
1988 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
1989 skip |=
1990 log_msg(GetReportData(), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1991 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixSupportedStages,
1992 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
1993 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
1994 }
1995 }
1996 break;
1997 case spv::OpMemoryModel:
1998 // If the capability isn't enabled, don't bother with the rest of this function.
1999 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2000 if (!seen_coopmat_capability) {
2001 return skip;
2002 }
2003 break;
2004 case spv::OpTypeCooperativeMatrixNV: {
2005 CoopMatType M;
2006 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2007
2008 if (M.all_constant) {
2009 // Validate that the type parameters are all supported for one of the
2010 // operands of a cooperative matrix property.
2011 bool valid = false;
2012 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2013 if (cooperative_matrix_properties[i].AType == M.component_type &&
2014 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2015 cooperative_matrix_properties[i].scope == M.scope) {
2016 valid = true;
2017 break;
2018 }
2019 if (cooperative_matrix_properties[i].BType == M.component_type &&
2020 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2021 cooperative_matrix_properties[i].scope == M.scope) {
2022 valid = true;
2023 break;
2024 }
2025 if (cooperative_matrix_properties[i].CType == M.component_type &&
2026 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2027 cooperative_matrix_properties[i].scope == M.scope) {
2028 valid = true;
2029 break;
2030 }
2031 if (cooperative_matrix_properties[i].DType == M.component_type &&
2032 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2033 cooperative_matrix_properties[i].scope == M.scope) {
2034 valid = true;
2035 break;
2036 }
2037 }
2038 if (!valid) {
2039 skip |= log_msg(GetReportData(), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
2040 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixType,
2041 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2042 insn.word(1));
2043 }
2044 }
2045 break;
2046 }
2047 case spv::OpCooperativeMatrixMulAddNV: {
2048 CoopMatType A, B, C, D;
2049 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2050 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2051 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2052 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
2053 assert(!"Couldn't find type of matrix");
2054 break;
2055 }
2056 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2057 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2058 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2059 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2060
2061 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2062 // Validate that the type parameters are all supported for the same
2063 // cooperative matrix property.
2064 bool valid = false;
2065 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2066 if (cooperative_matrix_properties[i].AType == A.component_type &&
2067 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2068 cooperative_matrix_properties[i].scope == A.scope &&
2069
2070 cooperative_matrix_properties[i].BType == B.component_type &&
2071 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2072 cooperative_matrix_properties[i].scope == B.scope &&
2073
2074 cooperative_matrix_properties[i].CType == C.component_type &&
2075 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2076 cooperative_matrix_properties[i].scope == C.scope &&
2077
2078 cooperative_matrix_properties[i].DType == D.component_type &&
2079 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2080 cooperative_matrix_properties[i].scope == D.scope) {
2081 valid = true;
2082 break;
2083 }
2084 }
2085 if (!valid) {
2086 skip |= log_msg(GetReportData(), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
2087 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixMulAdd,
2088 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2089 "VkCooperativeMatrixPropertiesNV",
2090 insn.word(2));
2091 }
2092 }
2093 break;
2094 }
2095 default:
2096 break;
2097 }
2098 }
2099
2100 return skip;
2101}
2102
2103static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07002104 auto type = module->get_def(type_id);
2105
2106 while (true) {
2107 switch (type.opcode()) {
2108 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07002109 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07002110 case spv::OpTypeSampledImage:
2111 type = module->get_def(type.word(2));
2112 break;
2113 case spv::OpTypePointer:
2114 type = module->get_def(type.word(3));
2115 break;
2116 case spv::OpTypeImage: {
2117 auto dim = type.word(3);
2118 auto arrayed = type.word(5);
2119 auto msaa = type.word(6);
2120
Chris Forbes74ba2232018-08-27 15:19:27 -07002121 uint32_t bits = 0;
2122 switch (GetFundamentalType(module, type.word(2))) {
2123 case FORMAT_TYPE_FLOAT:
2124 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
2125 break;
2126 case FORMAT_TYPE_UINT:
2127 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
2128 break;
2129 case FORMAT_TYPE_SINT:
2130 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
2131 break;
2132 default:
2133 break;
2134 }
2135
Chris Forbes47567b72017-06-09 12:09:45 -07002136 switch (dim) {
2137 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002138 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
2139 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002140 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002141 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2142 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
2143 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002144 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002145 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
2146 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002147 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07002148 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
2149 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002150 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07002151 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2152 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002153 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07002154 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002155 }
2156 }
2157 default:
2158 return 0;
2159 }
2160 }
2161}
2162
2163// For given pipelineLayout verify that the set_layout_node at slot.first
2164// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002165static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
2166 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07002167 if (!pipelineLayout) return nullptr;
2168
2169 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
2170
2171 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
2172}
2173
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002174static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05002175 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07002176 bool is_point_mode = false;
2177
2178 for (auto insn : *src) {
2179 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2180 switch (insn.word(2)) {
2181 case spv::ExecutionModePointMode:
2182 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
2183 is_point_mode = true;
2184 break;
2185
2186 case spv::ExecutionModeOutputPoints:
2187 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2188 break;
2189
2190 case spv::ExecutionModeIsolines:
2191 case spv::ExecutionModeOutputLineStrip:
2192 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
2193 break;
2194
2195 case spv::ExecutionModeTriangles:
2196 case spv::ExecutionModeQuads:
2197 case spv::ExecutionModeOutputTriangleStrip:
2198 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
2199 break;
2200 }
2201 }
2202 }
2203
2204 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2205}
2206
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002207// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
2208// o If there is only a vertex shader : gl_PointSize must be written when using points
2209// o If there is a geometry or tessellation shader:
2210// - If shaderTessellationAndGeometryPointSize feature is enabled:
2211// * gl_PointSize must be written in the final geometry stage
2212// - If shaderTessellationAndGeometryPointSize feature is disabled:
2213// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002214bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, shader_module const *src, spirv_inst_iter entrypoint,
2215 VkShaderStageFlagBits stage) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002216 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2217 return false;
2218 }
2219
2220 bool pointsize_written = false;
2221 bool skip = false;
2222
2223 // Search for PointSize built-in decorations
2224 std::vector<uint32_t> pointsize_builtin_offsets;
2225 spirv_inst_iter insn = entrypoint;
2226 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
2227 if (insn.opcode() == spv::OpMemberDecorate) {
2228 if (insn.word(3) == spv::DecorationBuiltIn) {
2229 if (insn.word(4) == spv::BuiltInPointSize) {
2230 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2231 }
2232 }
2233 } else if (insn.opcode() == spv::OpDecorate) {
2234 if (insn.word(2) == spv::DecorationBuiltIn) {
2235 if (insn.word(3) == spv::BuiltInPointSize) {
2236 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2237 }
2238 }
2239 }
2240
2241 insn++;
2242 }
2243
2244 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002245 !GetEnabledFeatures()->core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002246 if (pointsize_written) {
Mark Lobodzinski96d53422019-03-07 11:44:42 -07002247 skip |= log_msg(GetReportData(), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002248 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
2249 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
2250 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
2251 }
2252 } else if (!pointsize_written) {
2253 skip |=
Mark Lobodzinski96d53422019-03-07 11:44:42 -07002254 log_msg(GetReportData(), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002255 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
2256 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
2257 string_VkShaderStageFlagBits(stage));
2258 }
2259 return skip;
2260}
2261
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002262bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
2263 shader_module const **out_module, spirv_inst_iter *out_entrypoint,
2264 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07002265 bool skip = false;
Mark Lobodzinski9e9da292019-03-06 16:19:55 -07002266 auto module = *out_module = GetShaderModuleState(pStage->module);
Mark Lobodzinski96d53422019-03-07 11:44:42 -07002267 auto report_data = GetReportData();
Chris Forbes47567b72017-06-09 12:09:45 -07002268
2269 if (!module->has_valid_spirv) return false;
2270
2271 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002272 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07002273 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002274 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 -06002275 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2276 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002277 return true; // no point continuing beyond here, any analysis is just going to be garbage.
2278 }
2279 }
2280
Chris Forbes47567b72017-06-09 12:09:45 -07002281 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002282 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
2283 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002284
2285 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08002286 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002287 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07002288
Chris Forbes349b3132018-03-07 11:38:08 -08002289 // Validate shader capabilities against enabled device features
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002290 skip |= ValidateShaderCapabilities(module, pStage->stage, has_writable_descriptor);
2291 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002292 skip |= ValidateSpecializationOffsets(report_data, pStage);
2293 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
2294 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002295 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002296 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002297 }
Jeff Bolze4356752019-03-07 11:23:46 -06002298 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002299
2300 // Validate descriptor use
2301 for (auto use : descriptor_uses) {
2302 // While validating shaders capture which slots are used by the pipeline
2303 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002304 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07002305
2306 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002307 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002308 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002309 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002310
2311 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002312 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 -06002313 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002314 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05002315 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002316 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002317 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 -06002318 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002319 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
2320 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05002321 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002322 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 -06002323 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002324 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05002325 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07002326 string_VkDescriptorType(binding->descriptorType));
2327 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002328 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 -06002329 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002330 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
2331 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07002332 }
2333 }
2334
2335 // Validate use of input attachments against subpass structure
2336 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002337 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07002338
Petr Krause91f7a12017-12-14 20:57:36 +01002339 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002340 auto subpass = pipeline->graphicsPipelineCI.subpass;
2341
2342 for (auto use : input_attachment_uses) {
2343 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
2344 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07002345 ? input_attachments[use.first].attachment
2346 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07002347
2348 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002349 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 -06002350 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07002351 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002352 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002353 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002354 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 -06002355 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002356 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002357 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002358 }
2359 }
2360 }
2361
2362 return skip;
2363}
2364
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002365static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
2366 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
2367 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
2368 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07002369 bool skip = false;
2370
2371 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002372 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
2373 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07002374
2375 auto a_it = outputs.begin();
2376 auto b_it = inputs.begin();
2377
2378 // Maps sorted by key (location); walk them together to find mismatches
2379 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
2380 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
2381 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
2382 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
2383 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
2384
2385 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06002386 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 -06002387 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06002388 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
2389 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002390 a_it++;
2391 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06002392 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 -06002393 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06002394 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
2395 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002396 b_it++;
2397 } else {
2398 // subtleties of arrayed interfaces:
2399 // - if is_patch, then the member is not arrayed, even though the interface may be.
2400 // - if is_block_member, then the extra array level of an arrayed interface is not
2401 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002402 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
2403 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
2404 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06002405 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 -06002406 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06002407 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002408 DescribeType(producer, a_it->second.type_id).c_str(),
2409 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002410 }
2411 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06002412 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 -06002413 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002414 "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 -07002415 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
2416 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
2417 }
2418 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06002419 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 -06002420 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002421 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
2422 a_first.second, producer_stage->name, consumer_stage->name);
2423 }
2424 a_it++;
2425 b_it++;
2426 }
2427 }
2428
2429 return skip;
2430}
2431
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002432static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
2433 uint32_t stage_mask = 0;
2434 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2435 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2436 stage_mask |= pCreateInfo->pStages[i].stage;
2437 }
2438 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05002439 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
2440 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
2441 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002442 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
2443 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
2444 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2445 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
2446 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002447 }
2448 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002449 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002450}
2451
Chris Forbes47567b72017-06-09 12:09:45 -07002452// Validate that the shaders used by the given pipeline and store the active_slots
2453// that are actually used by the pipeline into pPipeline->active_slots
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002454bool CoreChecks::ValidateAndCapturePipelineShaderState(PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002455 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002456 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2457 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Mark Lobodzinski96d53422019-03-07 11:44:42 -07002458 auto report_data = GetReportData();
Chris Forbes47567b72017-06-09 12:09:45 -07002459
Jeff Bolz7e35c392018-09-04 15:30:41 -05002460 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002461 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002462 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002463 memset(entrypoints, 0, sizeof(entrypoints));
2464 bool skip = false;
2465
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002466 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
2467
Chris Forbes47567b72017-06-09 12:09:45 -07002468 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2469 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002470 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002471 skip |= ValidatePipelineShaderStage(pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002472 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002473 }
2474
2475 // if the shader stages are no good individually, cross-stage validation is pointless.
2476 if (skip) return true;
2477
2478 auto vi = pCreateInfo->pVertexInputState;
2479
2480 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002481 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07002482 }
2483
2484 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002485 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07002486 }
2487
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002488 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2489 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002490
2491 while (!shaders[producer] && producer != fragment_stage) {
2492 producer++;
2493 consumer++;
2494 }
2495
2496 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
2497 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002498 if (shaders[consumer]) {
2499 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002500 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
2501 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
2502 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002503 }
Chris Forbes47567b72017-06-09 12:09:45 -07002504
2505 producer = consumer;
2506 }
2507 }
2508
2509 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002510 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
2511 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07002512 }
2513
2514 return skip;
2515}
2516
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002517bool CoreChecks::ValidateComputePipeline(PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002518 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002519
2520 shader_module const *module;
2521 spirv_inst_iter entrypoint;
2522
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002523 return ValidatePipelineShaderStage(&pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07002524}
Chris Forbes4ae55b32017-06-09 14:42:56 -07002525
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002526bool CoreChecks::ValidateRayTracingPipelineNV(PIPELINE_STATE *pipeline) {
Jeff Bolzfbe51582018-09-13 10:01:35 -05002527 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
2528
2529 shader_module const *module;
2530 spirv_inst_iter entrypoint;
2531
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002532 return ValidatePipelineShaderStage(pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
Jeff Bolzfbe51582018-09-13 10:01:35 -05002533}
2534
Dave Houltona9df0ce2018-02-07 10:51:23 -07002535uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07002536
Dave Houltona9df0ce2018-02-07 10:51:23 -07002537static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07002538 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
2539 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
2540 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
2541 }
2542
2543 return nullptr;
2544}
2545
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002546bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2547 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002548 bool skip = false;
2549 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002550
Mark Lobodzinski44da62c2019-03-07 10:50:59 -07002551 if (GetDisables()->shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002552 return false;
2553 }
2554
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002555 auto have_glsl_shader = GetDeviceExtensions()->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002556
2557 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002558 skip |= 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 -06002559 "VUID-VkShaderModuleCreateInfo-pCode-01376",
2560 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
2561 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002562 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07002563 auto cache = GetValidationCacheInfo(pCreateInfo);
2564 uint32_t hash = 0;
2565 if (cache) {
2566 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002567 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07002568 }
2569
Chris Forbes4ae55b32017-06-09 14:42:56 -07002570 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06002571 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Mark Lobodzinski96d5c6e2019-03-07 11:28:21 -07002572 if (GetApiVersion() >= VK_API_VERSION_1_1) {
Dave Houlton0ea2d012018-06-21 14:00:26 -06002573 spirv_environment = SPV_ENV_VULKAN_1_1;
2574 }
2575 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002576 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07002577 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06002578 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002579 if (GetDeviceExtensions()->vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06002580 spvValidatorOptionsSetRelaxBlockLayout(options, true);
2581 }
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002582 if (GetDeviceExtensions()->vk_ext_scalar_block_layout &&
2583 GetEnabledFeatures()->scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00002584 spvValidatorOptionsSetScalarBlockLayout(options, true);
2585 }
Karl Schultzfda1b382018-08-08 18:56:11 -06002586 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002587 if (spv_valid != SPV_SUCCESS) {
2588 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002589 skip |=
2590 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
2591 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
2592 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07002593 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002594 } else {
2595 if (cache) {
2596 cache->Insert(hash);
2597 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002598 }
2599
Karl Schultzfda1b382018-08-08 18:56:11 -06002600 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002601 spvDiagnosticDestroy(diag);
2602 spvContextDestroy(ctx);
2603 }
2604
Chris Forbes4ae55b32017-06-09 14:42:56 -07002605 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07002606}
2607
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002608void CoreChecks::PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2609 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
2610 void *csm_state_data) {
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07002611 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinski44da62c2019-03-07 10:50:59 -07002612 if (GetEnables()->gpu_validation) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07002613 GpuPreCallCreateShaderModule(pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
Mark Lobodzinski01734072019-02-13 17:39:15 -07002614 &csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
2615 }
2616}
2617
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002618void CoreChecks::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2619 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
2620 VkResult result, void *csm_state_data) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07002621 if (VK_SUCCESS != result) return;
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07002622 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002623
Mark Lobodzinski96d5c6e2019-03-07 11:28:21 -07002624 spv_target_env spirv_environment = ((GetApiVersion() >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002625 bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
2626 std::unique_ptr<shader_module> new_shader_module(
2627 is_spirv ? new shader_module(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
2628 : new shader_module());
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002629 shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002630}