blob: 38c336fa3ba41ef135f46fdca8d0d8181d7123ce [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
Petr Kraus25810d02019-08-27 17:41:15 +020022#include "shader_validation.h"
23
Chris Forbes47567b72017-06-09 12:09:45 -070024#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020025#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020026#include <cinttypes>
27#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070028#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020029#include <string>
30#include <unordered_map>
31#include <vector>
32
Chris Forbes47567b72017-06-09 12:09:45 -070033#include <SPIRV/spirv.hpp>
34#include "vk_loader_platform.h"
35#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070036#include "vk_layer_data.h"
37#include "vk_layer_extension_utils.h"
38#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070039#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020041
Chris Forbes4ae55b32017-06-09 14:42:56 -070042#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070043#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070044
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080045void decoration_set::add(uint32_t decoration, uint32_t value) {
46 switch (decoration) {
47 case spv::DecorationLocation:
48 flags |= location_bit;
49 location = value;
50 break;
51 case spv::DecorationPatch:
52 flags |= patch_bit;
53 break;
54 case spv::DecorationRelaxedPrecision:
55 flags |= relaxed_precision_bit;
56 break;
57 case spv::DecorationBlock:
58 flags |= block_bit;
59 break;
60 case spv::DecorationBufferBlock:
61 flags |= buffer_block_bit;
62 break;
63 case spv::DecorationComponent:
64 flags |= component_bit;
65 component = value;
66 break;
67 case spv::DecorationInputAttachmentIndex:
68 flags |= input_attachment_index_bit;
69 input_attachment_index = value;
70 break;
71 case spv::DecorationDescriptorSet:
72 flags |= descriptor_set_bit;
73 descriptor_set = value;
74 break;
75 case spv::DecorationBinding:
76 flags |= binding_bit;
77 binding = value;
78 break;
79 case spv::DecorationNonWritable:
80 flags |= nonwritable_bit;
81 break;
82 case spv::DecorationBuiltIn:
83 flags |= builtin_bit;
84 builtin = value;
85 break;
86 }
87}
88
Chris Forbes47567b72017-06-09 12:09:45 -070089enum FORMAT_TYPE {
90 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
91 FORMAT_TYPE_SINT = 2,
92 FORMAT_TYPE_UINT = 4,
93};
94
95typedef std::pair<unsigned, unsigned> location_t;
96
Chris Forbes47567b72017-06-09 12:09:45 -070097struct shader_stage_attributes {
98 char const *const name;
99 bool arrayed_input;
100 bool arrayed_output;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 VkShaderStageFlags stage;
Chris Forbes47567b72017-06-09 12:09:45 -0700102};
103
104static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200105 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
106 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
107 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
108 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
109 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700110};
111
John Zulauf14c355b2019-06-27 16:09:37 -0600112unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
113
Chris Forbes47567b72017-06-09 12:09:45 -0700114// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600115void SHADER_MODULE_STATE::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -0700116 for (auto insn : *this) {
117 switch (insn.opcode()) {
118 // Types
119 case spv::OpTypeVoid:
120 case spv::OpTypeBool:
121 case spv::OpTypeInt:
122 case spv::OpTypeFloat:
123 case spv::OpTypeVector:
124 case spv::OpTypeMatrix:
125 case spv::OpTypeImage:
126 case spv::OpTypeSampler:
127 case spv::OpTypeSampledImage:
128 case spv::OpTypeArray:
129 case spv::OpTypeRuntimeArray:
130 case spv::OpTypeStruct:
131 case spv::OpTypeOpaque:
132 case spv::OpTypePointer:
133 case spv::OpTypeFunction:
134 case spv::OpTypeEvent:
135 case spv::OpTypeDeviceEvent:
136 case spv::OpTypeReserveId:
137 case spv::OpTypeQueue:
138 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600139 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600140 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700141 def_index[insn.word(1)] = insn.offset();
142 break;
143
144 // Fixed constants
145 case spv::OpConstantTrue:
146 case spv::OpConstantFalse:
147 case spv::OpConstant:
148 case spv::OpConstantComposite:
149 case spv::OpConstantSampler:
150 case spv::OpConstantNull:
151 def_index[insn.word(2)] = insn.offset();
152 break;
153
154 // Specialization constants
155 case spv::OpSpecConstantTrue:
156 case spv::OpSpecConstantFalse:
157 case spv::OpSpecConstant:
158 case spv::OpSpecConstantComposite:
159 case spv::OpSpecConstantOp:
160 def_index[insn.word(2)] = insn.offset();
161 break;
162
163 // Variables
164 case spv::OpVariable:
165 def_index[insn.word(2)] = insn.offset();
166 break;
167
168 // Functions
169 case spv::OpFunction:
170 def_index[insn.word(2)] = insn.offset();
171 break;
172
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800173 // Decorations
174 case spv::OpDecorate: {
175 auto targetId = insn.word(1);
176 decorations[targetId].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
177 } break;
178 case spv::OpGroupDecorate: {
179 auto const &src = decorations[insn.word(1)];
180 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
181 } break;
182
John Zulauf14c355b2019-06-27 16:09:37 -0600183 // Entry points ... add to the entrypoint table
184 case spv::OpEntryPoint: {
185 // Entry points do not have an id (the id is the function id) and thus need their own table
186 auto entrypoint_name = (char const *)&insn.word(3);
187 auto execution_model = insn.word(1);
188 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
189 entry_points.emplace(entrypoint_name, EntryPoint{insn.offset(), entrypoint_stage});
190 break;
191 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800192
Chris Forbes47567b72017-06-09 12:09:45 -0700193 default:
194 // We don't care about any other defs for now.
195 break;
196 }
197 }
198}
199
Jeff Bolz105d6492018-09-29 15:46:44 -0500200unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
201 switch (mode) {
202 case spv::ExecutionModelVertex:
203 return VK_SHADER_STAGE_VERTEX_BIT;
204 case spv::ExecutionModelTessellationControl:
205 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
206 case spv::ExecutionModelTessellationEvaluation:
207 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
208 case spv::ExecutionModelGeometry:
209 return VK_SHADER_STAGE_GEOMETRY_BIT;
210 case spv::ExecutionModelFragment:
211 return VK_SHADER_STAGE_FRAGMENT_BIT;
212 case spv::ExecutionModelGLCompute:
213 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600214 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700215 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600216 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700217 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600218 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700219 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600220 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700221 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600222 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700223 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600224 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700225 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500226 case spv::ExecutionModelTaskNV:
227 return VK_SHADER_STAGE_TASK_BIT_NV;
228 case spv::ExecutionModelMeshNV:
229 return VK_SHADER_STAGE_MESH_BIT_NV;
230 default:
231 return 0;
232 }
233}
234
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600235static spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600236 auto range = src->entry_points.equal_range(name);
237 for (auto it = range.first; it != range.second; ++it) {
238 if (it->second.stage == stageBits) {
239 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700240 }
241 }
Chris Forbes47567b72017-06-09 12:09:45 -0700242 return src->end();
243}
244
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600245static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700246 switch (sc) {
247 case spv::StorageClassInput:
248 return "input";
249 case spv::StorageClassOutput:
250 return "output";
251 case spv::StorageClassUniformConstant:
252 return "const uniform";
253 case spv::StorageClassUniform:
254 return "uniform";
255 case spv::StorageClassWorkgroup:
256 return "workgroup local";
257 case spv::StorageClassCrossWorkgroup:
258 return "workgroup global";
259 case spv::StorageClassPrivate:
260 return "private global";
261 case spv::StorageClassFunction:
262 return "function";
263 case spv::StorageClassGeneric:
264 return "generic";
265 case spv::StorageClassAtomicCounter:
266 return "atomic counter";
267 case spv::StorageClassImage:
268 return "image";
269 case spv::StorageClassPushConstant:
270 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800271 case spv::StorageClassStorageBuffer:
272 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700273 default:
274 return "unknown";
275 }
276}
277
278// Get the value of an integral constant
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600279unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700280 auto value = src->get_def(id);
281 assert(value != src->end());
282
283 if (value.opcode() != spv::OpConstant) {
284 // TODO: Either ensure that the specialization transform is already performed on a module we're
285 // considering here, OR -- specialize on the fly now.
286 return 1;
287 }
288
289 return value.word(3);
290}
291
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600292static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700293 auto insn = src->get_def(type);
294 assert(insn != src->end());
295
296 switch (insn.opcode()) {
297 case spv::OpTypeBool:
298 ss << "bool";
299 break;
300 case spv::OpTypeInt:
301 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
302 break;
303 case spv::OpTypeFloat:
304 ss << "float" << insn.word(2);
305 break;
306 case spv::OpTypeVector:
307 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600308 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700309 break;
310 case spv::OpTypeMatrix:
311 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600312 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700313 break;
314 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600315 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
316 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700317 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700318 case spv::OpTypeRuntimeArray:
319 ss << "runtime arr[] of ";
320 DescribeTypeInner(ss, src, insn.word(2));
321 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700322 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600323 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
324 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700325 break;
326 case spv::OpTypeStruct: {
327 ss << "struct of (";
328 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600329 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700330 if (i == insn.len() - 1) {
331 ss << ")";
332 } else {
333 ss << ", ";
334 }
335 }
336 break;
337 }
338 case spv::OpTypeSampler:
339 ss << "sampler";
340 break;
341 case spv::OpTypeSampledImage:
342 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600343 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700344 break;
345 case spv::OpTypeImage:
346 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
347 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600348 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500349 ss << "accelerationStruture";
350 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700351 default:
352 ss << "oddtype";
353 break;
354 }
355}
356
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600357static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600359 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700360 return ss.str();
361}
362
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600363static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
365 return type.word(2) < 64;
366}
367
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600368static bool TypesMatch(SHADER_MODULE_STATE const *a, SHADER_MODULE_STATE const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600369 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700370 // Walk two type trees together, and complain about differences
371 auto a_insn = a->get_def(a_type);
372 auto b_insn = b->get_def(b_type);
373 assert(a_insn != a->end());
374 assert(b_insn != b->end());
375
Chris Forbes062f1222018-08-21 15:34:15 -0700376 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
377
Chris Forbes47567b72017-06-09 12:09:45 -0700378 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600379 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700380 }
381
382 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
383 // 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 -0600384 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700385 }
386
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600387 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
388 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700389 }
390
391 if (a_insn.opcode() != b_insn.opcode()) {
392 return false;
393 }
394
395 if (a_insn.opcode() == spv::OpTypePointer) {
396 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600397 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700398 }
399
400 if (a_arrayed || b_arrayed) {
401 // If we havent resolved array-of-verts by here, we're not going to.
402 return false;
403 }
404
405 switch (a_insn.opcode()) {
406 case spv::OpTypeBool:
407 return true;
408 case spv::OpTypeInt:
409 // Match on width, signedness
410 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
411 case spv::OpTypeFloat:
412 // Match on width
413 return a_insn.word(2) == b_insn.word(2);
414 case spv::OpTypeVector:
415 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600416 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
417 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700418 return a_insn.word(3) >= b_insn.word(3);
419 } else {
420 return a_insn.word(3) == b_insn.word(3);
421 }
422 case spv::OpTypeMatrix:
423 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600424 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700425 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700426 case spv::OpTypeArray:
427 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
428 // 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 -0600429 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
430 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700431 case spv::OpTypeStruct:
432 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700433 {
434 if (a_insn.len() != b_insn.len()) {
435 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700436 }
Chris Forbes47567b72017-06-09 12:09:45 -0700437
Dave Houltona9df0ce2018-02-07 10:51:23 -0700438 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600439 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700440 return false;
441 }
442 }
443
444 return true;
445 }
Chris Forbes47567b72017-06-09 12:09:45 -0700446 default:
447 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
448 return false;
449 }
450}
451
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600452static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700453 auto it = map.find(id);
454 if (it == map.end())
455 return def;
456 else
457 return it->second;
458}
459
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600460static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700461 auto insn = src->get_def(type);
462 assert(insn != src->end());
463
464 switch (insn.opcode()) {
465 case spv::OpTypePointer:
466 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
467 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600468 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700469 case spv::OpTypeArray:
470 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600471 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700472 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600473 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700474 }
475 case spv::OpTypeMatrix:
476 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600477 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700478 case spv::OpTypeVector: {
479 auto scalar_type = src->get_def(insn.word(2));
480 auto bit_width =
481 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
482
483 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
484 return (bit_width * insn.word(3) + 127) / 128;
485 }
486 default:
487 // Everything else is just 1.
488 return 1;
489
490 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
491 }
492}
493
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600494static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200495 auto insn = src->get_def(type);
496 assert(insn != src->end());
497
498 switch (insn.opcode()) {
499 case spv::OpTypePointer:
500 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
501 // pointers around.
502 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
503 case spv::OpTypeStruct: {
504 uint32_t sum = 0;
505 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
506 sum += GetComponentsConsumedByType(src, insn.word(i), false);
507 }
508 return sum;
509 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500510 case spv::OpTypeArray:
511 if (strip_array_level) {
512 return GetComponentsConsumedByType(src, insn.word(2), false);
513 } else {
514 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200515 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200516 case spv::OpTypeMatrix:
517 // Num locations is the dimension * element size
518 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
519 case spv::OpTypeVector: {
520 auto scalar_type = src->get_def(insn.word(2));
521 auto bit_width =
522 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
523 // One component is 32-bit
524 return (bit_width * insn.word(3) + 31) / 32;
525 }
526 case spv::OpTypeFloat: {
527 auto bit_width = insn.word(2);
528 return (bit_width + 31) / 32;
529 }
530 case spv::OpTypeInt: {
531 auto bit_width = insn.word(2);
532 return (bit_width + 31) / 32;
533 }
534 case spv::OpConstant:
535 return GetComponentsConsumedByType(src, insn.word(1), false);
536 default:
537 return 0;
538 }
539}
540
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600541static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700542 switch (format) {
543 case VK_FORMAT_R64G64B64A64_SFLOAT:
544 case VK_FORMAT_R64G64B64A64_SINT:
545 case VK_FORMAT_R64G64B64A64_UINT:
546 case VK_FORMAT_R64G64B64_SFLOAT:
547 case VK_FORMAT_R64G64B64_SINT:
548 case VK_FORMAT_R64G64B64_UINT:
549 return 2;
550 default:
551 return 1;
552 }
553}
554
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600555static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700556 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
557 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
558 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
559 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700560 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
561 return FORMAT_TYPE_FLOAT;
562}
563
564// 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 -0700565// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600566static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700567 auto insn = src->get_def(type);
568 assert(insn != src->end());
569
570 switch (insn.opcode()) {
571 case spv::OpTypeInt:
572 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
573 case spv::OpTypeFloat:
574 return FORMAT_TYPE_FLOAT;
575 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700576 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700577 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700578 case spv::OpTypeRuntimeArray:
579 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600580 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700581 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600582 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700583
584 default:
585 return 0;
586 }
587}
588
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600589static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700590 uint32_t bit_pos = uint32_t(u_ffs(stage));
591 return bit_pos - 1;
592}
593
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600594static spirv_inst_iter GetStructType(SHADER_MODULE_STATE const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700595 while (true) {
596 if (def.opcode() == spv::OpTypePointer) {
597 def = src->get_def(def.word(3));
598 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
599 def = src->get_def(def.word(2));
600 is_array_of_verts = false;
601 } else if (def.opcode() == spv::OpTypeStruct) {
602 return def;
603 } else {
604 return src->end();
605 }
606 }
607}
608
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600609static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800610 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
611 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700612 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600613 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800614 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700615 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700616 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700617 }
618
619 std::unordered_map<unsigned, unsigned> member_components;
620 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700621 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700622
623 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
624 for (auto insn : *src) {
625 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
626 unsigned member_index = insn.word(2);
627
628 if (insn.word(3) == spv::DecorationComponent) {
629 unsigned component = insn.word(4);
630 member_components[member_index] = component;
631 }
632
633 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
634 member_relaxed_precision[member_index] = 1;
635 }
Chris Forbesa313d772017-06-13 13:59:41 -0700636
637 if (insn.word(3) == spv::DecorationPatch) {
638 member_patch[member_index] = 1;
639 }
Chris Forbes47567b72017-06-09 12:09:45 -0700640 }
641 }
642
Chris Forbesa313d772017-06-13 13:59:41 -0700643 // TODO: correctly handle location assignment from outside
644
Chris Forbes47567b72017-06-09 12:09:45 -0700645 // Second pass -- produce the output, from Location decorations
646 for (auto insn : *src) {
647 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
648 unsigned member_index = insn.word(2);
649 unsigned member_type_id = type.word(2 + member_index);
650
651 if (insn.word(3) == spv::DecorationLocation) {
652 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600653 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700654 auto component_it = member_components.find(member_index);
655 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
656 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700657 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700658
659 for (unsigned int offset = 0; offset < num_locations; offset++) {
660 interface_var v = {};
661 v.id = id;
662 // TODO: member index in interface_var too?
663 v.type_id = member_type_id;
664 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700665 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700666 v.is_block_member = true;
667 v.is_relaxed_precision = is_relaxed_precision;
668 (*out)[std::make_pair(location + offset, component)] = v;
669 }
670 }
671 }
672 }
Chris Forbesa313d772017-06-13 13:59:41 -0700673
674 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700675}
676
Ari Suonpaa696b3432019-03-11 14:02:57 +0200677static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800678 assert(entrypoint.opcode() == spv::OpEntryPoint);
679
Ari Suonpaa696b3432019-03-11 14:02:57 +0200680 std::vector<uint32_t> interfaces;
681 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
682 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
683 uint32_t word = 3;
684 while (entrypoint.word(word) & 0xff000000u) {
685 ++word;
686 }
687 ++word;
688
689 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
690
691 return interfaces;
692}
693
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600694static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600695 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700696 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
697
Chris Forbes47567b72017-06-09 12:09:45 -0700698 std::map<location_t, interface_var> out;
699
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800700 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
701 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700702 assert(insn != src->end());
703 assert(insn.opcode() == spv::OpVariable);
704
705 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800706 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700707 unsigned id = insn.word(2);
708 unsigned type = insn.word(1);
709
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800710 int location = d.location;
711 int builtin = d.builtin;
712 unsigned component = d.component;
713 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
714 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700715
Dave Houltona9df0ce2018-02-07 10:51:23 -0700716 if (builtin != -1)
717 continue;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800718 else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700719 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
720 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600721 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700722 for (unsigned int offset = 0; offset < num_locations; offset++) {
723 interface_var v = {};
724 v.id = id;
725 v.type_id = type;
726 v.offset = offset;
727 v.is_patch = is_patch;
728 v.is_relaxed_precision = is_relaxed_precision;
729 out[std::make_pair(location + offset, component)] = v;
730 }
Chris Forbes47567b72017-06-09 12:09:45 -0700731 }
732 }
733 }
734
735 return out;
736}
737
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600738static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200739 uint32_t storageClass) {
740 std::vector<uint32_t> variables;
741 std::vector<uint32_t> builtinStructMembers;
742 std::vector<uint32_t> builtinDecorations;
743
744 for (auto insn : *src) {
745 switch (insn.opcode()) {
746 // Find all built-in member decorations
747 case spv::OpMemberDecorate:
748 if (insn.word(3) == spv::DecorationBuiltIn) {
749 builtinStructMembers.push_back(insn.word(1));
750 }
751 break;
752 // Find all built-in decorations
753 case spv::OpDecorate:
754 switch (insn.word(2)) {
755 case spv::DecorationBlock: {
756 uint32_t blockID = insn.word(1);
757 for (auto builtInBlockID : builtinStructMembers) {
758 // Check if one of the members of the block are built-in -> the block is built-in
759 if (blockID == builtInBlockID) {
760 builtinDecorations.push_back(blockID);
761 break;
762 }
763 }
764 break;
765 }
766 case spv::DecorationBuiltIn:
767 builtinDecorations.push_back(insn.word(1));
768 break;
769 default:
770 break;
771 }
772 break;
773 default:
774 break;
775 }
776 }
777
778 // Find all interface variables belonging to the entrypoint and matching the storage class
779 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
780 auto def = src->get_def(id);
781 assert(def != src->end());
782 assert(def.opcode() == spv::OpVariable);
783
784 if (def.word(3) == storageClass) variables.push_back(def.word(1));
785 }
786
787 // Find all members belonging to the builtin block selected
788 std::vector<uint32_t> builtinBlockMembers;
789 for (auto &var : variables) {
790 auto def = src->get_def(src->get_def(var).word(3));
791
792 // It could be an array of IO blocks. The element type should be the struct defining the block contents
793 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
794
795 // Now find all members belonging to the struct defining the IO block
796 if (def.opcode() == spv::OpTypeStruct) {
797 for (auto builtInID : builtinDecorations) {
798 if (builtInID == def.word(1)) {
799 for (int i = 2; i < (int)def.len(); i++)
800 builtinBlockMembers.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
801 // These shouldn't be left after replacing.
802 for (auto insn : *src) {
803 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == builtInID &&
804 insn.word(3) == spv::DecorationBuiltIn) {
805 auto structIndex = insn.word(2);
806 assert(structIndex < builtinBlockMembers.size());
807 builtinBlockMembers[structIndex] = insn.word(4);
808 }
809 }
810 }
811 }
812 }
813 }
814
815 return builtinBlockMembers;
816}
817
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600818static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600819 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700820 std::vector<std::pair<uint32_t, interface_var>> out;
821
822 for (auto insn : *src) {
823 if (insn.opcode() == spv::OpDecorate) {
824 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
825 auto attachment_index = insn.word(3);
826 auto id = insn.word(1);
827
828 if (accessible_ids.count(id)) {
829 auto def = src->get_def(id);
830 assert(def != src->end());
831
832 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600833 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700834 for (unsigned int offset = 0; offset < num_locations; offset++) {
835 interface_var v = {};
836 v.id = id;
837 v.type_id = def.word(1);
838 v.offset = offset;
839 out.emplace_back(attachment_index + offset, v);
840 }
841 }
842 }
843 }
844 }
845 }
846
847 return out;
848}
849
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600850static bool IsWritableDescriptorType(SHADER_MODULE_STATE const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800851 auto type = module->get_def(type_id);
852
853 // 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 -0700854 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
855 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700856 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800857 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700858 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800859 }
860 }
861
862 switch (type.opcode()) {
863 case spv::OpTypeImage: {
864 auto dim = type.word(3);
865 auto sampled = type.word(7);
866 return sampled == 2 && dim != spv::DimSubpassData;
867 }
868
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700869 case spv::OpTypeStruct: {
870 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800871 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800872 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800873 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
874 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700875 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800876 }
877 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700878
879 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
880 // as nonwritable.
881 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
882 }
Chris Forbes8af24522018-03-07 11:37:45 -0800883 }
884
885 return false;
886}
887
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600888static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600889 debug_report_data const *report_data, SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids,
Chris Forbes8af24522018-03-07 11:37:45 -0800890 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700891 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
892
893 for (auto id : accessible_ids) {
894 auto insn = src->get_def(id);
895 assert(insn != src->end());
896
897 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800898 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
899 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800900 auto d = src->get_decorations(insn.word(2));
901 unsigned set = d.descriptor_set;
902 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -0700903
904 interface_var v = {};
905 v.id = insn.word(2);
906 v.type_id = insn.word(1);
907 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800908
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800909 if (!(d.flags & decoration_set::nonwritable_bit) &&
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700910 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800911 *has_writable_descriptor = true;
912 }
Chris Forbes47567b72017-06-09 12:09:45 -0700913 }
914 }
915
916 return out;
917}
918
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600919static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700920 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
921 // be specified only once.
922 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
923 bool skip = false;
924
925 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
926 auto desc = &vi->pVertexBindingDescriptions[i];
927 auto &binding = bindings[desc->binding];
928 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600929 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600930 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 -0600931 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700932 desc->binding);
933 } else {
934 binding = desc;
935 }
936 }
937
938 return skip;
939}
940
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600941static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600942 SHADER_MODULE_STATE const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700943 bool skip = false;
944
Petr Kraus25810d02019-08-27 17:41:15 +0200945 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700946
947 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +0200948 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -0700949 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +0200950 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
951 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
952 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -0700953 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
954 }
955 }
956 }
957
Petr Kraus25810d02019-08-27 17:41:15 +0200958 struct AttribInputPair {
959 const VkVertexInputAttributeDescription *attrib = nullptr;
960 const interface_var *input = nullptr;
961 };
962 std::map<uint32_t, AttribInputPair> location_map;
963 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
964 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -0700965
Petr Kraus25810d02019-08-27 17:41:15 +0200966 for (const auto location_it : location_map) {
967 const auto location = location_it.first;
968 const auto attrib = location_it.second.attrib;
969 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600970
Petr Kraus25810d02019-08-27 17:41:15 +0200971 if (attrib && !input) {
972 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
973 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
974 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
975 } else if (!attrib && input) {
Mark Young4e919b22018-05-21 15:53:59 -0600976 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 -0600977 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Petr Kraus25810d02019-08-27 17:41:15 +0200978 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
979 } else if (attrib && input) {
980 const auto attrib_type = GetFormatType(attrib->format);
981 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700982
983 // Type checking
984 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600985 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 -0600986 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Petr Kraus25810d02019-08-27 17:41:15 +0200987 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
988 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700989 }
Petr Kraus25810d02019-08-27 17:41:15 +0200990 } else { // !attrib && !input
991 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -0700992 }
993 }
994
995 return skip;
996}
997
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600998static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, SHADER_MODULE_STATE const *fs,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600999 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Kraus25810d02019-08-27 17:41:15 +02001000 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001001
Petr Kraus25810d02019-08-27 17:41:15 +02001002 const auto rpci = pipeline->rp_state->createInfo.ptr();
1003
1004 std::map<uint32_t, const VkAttachmentDescription2KHR *> color_attachments;
1005 const auto subpass = rpci->pSubpasses[subpass_index];
1006 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
1007 const uint32_t attachment = subpass.pColorAttachments[i].attachment;
1008 if (attachment != VK_ATTACHMENT_UNUSED && rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
1009 color_attachments[i] = &rpci->pAttachments[attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001010 }
1011 }
1012
Chris Forbes47567b72017-06-09 12:09:45 -07001013 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1014
Petr Kraus25810d02019-08-27 17:41:15 +02001015 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001016
Petr Kraus25810d02019-08-27 17:41:15 +02001017 struct AttachmentOutputPair {
1018 const VkAttachmentDescription2KHR *attachment = nullptr;
1019 const interface_var *output = nullptr;
1020 };
1021 std::map<uint32_t, AttachmentOutputPair> location_map;
1022 for (const auto &attachment_it : color_attachments) location_map[attachment_it.first].attachment = attachment_it.second;
1023 for (const auto &output_it : outputs) location_map[output_it.first.first].output = &output_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001024
Petr Kraus25810d02019-08-27 17:41:15 +02001025 const bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1026 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001027
Petr Kraus25810d02019-08-27 17:41:15 +02001028 for (const auto location_it : location_map) {
1029 const auto location = location_it.first;
1030 const auto attachment = location_it.second.attachment;
1031 const auto output = location_it.second.output;
Chris Forbes47567b72017-06-09 12:09:45 -07001032
Petr Kraus25810d02019-08-27 17:41:15 +02001033 if (attachment && !output) {
1034 if (pipeline->attachments[location].colorWriteMask != 0) {
1035 skip |=
1036 log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1037 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
1038 "Attachment %" PRIu32 " not written by fragment shader; undefined values will be written to attachment",
1039 location);
1040 }
1041 } else if (!attachment && output) {
1042 if (!(alphaToCoverageEnabled && location == 0)) {
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001043 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1044 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Petr Kraus25810d02019-08-27 17:41:15 +02001045 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001046 }
Petr Kraus25810d02019-08-27 17:41:15 +02001047 } else if (attachment && output) {
1048 const auto attachment_type = GetFormatType(attachment->format);
1049 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001050
1051 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001052 if (!(output_type & attachment_type)) {
1053 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1054 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
1055 "Attachment %" PRIu32
1056 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1057 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001058 }
Petr Kraus25810d02019-08-27 17:41:15 +02001059 } else { // !attachment && !output
1060 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001061 }
1062 }
1063
Petr Kraus25810d02019-08-27 17:41:15 +02001064 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
1065 bool locationZeroHasAlpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1066 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001067 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
1068 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1069 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1070 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
1071 }
1072
Chris Forbes47567b72017-06-09 12:09:45 -07001073 return skip;
1074}
1075
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001076// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1077// This function examines instructions in the static call tree for a write to this variable.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001078static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001079 auto type = builtin_instr.opcode();
1080 uint32_t target_id = builtin_instr.word(1);
1081 bool init_complete = false;
1082
1083 if (type == spv::OpMemberDecorate) {
1084 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1085 auto insn = entrypoint;
1086 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1087 switch (insn.opcode()) {
1088 case spv::OpTypePointer:
1089 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1090 target_id = insn.word(1);
1091 }
1092 break;
1093 case spv::OpVariable:
1094 if (insn.word(1) == target_id) {
1095 target_id = insn.word(2);
1096 init_complete = true;
1097 }
1098 break;
1099 }
1100 insn++;
1101 }
1102 }
1103
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001104 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1105
1106 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001107 std::unordered_set<uint32_t> worklist;
1108 worklist.insert(entrypoint.word(2));
1109
1110 // Follow instructions in call graph looking for writes to target
1111 while (!worklist.empty() && !found_write) {
1112 auto id_iter = worklist.begin();
1113 auto id = *id_iter;
1114 worklist.erase(id_iter);
1115
1116 auto insn = src->get_def(id);
1117 if (insn == src->end()) {
1118 continue;
1119 }
1120
1121 if (insn.opcode() == spv::OpFunction) {
1122 // Scan body of function looking for other function calls or items in our ID chain
1123 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1124 switch (insn.opcode()) {
1125 case spv::OpAccessChain:
1126 if (insn.word(3) == target_id) {
1127 if (type == spv::OpMemberDecorate) {
1128 auto value = GetConstantValue(src, insn.word(4));
1129 if (value == builtin_instr.word(2)) {
1130 target_id = insn.word(2);
1131 }
1132 } else {
1133 target_id = insn.word(2);
1134 }
1135 }
1136 break;
1137 case spv::OpStore:
1138 if (insn.word(1) == target_id) {
1139 found_write = true;
1140 }
1141 break;
1142 case spv::OpFunctionCall:
1143 worklist.insert(insn.word(3));
1144 break;
1145 }
1146 }
1147 }
1148 }
1149 return found_write;
1150}
1151
Chris Forbes47567b72017-06-09 12:09:45 -07001152// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1153// important for identifying the set of shader resources actually used by an entrypoint, for example.
1154// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1155// - NOT the shader input/output interfaces.
1156//
1157// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1158// converting parts of this to be generated from the machine-readable spec instead.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001159static std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001160 std::unordered_set<uint32_t> ids;
1161 std::unordered_set<uint32_t> worklist;
1162 worklist.insert(entrypoint.word(2));
1163
1164 while (!worklist.empty()) {
1165 auto id_iter = worklist.begin();
1166 auto id = *id_iter;
1167 worklist.erase(id_iter);
1168
1169 auto insn = src->get_def(id);
1170 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001171 // 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 -07001172 // that we may not care about.
1173 continue;
1174 }
1175
1176 // Try to add to the output set
1177 if (!ids.insert(id).second) {
1178 continue; // If we already saw this id, we don't want to walk it again.
1179 }
1180
1181 switch (insn.opcode()) {
1182 case spv::OpFunction:
1183 // Scan whole body of the function, enlisting anything interesting
1184 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1185 switch (insn.opcode()) {
1186 case spv::OpLoad:
1187 case spv::OpAtomicLoad:
1188 case spv::OpAtomicExchange:
1189 case spv::OpAtomicCompareExchange:
1190 case spv::OpAtomicCompareExchangeWeak:
1191 case spv::OpAtomicIIncrement:
1192 case spv::OpAtomicIDecrement:
1193 case spv::OpAtomicIAdd:
1194 case spv::OpAtomicISub:
1195 case spv::OpAtomicSMin:
1196 case spv::OpAtomicUMin:
1197 case spv::OpAtomicSMax:
1198 case spv::OpAtomicUMax:
1199 case spv::OpAtomicAnd:
1200 case spv::OpAtomicOr:
1201 case spv::OpAtomicXor:
1202 worklist.insert(insn.word(3)); // ptr
1203 break;
1204 case spv::OpStore:
1205 case spv::OpAtomicStore:
1206 worklist.insert(insn.word(1)); // ptr
1207 break;
1208 case spv::OpAccessChain:
1209 case spv::OpInBoundsAccessChain:
1210 worklist.insert(insn.word(3)); // base ptr
1211 break;
1212 case spv::OpSampledImage:
1213 case spv::OpImageSampleImplicitLod:
1214 case spv::OpImageSampleExplicitLod:
1215 case spv::OpImageSampleDrefImplicitLod:
1216 case spv::OpImageSampleDrefExplicitLod:
1217 case spv::OpImageSampleProjImplicitLod:
1218 case spv::OpImageSampleProjExplicitLod:
1219 case spv::OpImageSampleProjDrefImplicitLod:
1220 case spv::OpImageSampleProjDrefExplicitLod:
1221 case spv::OpImageFetch:
1222 case spv::OpImageGather:
1223 case spv::OpImageDrefGather:
1224 case spv::OpImageRead:
1225 case spv::OpImage:
1226 case spv::OpImageQueryFormat:
1227 case spv::OpImageQueryOrder:
1228 case spv::OpImageQuerySizeLod:
1229 case spv::OpImageQuerySize:
1230 case spv::OpImageQueryLod:
1231 case spv::OpImageQueryLevels:
1232 case spv::OpImageQuerySamples:
1233 case spv::OpImageSparseSampleImplicitLod:
1234 case spv::OpImageSparseSampleExplicitLod:
1235 case spv::OpImageSparseSampleDrefImplicitLod:
1236 case spv::OpImageSparseSampleDrefExplicitLod:
1237 case spv::OpImageSparseSampleProjImplicitLod:
1238 case spv::OpImageSparseSampleProjExplicitLod:
1239 case spv::OpImageSparseSampleProjDrefImplicitLod:
1240 case spv::OpImageSparseSampleProjDrefExplicitLod:
1241 case spv::OpImageSparseFetch:
1242 case spv::OpImageSparseGather:
1243 case spv::OpImageSparseDrefGather:
1244 case spv::OpImageTexelPointer:
1245 worklist.insert(insn.word(3)); // Image or sampled image
1246 break;
1247 case spv::OpImageWrite:
1248 worklist.insert(insn.word(1)); // Image -- different operand order to above
1249 break;
1250 case spv::OpFunctionCall:
1251 for (uint32_t i = 3; i < insn.len(); i++) {
1252 worklist.insert(insn.word(i)); // fn itself, and all args
1253 }
1254 break;
1255
1256 case spv::OpExtInst:
1257 for (uint32_t i = 5; i < insn.len(); i++) {
1258 worklist.insert(insn.word(i)); // Operands to ext inst
1259 }
1260 break;
1261 }
1262 }
1263 break;
1264 }
1265 }
1266
1267 return ids;
1268}
1269
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001270static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1271 std::vector<VkPushConstantRange> const *push_constant_ranges,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001272 SHADER_MODULE_STATE const *src, spirv_inst_iter type,
1273 VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001274 bool skip = false;
1275
1276 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001277 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001278 assert(type != src->end());
1279
1280 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1281 // TODO: arrays, matrices, weird sizes
1282 for (auto insn : *src) {
1283 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1284 if (insn.word(3) == spv::DecorationOffset) {
1285 unsigned offset = insn.word(4);
1286 auto size = 4; // Bytes; TODO: calculate this based on the type
1287
1288 bool found_range = false;
1289 for (auto const &range : *push_constant_ranges) {
1290 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1291 found_range = true;
1292
1293 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001294 skip |=
1295 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 -06001296 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001297 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1298 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001299 }
1300
1301 break;
1302 }
1303 }
1304
1305 if (!found_range) {
1306 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 -06001307 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001308 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001309 }
1310 }
1311 }
1312 }
1313
1314 return skip;
1315}
1316
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001317static bool ValidatePushConstantUsage(debug_report_data const *report_data,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001318 std::vector<VkPushConstantRange> const *push_constant_ranges, SHADER_MODULE_STATE const *src,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001319 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001320 bool skip = false;
1321
1322 for (auto id : accessible_ids) {
1323 auto def_insn = src->get_def(id);
1324 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001325 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1326 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001327 }
1328 }
1329
1330 return skip;
1331}
1332
1333// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001334static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001335 bool skip = false;
1336
1337 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1338
1339 if (spec) {
1340 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001341 if (spec->pMapEntries[i].offset >= spec->dataSize) {
1342 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
1343 "VUID-VkSpecializationInfo-offset-00773",
1344 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1345 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1346 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1347 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
1348
1349 continue;
1350 }
Chris Forbes47567b72017-06-09 12:09:45 -07001351 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001352 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 -06001353 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001354 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001355 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001356 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001357 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001358 }
1359 }
1360 }
1361
1362 return skip;
1363}
1364
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001365// TODO (jbolz): Can this return a const reference?
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001366static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001367 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001368 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001369 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001370 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001371
1372 // 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 -05001373 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1374 if (type.opcode() == spv::OpTypeRuntimeArray) {
1375 descriptor_count = 0;
1376 type = module->get_def(type.word(2));
1377 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001378 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001379 type = module->get_def(type.word(2));
1380 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001381 if (type.word(2) == spv::StorageClassStorageBuffer) {
1382 is_storage_buffer = true;
1383 }
Chris Forbes47567b72017-06-09 12:09:45 -07001384 type = module->get_def(type.word(3));
1385 }
1386 }
1387
1388 switch (type.opcode()) {
1389 case spv::OpTypeStruct: {
1390 for (auto insn : *module) {
1391 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1392 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001393 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001394 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1395 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1396 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001397 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001398 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1399 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1400 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1401 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001402 }
Chris Forbes47567b72017-06-09 12:09:45 -07001403 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001404 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1405 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1406 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001407 }
1408 }
1409 }
1410
1411 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001412 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001413 }
1414
1415 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001416 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1417 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1418 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001419
Chris Forbes73c00bf2018-06-22 16:28:06 -07001420 case spv::OpTypeSampledImage: {
1421 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1422 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1423 auto image_type = module->get_def(type.word(2));
1424 auto dim = image_type.word(3);
1425 auto sampled = image_type.word(7);
1426 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001427 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1428 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001429 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001430 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001431 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1432 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001433
1434 case spv::OpTypeImage: {
1435 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1436 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1437 auto dim = type.word(3);
1438 auto sampled = type.word(7);
1439
1440 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001441 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1442 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001443 } else if (dim == spv::DimBuffer) {
1444 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001445 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1446 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001447 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001448 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1449 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001450 }
1451 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001452 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1453 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1454 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001455 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001456 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1457 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001458 }
1459 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001460 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001461 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001462 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001463
1464 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1465 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001466 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001467 }
1468}
1469
Jeff Bolze54ae892018-09-08 12:16:29 -05001470static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001471 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001472 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1473 if (ss.tellp()) ss << ", ";
1474 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001475 }
1476 return ss.str();
1477}
1478
Jeff Bolzee743412019-06-20 22:24:32 -05001479static bool RequirePropertyFlag(debug_report_data const *report_data, VkBool32 check, char const *flag, char const *structure) {
1480 if (!check) {
1481 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1482 kVUID_Core_Shader_ExceedDeviceLimit, "Shader requires flag %s set in %s but it is not set on the device", flag,
1483 structure)) {
1484 return true;
1485 }
1486 }
1487
1488 return false;
1489}
1490
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001491static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001492 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001493 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 -06001494 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001495 return true;
1496 }
1497 }
1498
1499 return false;
1500}
1501
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001502static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001503 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001504 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 -06001505 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001506 extension_name)) {
1507 return true;
1508 }
1509 }
1510
1511 return false;
1512}
1513
John Zulaufac4c6e12019-07-01 16:05:58 -06001514bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001515 bool skip = false;
1516
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001517 struct FeaturePointer {
1518 // Callable object to test if this feature is enabled in the given aggregate feature struct
1519 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1520
1521 // Test if feature pointer is populated
1522 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1523
1524 // Default and nullptr constructor to create an empty FeaturePointer
1525 FeaturePointer() : IsEnabled(nullptr) {}
1526 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1527
1528 // Constructors to populate FeaturePointer based on given pointer to member
1529 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1530 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1531 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1532 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1533 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1534 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001535 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1536 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001537 FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
1538 : IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
Tobias Hector6a0ece72018-12-10 12:24:05 +00001539 FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
1540 : IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001541 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1542 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001543 FeaturePointer(VkBool32 VkPhysicalDeviceFloatControlsPropertiesKHR::*ptr)
1544 : IsEnabled([=](const DeviceFeatures &features) { return features.float_controls.*ptr; }) {}
Graeme Leese9b6a1522019-06-07 20:49:45 +01001545 FeaturePointer(VkBool32 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR::*ptr)
1546 : IsEnabled([=](const DeviceFeatures &features) { return features.uniform_buffer_standard_layout.*ptr; }) {}
Jason Macnakc5a621d2019-06-10 12:42:50 -07001547 FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
1548 : IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
Jason Macnak325e8b52019-06-10 13:33:10 -07001549 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
1550 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
Jason Macnakd7fddf82019-06-13 09:52:49 -07001551 FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
1552 : IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001553 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
1554 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001555 FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
1556 : IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001557 };
1558
Chris Forbes47567b72017-06-09 12:09:45 -07001559 struct CapabilityInfo {
1560 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001561 FeaturePointer feature;
1562 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001563 };
1564
Chris Forbes47567b72017-06-09 12:09:45 -07001565 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001566 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001567 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1568 // feature bits.
1569 {spv::CapabilityMatrix, {nullptr}},
1570 {spv::CapabilityShader, {nullptr}},
1571 {spv::CapabilityInputAttachment, {nullptr}},
1572 {spv::CapabilitySampled1D, {nullptr}},
1573 {spv::CapabilityImage1D, {nullptr}},
1574 {spv::CapabilitySampledBuffer, {nullptr}},
Toni Merilehtib13a4a22019-05-21 12:58:44 +03001575 {spv::CapabilityStorageImageExtendedFormats, {nullptr}},
Chris Forbes47567b72017-06-09 12:09:45 -07001576 {spv::CapabilityImageQuery, {nullptr}},
1577 {spv::CapabilityDerivativeControl, {nullptr}},
1578
1579 // Capabilities that are optionally supported, but require a feature to
1580 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001581 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1582 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1583 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1584 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1585 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1586 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1587 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1588 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1589 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1590 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1591 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1592 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1593 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1594 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1595 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1596 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1597 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1598 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1599 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1600 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001601 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1602 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1603 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1604 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001605
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001606 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1607 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1608 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1609 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1610 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1611 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1612 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1613 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1614 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1615 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1616 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
Jason Macnakf7019582019-06-13 10:07:26 -07001617 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001618
1619 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001620 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1621 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1622 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1623 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1624 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1625 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1626 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1627 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Jason Macnakb7d091c2019-06-10 11:13:11 -07001628 {spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
aqnuep7033c702018-09-11 18:03:29 +02001629 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001630
Jason Macnakc5a621d2019-06-10 12:42:50 -07001631 {spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
1632 {spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
Jason Macnakf7019582019-06-13 10:07:26 -07001633 {spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
Jason Macnakc5a621d2019-06-10 12:42:50 -07001634
Jason Macnakf7019582019-06-13 10:07:26 -07001635 {spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1636 {spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1637 {spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001638
Jason Macnakf7019582019-06-13 10:07:26 -07001639 {spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
1640 {spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001641
Jason Macnakf7019582019-06-13 10:07:26 -07001642 {spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1643 {spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001644
Jason Macnakd7fddf82019-06-13 09:52:49 -07001645 {spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
1646
Jeff Bolze4356752019-03-07 11:23:46 -06001647 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001648
1649 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1650 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1651 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1652 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1653 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1654 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1655 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1656 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1657 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1658 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1659 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1660 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1661 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1662 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1663 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001664
1665 {spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1666 {spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1667 {spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001668 {spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
Chris Forbes47567b72017-06-09 12:09:45 -07001669 };
1670 // clang-format on
1671
1672 for (auto insn : *src) {
1673 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001674 size_t n = capabilities.count(insn.word(1));
1675 if (1 == n) { // key occurs exactly once
1676 auto it = capabilities.find(insn.word(1));
1677 if (it != capabilities.end()) {
1678 if (it->second.feature) {
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001679 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(enabled_features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001680 }
1681 if (it->second.extension) {
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001682 skip |= RequireExtension(report_data, device_extensions.*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001683 }
Chris Forbes47567b72017-06-09 12:09:45 -07001684 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001685 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1686 bool needs_feature = false, has_feature = false;
1687 bool needs_ext = false, has_ext = false;
1688 std::string feature_names = "(one of) [ ";
1689 std::string extension_names = feature_names;
1690 auto caps = capabilities.equal_range(insn.word(1));
1691 for (auto it = caps.first; it != caps.second; ++it) {
1692 if (it->second.feature) {
1693 needs_feature = true;
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001694 has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001695 feature_names += it->second.name;
1696 feature_names += " ";
1697 }
1698 if (it->second.extension) {
1699 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001700 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001701 extension_names += it->second.name;
1702 extension_names += " ";
1703 }
1704 }
1705 if (needs_feature) {
1706 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001707 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001708 }
1709 if (needs_ext) {
1710 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001711 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001712 }
Jeff Bolzee743412019-06-20 22:24:32 -05001713 } else { // Do group non-uniform checks
1714 const VkSubgroupFeatureFlags supportedOperations = phys_dev_ext_props.subgroup_props.supportedOperations;
1715 const VkSubgroupFeatureFlags supportedStages = phys_dev_ext_props.subgroup_props.supportedStages;
1716
1717 switch (insn.word(1)) {
1718 default:
1719 break;
1720 case spv::CapabilityGroupNonUniform:
1721 case spv::CapabilityGroupNonUniformVote:
1722 case spv::CapabilityGroupNonUniformArithmetic:
1723 case spv::CapabilityGroupNonUniformBallot:
1724 case spv::CapabilityGroupNonUniformShuffle:
1725 case spv::CapabilityGroupNonUniformShuffleRelative:
1726 case spv::CapabilityGroupNonUniformClustered:
1727 case spv::CapabilityGroupNonUniformQuad:
1728 case spv::CapabilityGroupNonUniformPartitionedNV:
1729 RequirePropertyFlag(report_data, supportedStages & stage, string_VkShaderStageFlagBits(stage),
1730 "VkPhysicalDeviceSubgroupProperties::supportedStages");
1731 break;
1732 }
1733
1734 switch (insn.word(1)) {
1735 default:
1736 break;
1737 case spv::CapabilityGroupNonUniform:
1738 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT,
1739 "VK_SUBGROUP_FEATURE_BASIC_BIT",
1740 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1741 break;
1742 case spv::CapabilityGroupNonUniformVote:
1743 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT,
1744 "VK_SUBGROUP_FEATURE_VOTE_BIT",
1745 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1746 break;
1747 case spv::CapabilityGroupNonUniformArithmetic:
1748 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
1749 "VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
1750 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1751 break;
1752 case spv::CapabilityGroupNonUniformBallot:
1753 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT,
1754 "VK_SUBGROUP_FEATURE_BALLOT_BIT",
1755 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1756 break;
1757 case spv::CapabilityGroupNonUniformShuffle:
1758 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
1759 "VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
1760 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1761 break;
1762 case spv::CapabilityGroupNonUniformShuffleRelative:
1763 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
1764 "VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
1765 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1766 break;
1767 case spv::CapabilityGroupNonUniformClustered:
1768 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
1769 "VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
1770 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1771 break;
1772 case spv::CapabilityGroupNonUniformQuad:
1773 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT,
1774 "VK_SUBGROUP_FEATURE_QUAD_BIT",
1775 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1776 break;
1777 case spv::CapabilityGroupNonUniformPartitionedNV:
1778 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
1779 "VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
1780 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1781 break;
1782 }
Chris Forbes47567b72017-06-09 12:09:45 -07001783 }
1784 }
1785 }
1786
Jeff Bolzee743412019-06-20 22:24:32 -05001787 return skip;
1788}
1789
John Zulaufac4c6e12019-07-01 16:05:58 -06001790bool CoreChecks::ValidateShaderStageWritableDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001791 bool skip = false;
1792
Chris Forbes349b3132018-03-07 11:38:08 -08001793 if (has_writable_descriptor) {
1794 switch (stage) {
1795 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001796 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1797 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1798 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1799 case VK_SHADER_STAGE_MISS_BIT_NV:
1800 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1801 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1802 case VK_SHADER_STAGE_TASK_BIT_NV:
1803 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001804 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001805 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001806 break;
1807 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001808 skip |= RequireFeature(report_data, enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001809 break;
1810 default:
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001811 skip |= RequireFeature(report_data, enabled_features.core.vertexPipelineStoresAndAtomics,
1812 "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001813 break;
1814 }
1815 }
1816
Chris Forbes47567b72017-06-09 12:09:45 -07001817 return skip;
1818}
1819
Jeff Bolzee743412019-06-20 22:24:32 -05001820bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001821 std::unordered_set<uint32_t> const &accessible_ids) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001822 bool skip = false;
1823
1824 auto const subgroup_props = phys_dev_ext_props.subgroup_props;
1825
1826 for (uint32_t id : accessible_ids) {
1827 auto inst = module->get_def(id);
1828
1829 // Check the quad operations.
1830 switch (inst.opcode()) {
1831 default:
1832 break;
1833 case spv::OpGroupNonUniformQuadBroadcast:
1834 case spv::OpGroupNonUniformQuadSwap:
1835 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
1836 skip |= RequireFeature(report_data, subgroup_props.quadOperationsInAllStages,
1837 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
1838 }
1839 break;
1840 }
1841 }
1842
1843 return skip;
1844}
1845
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001846bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001847 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001848 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1849 pStage->stage == VK_SHADER_STAGE_ALL) {
1850 return false;
1851 }
1852
1853 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001854 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001855
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001856 std::set<uint32_t> patchIDs;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001857 struct Variable {
1858 uint32_t baseTypePtrID;
1859 uint32_t ID;
1860 uint32_t storageClass;
1861 };
1862 std::vector<Variable> variables;
1863
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001864 uint32_t numVertices = 0;
1865
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001866 for (auto insn : *src) {
1867 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001868 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001869 case spv::OpDecorate:
1870 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001871 case spv::DecorationPatch: {
1872 patchIDs.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001873 break;
1874 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001875 default:
1876 break;
1877 }
1878 break;
1879 // Find all input and output variables
1880 case spv::OpVariable: {
1881 Variable var = {};
1882 var.storageClass = insn.word(3);
1883 if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
1884 var.baseTypePtrID = insn.word(1);
1885 var.ID = insn.word(2);
1886 variables.push_back(var);
1887 }
1888 break;
1889 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001890 case spv::OpExecutionMode:
1891 if (insn.word(1) == entrypoint.word(2)) {
1892 switch (insn.word(2)) {
1893 default:
1894 break;
1895 case spv::ExecutionModeOutputVertices:
1896 numVertices = insn.word(3);
1897 break;
1898 }
1899 }
1900 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001901 default:
1902 break;
1903 }
1904 }
1905
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001906 bool strip_output_array_level =
1907 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
1908 bool strip_input_array_level =
1909 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
1910 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
1911
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001912 uint32_t numCompIn = 0, numCompOut = 0;
1913 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001914 // Check if the variable is a patch. Patches can also be members of blocks,
1915 // but if they are then the top-level arrayness has already been stripped
1916 // by the time GetComponentsConsumedByType gets to it.
1917 bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001918
1919 if (var.storageClass == spv::StorageClassInput) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001920 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001921 } else { // var.storageClass == spv::StorageClassOutput
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001922 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001923 }
1924 }
1925
1926 switch (pStage->stage) {
1927 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001928 if (numCompOut > limits.maxVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001929 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1930 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1931 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1932 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
1933 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001934 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001935 }
1936 break;
1937
1938 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001939 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001940 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1941 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1942 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1943 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
1944 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001945 limits.maxTessellationControlPerVertexInputComponents,
1946 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001947 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001948 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001949 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1950 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1951 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1952 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
1953 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001954 limits.maxTessellationControlPerVertexOutputComponents,
1955 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001956 }
1957 break;
1958
1959 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001960 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001961 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1962 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1963 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1964 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
1965 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001966 limits.maxTessellationEvaluationInputComponents,
1967 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001968 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001969 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001970 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1971 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1972 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1973 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
1974 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001975 limits.maxTessellationEvaluationOutputComponents,
1976 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001977 }
1978 break;
1979
1980 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001981 if (numCompIn > limits.maxGeometryInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001982 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1983 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1984 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1985 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
1986 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001987 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001988 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001989 if (numCompOut > limits.maxGeometryOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001990 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1991 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1992 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1993 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
1994 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001995 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001996 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001997 if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
1998 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1999 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
2000 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2001 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2002 "components by %u components",
2003 limits.maxGeometryTotalOutputComponents,
2004 numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
2005 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002006 break;
2007
2008 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002009 if (numCompIn > limits.maxFragmentInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002010 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
2011 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
2012 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2013 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2014 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002015 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002016 }
2017 break;
2018
Jeff Bolz148d94e2018-12-13 21:25:56 -06002019 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2020 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2021 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2022 case VK_SHADER_STAGE_MISS_BIT_NV:
2023 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2024 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2025 case VK_SHADER_STAGE_TASK_BIT_NV:
2026 case VK_SHADER_STAGE_MESH_BIT_NV:
2027 break;
2028
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002029 default:
2030 assert(false); // This should never happen
2031 }
2032 return skip;
2033}
2034
Jeff Bolze4356752019-03-07 11:23:46 -06002035// copy the specialization constant value into buf, if it is present
2036void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2037 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2038
2039 if (spec && spec_id < spec->mapEntryCount) {
2040 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2041 }
2042}
2043
2044// Fill in value with the constant or specialization constant value, if available.
2045// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002046static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002047 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2048 auto type_id = src->get_def(insn.word(1));
2049 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2050 return false;
2051 }
2052 switch (insn.opcode()) {
2053 case spv::OpSpecConstant:
2054 *value = insn.word(3);
2055 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2056 return true;
2057 case spv::OpConstant:
2058 *value = insn.word(3);
2059 return true;
2060 default:
2061 return false;
2062 }
2063}
2064
2065// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002066VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002067 switch (insn.opcode()) {
2068 case spv::OpTypeInt:
2069 switch (insn.word(2)) {
2070 case 8:
2071 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2072 case 16:
2073 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2074 case 32:
2075 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2076 case 64:
2077 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2078 default:
2079 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2080 }
2081 case spv::OpTypeFloat:
2082 switch (insn.word(2)) {
2083 case 16:
2084 return VK_COMPONENT_TYPE_FLOAT16_NV;
2085 case 32:
2086 return VK_COMPONENT_TYPE_FLOAT32_NV;
2087 case 64:
2088 return VK_COMPONENT_TYPE_FLOAT64_NV;
2089 default:
2090 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2091 }
2092 default:
2093 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2094 }
2095}
2096
2097// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2098// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002099bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002100 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002101 bool skip = false;
2102
2103 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2104 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2105 // Map SPIR-V result ID to the ID of its type.
2106 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2107
2108 struct CoopMatType {
2109 uint32_t scope, rows, cols;
2110 VkComponentTypeNV component_type;
2111 bool all_constant;
2112
2113 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2114
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002115 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002116 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2117 spirv_inst_iter insn = src->get_def(id);
2118 uint32_t component_type_id = insn.word(2);
2119 uint32_t scope_id = insn.word(3);
2120 uint32_t rows_id = insn.word(4);
2121 uint32_t cols_id = insn.word(5);
2122 auto component_type_iter = src->get_def(component_type_id);
2123 auto scope_iter = src->get_def(scope_id);
2124 auto rows_iter = src->get_def(rows_id);
2125 auto cols_iter = src->get_def(cols_id);
2126
2127 all_constant = true;
2128 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2129 all_constant = false;
2130 }
2131 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2132 all_constant = false;
2133 }
2134 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2135 all_constant = false;
2136 }
2137 component_type = GetComponentType(component_type_iter, src);
2138 }
2139 };
2140
2141 bool seen_coopmat_capability = false;
2142
2143 for (auto insn : *src) {
2144 // Whitelist instructions whose result can be a cooperative matrix type, and
2145 // keep track of their types. It would be nice if SPIRV-Headers generated code
2146 // to identify which instructions have a result type and result id. Lacking that,
2147 // this whitelist is based on the set of instructions that
2148 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2149 switch (insn.opcode()) {
2150 case spv::OpLoad:
2151 case spv::OpCooperativeMatrixLoadNV:
2152 case spv::OpCooperativeMatrixMulAddNV:
2153 case spv::OpSNegate:
2154 case spv::OpFNegate:
2155 case spv::OpIAdd:
2156 case spv::OpFAdd:
2157 case spv::OpISub:
2158 case spv::OpFSub:
2159 case spv::OpFDiv:
2160 case spv::OpSDiv:
2161 case spv::OpUDiv:
2162 case spv::OpMatrixTimesScalar:
2163 case spv::OpConstantComposite:
2164 case spv::OpCompositeConstruct:
2165 case spv::OpConvertFToU:
2166 case spv::OpConvertFToS:
2167 case spv::OpConvertSToF:
2168 case spv::OpConvertUToF:
2169 case spv::OpUConvert:
2170 case spv::OpSConvert:
2171 case spv::OpFConvert:
2172 id_to_type_id[insn.word(2)] = insn.word(1);
2173 break;
2174 default:
2175 break;
2176 }
2177
2178 switch (insn.opcode()) {
2179 case spv::OpDecorate:
2180 if (insn.word(2) == spv::DecorationSpecId) {
2181 id_to_spec_id[insn.word(1)] = insn.word(3);
2182 }
2183 break;
2184 case spv::OpCapability:
2185 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2186 seen_coopmat_capability = true;
2187
2188 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
2189 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002190 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002191 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2192 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2193 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
2194 }
2195 }
2196 break;
2197 case spv::OpMemoryModel:
2198 // If the capability isn't enabled, don't bother with the rest of this function.
2199 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2200 if (!seen_coopmat_capability) {
2201 return skip;
2202 }
2203 break;
2204 case spv::OpTypeCooperativeMatrixNV: {
2205 CoopMatType M;
2206 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2207
2208 if (M.all_constant) {
2209 // Validate that the type parameters are all supported for one of the
2210 // operands of a cooperative matrix property.
2211 bool valid = false;
2212 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2213 if (cooperative_matrix_properties[i].AType == M.component_type &&
2214 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2215 cooperative_matrix_properties[i].scope == M.scope) {
2216 valid = true;
2217 break;
2218 }
2219 if (cooperative_matrix_properties[i].BType == M.component_type &&
2220 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2221 cooperative_matrix_properties[i].scope == M.scope) {
2222 valid = true;
2223 break;
2224 }
2225 if (cooperative_matrix_properties[i].CType == M.component_type &&
2226 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2227 cooperative_matrix_properties[i].scope == M.scope) {
2228 valid = true;
2229 break;
2230 }
2231 if (cooperative_matrix_properties[i].DType == M.component_type &&
2232 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2233 cooperative_matrix_properties[i].scope == M.scope) {
2234 valid = true;
2235 break;
2236 }
2237 }
2238 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002239 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002240 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixType,
2241 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2242 insn.word(1));
2243 }
2244 }
2245 break;
2246 }
2247 case spv::OpCooperativeMatrixMulAddNV: {
2248 CoopMatType A, B, C, D;
2249 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2250 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2251 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2252 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002253 // Couldn't find type of matrix
2254 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002255 break;
2256 }
2257 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2258 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2259 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2260 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2261
2262 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2263 // Validate that the type parameters are all supported for the same
2264 // cooperative matrix property.
2265 bool valid = false;
2266 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2267 if (cooperative_matrix_properties[i].AType == A.component_type &&
2268 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2269 cooperative_matrix_properties[i].scope == A.scope &&
2270
2271 cooperative_matrix_properties[i].BType == B.component_type &&
2272 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2273 cooperative_matrix_properties[i].scope == B.scope &&
2274
2275 cooperative_matrix_properties[i].CType == C.component_type &&
2276 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2277 cooperative_matrix_properties[i].scope == C.scope &&
2278
2279 cooperative_matrix_properties[i].DType == D.component_type &&
2280 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2281 cooperative_matrix_properties[i].scope == D.scope) {
2282 valid = true;
2283 break;
2284 }
2285 }
2286 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002287 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002288 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixMulAdd,
2289 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2290 "VkCooperativeMatrixPropertiesNV",
2291 insn.word(2));
2292 }
2293 }
2294 break;
2295 }
2296 default:
2297 break;
2298 }
2299 }
2300
2301 return skip;
2302}
2303
John Zulaufac4c6e12019-07-01 16:05:58 -06002304bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002305 auto entrypoint_id = entrypoint.word(2);
2306
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002307 // The first denorm execution mode encountered, along with its bit width.
2308 // Used to check if SeparateDenormSettings is respected.
2309 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002310
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002311 // The first rounding mode encountered, along with its bit width.
2312 // Used to check if SeparateRoundingModeSettings is respected.
2313 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002314
2315 bool skip = false;
2316
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002317 uint32_t verticesOut = 0;
2318 uint32_t invocations = 0;
2319
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002320 for (auto insn : *src) {
2321 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2322 auto mode = insn.word(2);
2323 switch (mode) {
2324 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2325 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002326 if ((bit_width == 16 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat16) ||
2327 (bit_width == 32 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat32) ||
2328 (bit_width == 64 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002329 skip |=
2330 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2331 kVUID_Core_Shader_FeatureNotEnabled,
2332 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2333 bit_width);
2334 }
2335 break;
2336 }
2337
2338 case spv::ExecutionModeDenormPreserve: {
2339 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002340 if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormPreserveFloat16) ||
2341 (bit_width == 32 && !enabled_features.float_controls.shaderDenormPreserveFloat32) ||
2342 (bit_width == 64 && !enabled_features.float_controls.shaderDenormPreserveFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002343 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2344 kVUID_Core_Shader_FeatureNotEnabled,
2345 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2346 bit_width);
2347 }
2348
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002349 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2350 // Register the first denorm execution mode found
2351 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002352 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
2353 switch (enabled_features.float_controls.denormBehaviorIndependence) {
2354 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2355 if (first_rounding_mode.second != 32 && bit_width != 32) {
2356 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2357 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2358 "Shader uses different denorm execution modes for 16 and 64-bit but "
2359 "denormBehaviorIndependence is "
2360 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2361 }
2362 break;
2363
2364 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2365 break;
2366
2367 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2368 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2369 0, kVUID_Core_Shader_FeatureNotEnabled,
2370 "Shader uses different denorm execution modes for different bit widths but "
2371 "denormBehaviorIndependence is "
2372 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2373 break;
2374
2375 default:
2376 break;
2377 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002378 }
2379 break;
2380 }
2381
2382 case spv::ExecutionModeDenormFlushToZero: {
2383 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002384 if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat16) ||
2385 (bit_width == 32 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat32) ||
2386 (bit_width == 64 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002387 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2388 kVUID_Core_Shader_FeatureNotEnabled,
2389 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2390 bit_width);
2391 }
2392
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002393 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2394 // Register the first denorm execution mode found
2395 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002396 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
2397 switch (enabled_features.float_controls.denormBehaviorIndependence) {
2398 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2399 if (first_rounding_mode.second != 32 && bit_width != 32) {
2400 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2401 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2402 "Shader uses different denorm execution modes for 16 and 64-bit but "
2403 "denormBehaviorIndependence is "
2404 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2405 }
2406 break;
2407
2408 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2409 break;
2410
2411 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2412 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2413 0, kVUID_Core_Shader_FeatureNotEnabled,
2414 "Shader uses different denorm execution modes for different bit widths but "
2415 "denormBehaviorIndependence is "
2416 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2417 break;
2418
2419 default:
2420 break;
2421 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002422 }
2423 break;
2424 }
2425
2426 case spv::ExecutionModeRoundingModeRTE: {
2427 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002428 if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTEFloat16) ||
2429 (bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTEFloat32) ||
2430 (bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTEFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002431 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2432 kVUID_Core_Shader_FeatureNotEnabled,
2433 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2434 bit_width);
2435 }
2436
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002437 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2438 // Register the first rounding mode found
2439 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002440 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
2441 switch (enabled_features.float_controls.roundingModeIndependence) {
2442 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2443 if (first_rounding_mode.second != 32 && bit_width != 32) {
2444 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2445 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2446 "Shader uses different rounding modes for 16 and 64-bit but "
2447 "roundingModeIndependence is "
2448 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2449 }
2450 break;
2451
2452 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2453 break;
2454
2455 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2456 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2457 0, kVUID_Core_Shader_FeatureNotEnabled,
2458 "Shader uses different rounding modes for different bit widths but "
2459 "roundingModeIndependence is "
2460 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2461 break;
2462
2463 default:
2464 break;
2465 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002466 }
2467 break;
2468 }
2469
2470 case spv::ExecutionModeRoundingModeRTZ: {
2471 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002472 if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTZFloat16) ||
2473 (bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTZFloat32) ||
2474 (bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTZFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002475 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2476 kVUID_Core_Shader_FeatureNotEnabled,
2477 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
2478 bit_width);
2479 }
2480
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002481 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2482 // Register the first rounding mode found
2483 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002484 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
2485 switch (enabled_features.float_controls.roundingModeIndependence) {
2486 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2487 if (first_rounding_mode.second != 32 && bit_width != 32) {
2488 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2489 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2490 "Shader uses different rounding modes for 16 and 64-bit but "
2491 "roundingModeIndependence is "
2492 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2493 }
2494 break;
2495
2496 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2497 break;
2498
2499 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2500 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2501 0, kVUID_Core_Shader_FeatureNotEnabled,
2502 "Shader uses different rounding modes for different bit widths but "
2503 "roundingModeIndependence is "
2504 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2505 break;
2506
2507 default:
2508 break;
2509 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002510 }
2511 break;
2512 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002513
2514 case spv::ExecutionModeOutputVertices: {
2515 verticesOut = insn.word(3);
2516 break;
2517 }
2518
2519 case spv::ExecutionModeInvocations: {
2520 invocations = insn.word(3);
2521 break;
2522 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002523 }
2524 }
2525 }
2526
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002527 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
2528 if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
2529 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2530 "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
2531 "Geometry shader entry point must have an OpExecutionMode instruction that "
2532 "specifies a maximum output vertex count that is greater than 0 and less "
2533 "than or equal to maxGeometryOutputVertices. "
2534 "OutputVertices=%d, maxGeometryOutputVertices=%d",
2535 verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
2536 }
2537
2538 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
2539 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2540 "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
2541 "Geometry shader entry point must have an OpExecutionMode instruction that "
2542 "specifies an invocation count that is greater than 0 and less "
2543 "than or equal to maxGeometryShaderInvocations. "
2544 "Invocations=%d, maxGeometryShaderInvocations=%d",
2545 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
2546 }
2547 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002548 return skip;
2549}
2550
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002551static uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07002552 auto type = module->get_def(type_id);
2553
2554 while (true) {
2555 switch (type.opcode()) {
2556 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07002557 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07002558 case spv::OpTypeSampledImage:
2559 type = module->get_def(type.word(2));
2560 break;
2561 case spv::OpTypePointer:
2562 type = module->get_def(type.word(3));
2563 break;
2564 case spv::OpTypeImage: {
2565 auto dim = type.word(3);
2566 auto arrayed = type.word(5);
2567 auto msaa = type.word(6);
2568
Chris Forbes74ba2232018-08-27 15:19:27 -07002569 uint32_t bits = 0;
2570 switch (GetFundamentalType(module, type.word(2))) {
2571 case FORMAT_TYPE_FLOAT:
2572 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
2573 break;
2574 case FORMAT_TYPE_UINT:
2575 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
2576 break;
2577 case FORMAT_TYPE_SINT:
2578 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
2579 break;
2580 default:
2581 break;
2582 }
2583
Chris Forbes47567b72017-06-09 12:09:45 -07002584 switch (dim) {
2585 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002586 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
2587 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002588 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002589 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2590 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
2591 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002592 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002593 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
2594 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002595 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07002596 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
2597 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002598 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07002599 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2600 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002601 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07002602 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002603 }
2604 }
2605 default:
2606 return 0;
2607 }
2608 }
2609}
2610
2611// For given pipelineLayout verify that the set_layout_node at slot.first
2612// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06002613static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002614 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07002615 if (!pipelineLayout) return nullptr;
2616
2617 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
2618
2619 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
2620}
2621
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002622static bool FindLocalSize(SHADER_MODULE_STATE const *src, uint32_t &local_size_x, uint32_t &local_size_y, uint32_t &local_size_z) {
Locke1ec6d952019-04-02 11:57:21 -06002623 for (auto insn : *src) {
2624 if (insn.opcode() == spv::OpEntryPoint) {
2625 auto executionModel = insn.word(1);
2626 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
2627 if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
2628 auto entrypoint_id = insn.word(2);
2629 for (auto insn1 : *src) {
2630 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
2631 insn1.word(2) == spv::ExecutionModeLocalSize) {
2632 local_size_x = insn1.word(3);
2633 local_size_y = insn1.word(4);
2634 local_size_z = insn1.word(5);
2635 return true;
2636 }
2637 }
2638 }
2639 }
2640 }
2641 return false;
2642}
2643
John Zulauf14c355b2019-06-27 16:09:37 -06002644static void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05002645 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07002646 bool is_point_mode = false;
2647
2648 for (auto insn : *src) {
2649 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2650 switch (insn.word(2)) {
2651 case spv::ExecutionModePointMode:
2652 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
2653 is_point_mode = true;
2654 break;
2655
2656 case spv::ExecutionModeOutputPoints:
2657 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2658 break;
2659
2660 case spv::ExecutionModeIsolines:
2661 case spv::ExecutionModeOutputLineStrip:
2662 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
2663 break;
2664
2665 case spv::ExecutionModeTriangles:
2666 case spv::ExecutionModeQuads:
2667 case spv::ExecutionModeOutputTriangleStrip:
2668 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
2669 break;
2670 }
2671 }
2672 }
2673
2674 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2675}
2676
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002677// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
2678// o If there is only a vertex shader : gl_PointSize must be written when using points
2679// o If there is a geometry or tessellation shader:
2680// - If shaderTessellationAndGeometryPointSize feature is enabled:
2681// * gl_PointSize must be written in the final geometry stage
2682// - If shaderTessellationAndGeometryPointSize feature is disabled:
2683// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002684bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06002685 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002686 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2687 return false;
2688 }
2689
2690 bool pointsize_written = false;
2691 bool skip = false;
2692
2693 // Search for PointSize built-in decorations
2694 std::vector<uint32_t> pointsize_builtin_offsets;
2695 spirv_inst_iter insn = entrypoint;
2696 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
2697 if (insn.opcode() == spv::OpMemberDecorate) {
2698 if (insn.word(3) == spv::DecorationBuiltIn) {
2699 if (insn.word(4) == spv::BuiltInPointSize) {
2700 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2701 }
2702 }
2703 } else if (insn.opcode() == spv::OpDecorate) {
2704 if (insn.word(2) == spv::DecorationBuiltIn) {
2705 if (insn.word(3) == spv::BuiltInPointSize) {
2706 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2707 }
2708 }
2709 }
2710
2711 insn++;
2712 }
2713
2714 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002715 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002716 if (pointsize_written) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002717 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002718 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
2719 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
2720 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
2721 }
2722 } else if (!pointsize_written) {
2723 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002724 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002725 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
2726 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
2727 string_VkShaderStageFlagBits(stage));
2728 }
2729 return skip;
2730}
John Zulauf14c355b2019-06-27 16:09:37 -06002731void ValidationStateTracker::RecordPipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
2732 PIPELINE_STATE::StageState *stage_state) {
2733 // Validation shouldn't rely on anything in stage state being valid if the spirv isn't
2734 auto module = GetShaderModuleState(pStage->module);
2735 if (!module->has_valid_spirv) return;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002736
John Zulauf14c355b2019-06-27 16:09:37 -06002737 // Validation shouldn't rely on anything in stage state being valid if the entrypoint isn't present
2738 auto entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
2739 if (entrypoint == module->end()) return;
Chris Forbes47567b72017-06-09 12:09:45 -07002740
Chris Forbes47567b72017-06-09 12:09:45 -07002741 // Mark accessible ids
John Zulauf14c355b2019-06-27 16:09:37 -06002742 stage_state->accessible_ids = MarkAccessibleIds(module, entrypoint);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002743 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002744
John Zulauf14c355b2019-06-27 16:09:37 -06002745 stage_state->descriptor_uses =
2746 CollectInterfaceByDescriptorSlot(report_data, module, stage_state->accessible_ids, &stage_state->has_writable_descriptor);
2747 // Capture descriptor uses for the pipeline
2748 for (auto use : stage_state->descriptor_uses) {
2749 // While validating shaders capture which slots are used by the pipeline
2750 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
2751 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
2752 }
2753}
2754
2755bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
2756 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06002757 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06002758 bool skip = false;
2759
2760 // Check the module
2761 if (!module->has_valid_spirv) {
2762 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2763 "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s.",
2764 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
2765 }
2766
2767 // Check the entrypoint
2768 if (entrypoint == module->end()) {
2769 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2770 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2771 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
2772 }
2773 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
2774
2775 // Mark accessible ids
2776 auto &accessible_ids = stage_state.accessible_ids;
2777
Chris Forbes47567b72017-06-09 12:09:45 -07002778 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06002779 bool has_writable_descriptor = stage_state.has_writable_descriptor;
2780 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07002781
Chris Forbes349b3132018-03-07 11:38:08 -08002782 // Validate shader capabilities against enabled device features
Jeff Bolzee743412019-06-20 22:24:32 -05002783 skip |= ValidateShaderCapabilities(module, pStage->stage);
2784 skip |= ValidateShaderStageWritableDescriptor(pStage->stage, has_writable_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002785 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
Jeff Bolzee743412019-06-20 22:24:32 -05002786 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, accessible_ids);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002787 skip |= ValidateExecutionModes(module, entrypoint);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002788 skip |= ValidateSpecializationOffsets(report_data, pStage);
2789 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
2790 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002791 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002792 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002793 }
Jeff Bolze4356752019-03-07 11:23:46 -06002794 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002795
2796 // Validate descriptor use
2797 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07002798 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002799 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002800 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002801 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002802
2803 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002804 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 -06002805 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002806 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05002807 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002808 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002809 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 -06002810 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002811 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
2812 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05002813 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002814 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 -06002815 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002816 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05002817 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07002818 string_VkDescriptorType(binding->descriptorType));
2819 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002820 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 -06002821 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002822 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
2823 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07002824 }
2825 }
2826
2827 // Validate use of input attachments against subpass structure
2828 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002829 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07002830
Petr Krause91f7a12017-12-14 20:57:36 +01002831 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002832 auto subpass = pipeline->graphicsPipelineCI.subpass;
2833
2834 for (auto use : input_attachment_uses) {
2835 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
2836 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07002837 ? input_attachments[use.first].attachment
2838 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07002839
2840 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002841 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 -06002842 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07002843 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002844 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002845 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002846 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 -06002847 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002848 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002849 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002850 }
2851 }
2852 }
Lockeaa8fdc02019-04-02 11:59:20 -06002853 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
2854 skip |= ValidateComputeWorkGroupSizes(module);
2855 }
Chris Forbes47567b72017-06-09 12:09:45 -07002856 return skip;
2857}
2858
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002859static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, SHADER_MODULE_STATE const *producer,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002860 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002861 SHADER_MODULE_STATE const *consumer, spirv_inst_iter consumer_entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002862 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07002863 bool skip = false;
2864
2865 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002866 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
2867 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07002868
2869 auto a_it = outputs.begin();
2870 auto b_it = inputs.begin();
2871
2872 // Maps sorted by key (location); walk them together to find mismatches
2873 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
2874 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
2875 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
2876 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
2877 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
2878
2879 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06002880 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 -06002881 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06002882 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
2883 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002884 a_it++;
2885 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06002886 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 -06002887 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06002888 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
2889 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002890 b_it++;
2891 } else {
2892 // subtleties of arrayed interfaces:
2893 // - if is_patch, then the member is not arrayed, even though the interface may be.
2894 // - if is_block_member, then the extra array level of an arrayed interface is not
2895 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002896 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
2897 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
2898 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06002899 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 -06002900 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06002901 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002902 DescribeType(producer, a_it->second.type_id).c_str(),
2903 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002904 }
2905 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06002906 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 -06002907 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002908 "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 -07002909 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
2910 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
2911 }
2912 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06002913 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 -06002914 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002915 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
2916 a_first.second, producer_stage->name, consumer_stage->name);
2917 }
2918 a_it++;
2919 b_it++;
2920 }
2921 }
2922
Ari Suonpaa696b3432019-03-11 14:02:57 +02002923 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
2924 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
2925 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
2926
2927 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
2928 if (builtins_producer.size() != builtins_consumer.size()) {
2929 skip |=
2930 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
2931 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
2932 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).", producer_stage->name,
2933 (int)builtins_producer.size(), consumer_stage->name, (int)builtins_consumer.size());
2934 } else {
2935 auto it_producer = builtins_producer.begin();
2936 auto it_consumer = builtins_consumer.begin();
2937 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
2938 if (*it_producer != *it_consumer) {
2939 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
2940 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
2941 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
2942 consumer_stage->name);
2943 break;
2944 }
2945 it_producer++;
2946 it_consumer++;
2947 }
2948 }
2949 }
2950 }
2951
Chris Forbes47567b72017-06-09 12:09:45 -07002952 return skip;
2953}
2954
John Zulauf14c355b2019-06-27 16:09:37 -06002955static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002956 uint32_t stage_mask = 0;
2957 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2958 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2959 stage_mask |= pCreateInfo->pStages[i].stage;
2960 }
2961 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05002962 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
2963 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
2964 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002965 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
2966 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
2967 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2968 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
2969 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002970 }
2971 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002972 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002973}
2974
Chris Forbes47567b72017-06-09 12:09:45 -07002975// Validate that the shaders used by the given pipeline and store the active_slots
2976// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06002977bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002978 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002979 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2980 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002981
John Zulauf14c355b2019-06-27 16:09:37 -06002982 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002983 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002984 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002985 memset(entrypoints, 0, sizeof(entrypoints));
2986 bool skip = false;
2987
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002988 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
2989
Chris Forbes47567b72017-06-09 12:09:45 -07002990 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2991 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002992 auto stage_id = GetShaderStageId(pStage->stage);
John Zulauf14c355b2019-06-27 16:09:37 -06002993 shaders[stage_id] = GetShaderModuleState(pStage->module);
2994 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
2995 skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
2996
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002997 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002998 }
2999
3000 // if the shader stages are no good individually, cross-stage validation is pointless.
3001 if (skip) return true;
3002
3003 auto vi = pCreateInfo->pVertexInputState;
3004
3005 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003006 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003007 }
3008
3009 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003010 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003011 }
3012
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003013 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3014 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003015
3016 while (!shaders[producer] && producer != fragment_stage) {
3017 producer++;
3018 consumer++;
3019 }
3020
3021 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3022 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003023 if (shaders[consumer]) {
3024 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003025 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
3026 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
3027 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003028 }
Chris Forbes47567b72017-06-09 12:09:45 -07003029
3030 producer = consumer;
3031 }
3032 }
3033
3034 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003035 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
3036 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003037 }
3038
3039 return skip;
3040}
3041
John Zulaufac4c6e12019-07-01 16:05:58 -06003042bool CoreChecks::ValidateComputePipeline(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003043 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003044
John Zulauf14c355b2019-06-27 16:09:37 -06003045 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3046 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003047
John Zulauf14c355b2019-06-27 16:09:37 -06003048 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003049}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003050
John Zulaufac4c6e12019-07-01 16:05:58 -06003051bool CoreChecks::ValidateRayTracingPipelineNV(PIPELINE_STATE *pipeline) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003052 bool skip = false;
3053 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3054 const auto &stage = pipeline->raytracingPipelineCI.ptr()->pStages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003055
John Zulaufe4474e72019-07-01 17:28:27 -06003056 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3057 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003058
John Zulaufe4474e72019-07-01 17:28:27 -06003059 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
3060 }
3061 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003062}
3063
Dave Houltona9df0ce2018-02-07 10:51:23 -07003064uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003065
Dave Houltona9df0ce2018-02-07 10:51:23 -07003066static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003067 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3068 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003069 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003070 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003071 return nullptr;
3072}
3073
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003074bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3075 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003076 bool skip = false;
3077 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003078
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06003079 if (disabled.shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003080 return false;
3081 }
3082
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003083 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003084
3085 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003086 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 -06003087 "VUID-VkShaderModuleCreateInfo-pCode-01376",
3088 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3089 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003090 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003091 auto cache = GetValidationCacheInfo(pCreateInfo);
3092 uint32_t hash = 0;
3093 if (cache) {
3094 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003095 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003096 }
3097
Chris Forbes4ae55b32017-06-09 14:42:56 -07003098 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06003099 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Mark Lobodzinski544def72019-04-19 14:25:59 -06003100 if (api_version >= VK_API_VERSION_1_1) {
Dave Houlton0ea2d012018-06-21 14:00:26 -06003101 spirv_environment = SPV_ENV_VULKAN_1_1;
3102 }
3103 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003104 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003105 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06003106 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003107 if (device_extensions.vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06003108 spvValidatorOptionsSetRelaxBlockLayout(options, true);
3109 }
Graeme Leese9b6a1522019-06-07 20:49:45 +01003110 if (device_extensions.vk_khr_uniform_buffer_standard_layout &&
3111 enabled_features.uniform_buffer_standard_layout.uniformBufferStandardLayout == VK_TRUE) {
3112 spvValidatorOptionsSetUniformBufferStandardLayout(options, true);
3113 }
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003114 if (device_extensions.vk_ext_scalar_block_layout &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003115 enabled_features.scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00003116 spvValidatorOptionsSetScalarBlockLayout(options, true);
3117 }
Karl Schultzfda1b382018-08-08 18:56:11 -06003118 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003119 if (spv_valid != SPV_SUCCESS) {
3120 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003121 skip |=
3122 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
3123 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
3124 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07003125 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003126 } else {
3127 if (cache) {
3128 cache->Insert(hash);
3129 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003130 }
3131
Karl Schultzfda1b382018-08-08 18:56:11 -06003132 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003133 spvDiagnosticDestroy(diag);
3134 spvContextDestroy(ctx);
3135 }
3136
Chris Forbes4ae55b32017-06-09 14:42:56 -07003137 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003138}
3139
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003140void CoreChecks::PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3141 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
3142 void *csm_state_data) {
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07003143 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06003144 if (enabled.gpu_validation) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07003145 GpuPreCallCreateShaderModule(pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
Mark Lobodzinski01734072019-02-13 17:39:15 -07003146 &csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
3147 }
3148}
3149
John Zulauf7eeb6f72019-06-17 11:56:36 -06003150void ValidationStateTracker::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3151 const VkAllocationCallbacks *pAllocator,
3152 VkShaderModule *pShaderModule, VkResult result,
3153 void *csm_state_data) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07003154 if (VK_SUCCESS != result) return;
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07003155 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003156
Mark Lobodzinski544def72019-04-19 14:25:59 -06003157 spv_target_env spirv_environment = ((api_version >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003158 bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003159 std::unique_ptr<SHADER_MODULE_STATE> new_shader_module(
3160 is_spirv ? new SHADER_MODULE_STATE(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
3161 : new SHADER_MODULE_STATE());
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003162 shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003163}
Lockeaa8fdc02019-04-02 11:59:20 -06003164
John Zulaufac4c6e12019-07-01 16:05:58 -06003165bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003166 bool skip = false;
3167 uint32_t local_size_x = 0;
3168 uint32_t local_size_y = 0;
3169 uint32_t local_size_z = 0;
3170 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3171 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003172 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3173 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3174 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
3175 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3176 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06003177 }
3178 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003179 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3180 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3181 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
3182 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3183 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06003184 }
3185 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003186 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3187 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3188 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
3189 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3190 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06003191 }
3192
3193 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
3194 uint64_t invocations = local_size_x * local_size_y;
3195 // Prevent overflow.
3196 bool fail = false;
3197 if (invocations > UINT32_MAX || invocations > limit) {
3198 fail = true;
3199 }
3200 if (!fail) {
3201 invocations *= local_size_z;
3202 if (invocations > UINT32_MAX || invocations > limit) {
3203 fail = true;
3204 }
3205 }
3206 if (fail) {
3207 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3208 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
locke-lunarg9edc2812019-06-17 23:18:52 -06003209 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
Lockeaa8fdc02019-04-02 11:59:20 -06003210 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
3211 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
3212 limit);
3213 }
3214 }
3215 return skip;
3216}