blob: dbbb67cc8c22c6fc6d3109e558f51d8a1410df03 [file] [log] [blame]
sfricke-samsung691299b2021-01-01 20:48:48 -08001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
Tobias Hector6663c9b2020-11-05 10:18:02 +00005 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Chris Forbes47567b72017-06-09 12:09:45 -07006 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060020 * Author: Dave Houlton <daveh@lunarg.com>
Tobias Hector6663c9b2020-11-05 10:18:02 +000021 * Author: Tobias Hector <tobias.hector@amd.com>
Chris Forbes47567b72017-06-09 12:09:45 -070022 */
23
Petr Kraus25810d02019-08-27 17:41:15 +020024#include "shader_validation.h"
25
Chris Forbes47567b72017-06-09 12:09:45 -070026#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020027#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060029#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070031#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <string>
33#include <unordered_map>
34#include <vector>
35
Mark Lobodzinski102687e2020-04-28 11:03:28 -060036#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_loader_platform.h"
38#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039#include "vk_layer_data.h"
40#include "vk_layer_extension_utils.h"
41#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070042#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070043#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020044
Chris Forbes4ae55b32017-06-09 14:42:56 -070045#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070046#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070047
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080048void decoration_set::add(uint32_t decoration, uint32_t value) {
49 switch (decoration) {
50 case spv::DecorationLocation:
51 flags |= location_bit;
52 location = value;
53 break;
54 case spv::DecorationPatch:
55 flags |= patch_bit;
56 break;
57 case spv::DecorationRelaxedPrecision:
58 flags |= relaxed_precision_bit;
59 break;
60 case spv::DecorationBlock:
61 flags |= block_bit;
62 break;
63 case spv::DecorationBufferBlock:
64 flags |= buffer_block_bit;
65 break;
66 case spv::DecorationComponent:
67 flags |= component_bit;
68 component = value;
69 break;
70 case spv::DecorationInputAttachmentIndex:
71 flags |= input_attachment_index_bit;
72 input_attachment_index = value;
73 break;
74 case spv::DecorationDescriptorSet:
75 flags |= descriptor_set_bit;
76 descriptor_set = value;
77 break;
78 case spv::DecorationBinding:
79 flags |= binding_bit;
80 binding = value;
81 break;
82 case spv::DecorationNonWritable:
83 flags |= nonwritable_bit;
84 break;
85 case spv::DecorationBuiltIn:
86 flags |= builtin_bit;
87 builtin = value;
88 break;
89 }
90}
91
Chris Forbes47567b72017-06-09 12:09:45 -070092enum FORMAT_TYPE {
93 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
94 FORMAT_TYPE_SINT = 2,
95 FORMAT_TYPE_UINT = 4,
96};
97
98typedef std::pair<unsigned, unsigned> location_t;
99
Chris Forbes47567b72017-06-09 12:09:45 -0700100static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
102 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
103 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
104 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
105 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700106};
107
John Zulauf14c355b2019-06-27 16:09:37 -0600108unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
109
Chris Forbes47567b72017-06-09 12:09:45 -0700110// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600111void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600112 function_set func_set = {};
113 EntryPoint *entry_point = nullptr;
114
Chris Forbes47567b72017-06-09 12:09:45 -0700115 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600116 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 if (func_set.offset) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600118 func_set.op_lists.insert({insn.opcode(), insn.offset()});
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700119 } else if (entry_point) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600120 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
121 }
122
Chris Forbes47567b72017-06-09 12:09:45 -0700123 switch (insn.opcode()) {
124 // Types
125 case spv::OpTypeVoid:
126 case spv::OpTypeBool:
127 case spv::OpTypeInt:
128 case spv::OpTypeFloat:
129 case spv::OpTypeVector:
130 case spv::OpTypeMatrix:
131 case spv::OpTypeImage:
132 case spv::OpTypeSampler:
133 case spv::OpTypeSampledImage:
134 case spv::OpTypeArray:
135 case spv::OpTypeRuntimeArray:
136 case spv::OpTypeStruct:
137 case spv::OpTypeOpaque:
138 case spv::OpTypePointer:
139 case spv::OpTypeFunction:
140 case spv::OpTypeEvent:
141 case spv::OpTypeDeviceEvent:
142 case spv::OpTypeReserveId:
143 case spv::OpTypeQueue:
144 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600145 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600146 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700147 def_index[insn.word(1)] = insn.offset();
148 break;
149
150 // Fixed constants
151 case spv::OpConstantTrue:
152 case spv::OpConstantFalse:
153 case spv::OpConstant:
154 case spv::OpConstantComposite:
155 case spv::OpConstantSampler:
156 case spv::OpConstantNull:
157 def_index[insn.word(2)] = insn.offset();
158 break;
159
160 // Specialization constants
161 case spv::OpSpecConstantTrue:
162 case spv::OpSpecConstantFalse:
163 case spv::OpSpecConstant:
164 case spv::OpSpecConstantComposite:
165 case spv::OpSpecConstantOp:
166 def_index[insn.word(2)] = insn.offset();
167 break;
168
169 // Variables
170 case spv::OpVariable:
171 def_index[insn.word(2)] = insn.offset();
172 break;
173
174 // Functions
175 case spv::OpFunction:
176 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600177 func_set.id = insn.word(2);
178 func_set.offset = insn.offset();
179 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700180 break;
181
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800182 // Decorations
183 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700184 auto target_id = insn.word(1);
185 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800186 } break;
187 case spv::OpGroupDecorate: {
188 auto const &src = decorations[insn.word(1)];
189 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
190 } break;
191
John Zulauf14c355b2019-06-27 16:09:37 -0600192 // Entry points ... add to the entrypoint table
193 case spv::OpEntryPoint: {
194 // Entry points do not have an id (the id is the function id) and thus need their own table
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700195 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600196 auto execution_model = insn.word(1);
197 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600198 entry_points.emplace(entrypoint_name,
199 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
200
201 auto range = entry_points.equal_range(entrypoint_name);
202 for (auto it = range.first; it != range.second; ++it) {
203 if (it->second.offset == insn.offset()) {
204 entry_point = &(it->second);
205 break;
206 }
207 }
208 assert(entry_point != nullptr);
209 break;
210 }
211 case spv::OpFunctionEnd: {
212 assert(entry_point != nullptr);
213 func_set.length = insn.offset() - func_set.offset;
214 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600215 break;
216 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800217
Chris Forbes47567b72017-06-09 12:09:45 -0700218 default:
219 // We don't care about any other defs for now.
220 break;
221 }
222 }
223}
224
Jeff Bolz105d6492018-09-29 15:46:44 -0500225unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
226 switch (mode) {
227 case spv::ExecutionModelVertex:
228 return VK_SHADER_STAGE_VERTEX_BIT;
229 case spv::ExecutionModelTessellationControl:
230 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
231 case spv::ExecutionModelTessellationEvaluation:
232 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
233 case spv::ExecutionModelGeometry:
234 return VK_SHADER_STAGE_GEOMETRY_BIT;
235 case spv::ExecutionModelFragment:
236 return VK_SHADER_STAGE_FRAGMENT_BIT;
237 case spv::ExecutionModelGLCompute:
238 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600239 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700240 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600241 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700242 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600243 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700244 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600245 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700246 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600247 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700248 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600249 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700250 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500251 case spv::ExecutionModelTaskNV:
252 return VK_SHADER_STAGE_TASK_BIT_NV;
253 case spv::ExecutionModelMeshNV:
254 return VK_SHADER_STAGE_MESH_BIT_NV;
255 default:
256 return 0;
257 }
258}
259
locke-lunargde3f0fa2020-09-10 11:55:31 -0600260const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
261 VkShaderStageFlagBits stageBits) {
262 auto range = src->entry_points.equal_range(name);
263 for (auto it = range.first; it != range.second; ++it) {
264 if (it->second.stage == stageBits) {
265 return &(it->second);
266 }
267 }
268 return nullptr;
269}
270
locke-lunargd9a069d2019-09-17 01:50:19 -0600271spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600272 auto range = src->entry_points.equal_range(name);
273 for (auto it = range.first; it != range.second; ++it) {
274 if (it->second.stage == stageBits) {
275 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700276 }
277 }
Chris Forbes47567b72017-06-09 12:09:45 -0700278 return src->end();
279}
280
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600281static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700282 switch (sc) {
283 case spv::StorageClassInput:
284 return "input";
285 case spv::StorageClassOutput:
286 return "output";
287 case spv::StorageClassUniformConstant:
288 return "const uniform";
289 case spv::StorageClassUniform:
290 return "uniform";
291 case spv::StorageClassWorkgroup:
292 return "workgroup local";
293 case spv::StorageClassCrossWorkgroup:
294 return "workgroup global";
295 case spv::StorageClassPrivate:
296 return "private global";
297 case spv::StorageClassFunction:
298 return "function";
299 case spv::StorageClassGeneric:
300 return "generic";
301 case spv::StorageClassAtomicCounter:
302 return "atomic counter";
303 case spv::StorageClassImage:
304 return "image";
305 case spv::StorageClassPushConstant:
306 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800307 case spv::StorageClassStorageBuffer:
308 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700309 default:
310 return "unknown";
311 }
312}
313
314// Get the value of an integral constant
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600315unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700316 auto value = src->get_def(id);
317 assert(value != src->end());
318
319 if (value.opcode() != spv::OpConstant) {
320 // TODO: Either ensure that the specialization transform is already performed on a module we're
321 // considering here, OR -- specialize on the fly now.
322 return 1;
323 }
324
325 return value.word(3);
326}
327
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600328static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700329 auto insn = src->get_def(type);
330 assert(insn != src->end());
331
332 switch (insn.opcode()) {
333 case spv::OpTypeBool:
334 ss << "bool";
335 break;
336 case spv::OpTypeInt:
337 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
338 break;
339 case spv::OpTypeFloat:
340 ss << "float" << insn.word(2);
341 break;
342 case spv::OpTypeVector:
343 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600344 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700345 break;
346 case spv::OpTypeMatrix:
347 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600348 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700349 break;
350 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600351 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
352 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700353 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700354 case spv::OpTypeRuntimeArray:
355 ss << "runtime arr[] of ";
356 DescribeTypeInner(ss, src, insn.word(2));
357 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700358 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600359 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
360 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700361 break;
362 case spv::OpTypeStruct: {
363 ss << "struct of (";
364 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600365 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700366 if (i == insn.len() - 1) {
367 ss << ")";
368 } else {
369 ss << ", ";
370 }
371 }
372 break;
373 }
374 case spv::OpTypeSampler:
375 ss << "sampler";
376 break;
377 case spv::OpTypeSampledImage:
378 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600379 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700380 break;
381 case spv::OpTypeImage:
382 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
383 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600384 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500385 ss << "accelerationStruture";
386 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700387 default:
388 ss << "oddtype";
389 break;
390 }
391}
392
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600393static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700394 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600395 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700396 return ss.str();
397}
398
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600399static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700400 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
401 return type.word(2) < 64;
402}
403
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600404static 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 -0600405 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700406 // Walk two type trees together, and complain about differences
407 auto a_insn = a->get_def(a_type);
408 auto b_insn = b->get_def(b_type);
409 assert(a_insn != a->end());
410 assert(b_insn != b->end());
411
Chris Forbes062f1222018-08-21 15:34:15 -0700412 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
413
Chris Forbes47567b72017-06-09 12:09:45 -0700414 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600415 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700416 }
417
418 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
419 // 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 -0600420 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700421 }
422
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600423 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
424 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700425 }
426
427 if (a_insn.opcode() != b_insn.opcode()) {
428 return false;
429 }
430
431 if (a_insn.opcode() == spv::OpTypePointer) {
432 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600433 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700434 }
435
436 if (a_arrayed || b_arrayed) {
437 // If we havent resolved array-of-verts by here, we're not going to.
438 return false;
439 }
440
441 switch (a_insn.opcode()) {
442 case spv::OpTypeBool:
443 return true;
444 case spv::OpTypeInt:
445 // Match on width, signedness
446 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
447 case spv::OpTypeFloat:
448 // Match on width
449 return a_insn.word(2) == b_insn.word(2);
450 case spv::OpTypeVector:
451 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600452 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
453 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700454 return a_insn.word(3) >= b_insn.word(3);
455 } else {
456 return a_insn.word(3) == b_insn.word(3);
457 }
458 case spv::OpTypeMatrix:
459 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600460 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700461 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700462 case spv::OpTypeArray:
463 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
464 // 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 -0600465 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
466 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700467 case spv::OpTypeStruct:
468 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700469 {
470 if (a_insn.len() != b_insn.len()) {
471 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700472 }
Chris Forbes47567b72017-06-09 12:09:45 -0700473
Dave Houltona9df0ce2018-02-07 10:51:23 -0700474 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600475 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700476 return false;
477 }
478 }
479
480 return true;
481 }
Chris Forbes47567b72017-06-09 12:09:45 -0700482 default:
483 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
484 return false;
485 }
486}
487
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600488static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700489 auto insn = src->get_def(type);
490 assert(insn != src->end());
491
492 switch (insn.opcode()) {
493 case spv::OpTypePointer:
494 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
495 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600496 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700497 case spv::OpTypeArray:
498 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600499 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700500 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600501 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700502 }
503 case spv::OpTypeMatrix:
504 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600505 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700506 case spv::OpTypeVector: {
507 auto scalar_type = src->get_def(insn.word(2));
508 auto bit_width =
509 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
510
511 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
512 return (bit_width * insn.word(3) + 127) / 128;
513 }
514 default:
515 // Everything else is just 1.
516 return 1;
517
518 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
519 }
520}
521
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600522static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200523 auto insn = src->get_def(type);
524 assert(insn != src->end());
525
526 switch (insn.opcode()) {
527 case spv::OpTypePointer:
528 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
529 // pointers around.
530 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
531 case spv::OpTypeStruct: {
532 uint32_t sum = 0;
533 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
534 sum += GetComponentsConsumedByType(src, insn.word(i), false);
535 }
536 return sum;
537 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500538 case spv::OpTypeArray:
539 if (strip_array_level) {
540 return GetComponentsConsumedByType(src, insn.word(2), false);
541 } else {
542 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200543 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200544 case spv::OpTypeMatrix:
545 // Num locations is the dimension * element size
546 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
547 case spv::OpTypeVector: {
548 auto scalar_type = src->get_def(insn.word(2));
549 auto bit_width =
550 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
551 // One component is 32-bit
552 return (bit_width * insn.word(3) + 31) / 32;
553 }
554 case spv::OpTypeFloat: {
555 auto bit_width = insn.word(2);
556 return (bit_width + 31) / 32;
557 }
558 case spv::OpTypeInt: {
559 auto bit_width = insn.word(2);
560 return (bit_width + 31) / 32;
561 }
562 case spv::OpConstant:
563 return GetComponentsConsumedByType(src, insn.word(1), false);
564 default:
565 return 0;
566 }
567}
568
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600569static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700570 switch (format) {
571 case VK_FORMAT_R64G64B64A64_SFLOAT:
572 case VK_FORMAT_R64G64B64A64_SINT:
573 case VK_FORMAT_R64G64B64A64_UINT:
574 case VK_FORMAT_R64G64B64_SFLOAT:
575 case VK_FORMAT_R64G64B64_SINT:
576 case VK_FORMAT_R64G64B64_UINT:
577 return 2;
578 default:
579 return 1;
580 }
581}
582
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600583static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700584 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
585 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
586 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
587 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700588 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
589 return FORMAT_TYPE_FLOAT;
590}
591
592// 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 -0700593// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600594static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700595 auto insn = src->get_def(type);
596 assert(insn != src->end());
597
598 switch (insn.opcode()) {
599 case spv::OpTypeInt:
600 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
601 case spv::OpTypeFloat:
602 return FORMAT_TYPE_FLOAT;
603 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700604 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700605 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700606 case spv::OpTypeRuntimeArray:
607 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600608 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700609 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600610 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700611
612 default:
613 return 0;
614 }
615}
616
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600617static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700618 uint32_t bit_pos = uint32_t(u_ffs(stage));
619 return bit_pos - 1;
620}
621
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600622static 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 -0700623 while (true) {
624 if (def.opcode() == spv::OpTypePointer) {
625 def = src->get_def(def.word(3));
626 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
627 def = src->get_def(def.word(2));
628 is_array_of_verts = false;
629 } else if (def.opcode() == spv::OpTypeStruct) {
630 return def;
631 } else {
632 return src->end();
633 }
634 }
635}
636
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600637static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800638 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
639 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700640 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600641 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800642 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700643 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700644 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700645 }
646
647 std::unordered_map<unsigned, unsigned> member_components;
648 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700649 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700650
651 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
652 for (auto insn : *src) {
653 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
654 unsigned member_index = insn.word(2);
655
656 if (insn.word(3) == spv::DecorationComponent) {
657 unsigned component = insn.word(4);
658 member_components[member_index] = component;
659 }
660
661 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
662 member_relaxed_precision[member_index] = 1;
663 }
Chris Forbesa313d772017-06-13 13:59:41 -0700664
665 if (insn.word(3) == spv::DecorationPatch) {
666 member_patch[member_index] = 1;
667 }
Chris Forbes47567b72017-06-09 12:09:45 -0700668 }
669 }
670
Chris Forbesa313d772017-06-13 13:59:41 -0700671 // TODO: correctly handle location assignment from outside
672
Chris Forbes47567b72017-06-09 12:09:45 -0700673 // Second pass -- produce the output, from Location decorations
674 for (auto insn : *src) {
675 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
676 unsigned member_index = insn.word(2);
677 unsigned member_type_id = type.word(2 + member_index);
678
679 if (insn.word(3) == spv::DecorationLocation) {
680 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600681 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700682 auto component_it = member_components.find(member_index);
683 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
684 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700685 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700686
687 for (unsigned int offset = 0; offset < num_locations; offset++) {
688 interface_var v = {};
689 v.id = id;
690 // TODO: member index in interface_var too?
691 v.type_id = member_type_id;
692 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700693 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700694 v.is_block_member = true;
695 v.is_relaxed_precision = is_relaxed_precision;
696 (*out)[std::make_pair(location + offset, component)] = v;
697 }
698 }
699 }
700 }
Chris Forbesa313d772017-06-13 13:59:41 -0700701
702 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700703}
704
Ari Suonpaa696b3432019-03-11 14:02:57 +0200705static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800706 assert(entrypoint.opcode() == spv::OpEntryPoint);
707
Ari Suonpaa696b3432019-03-11 14:02:57 +0200708 std::vector<uint32_t> interfaces;
709 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
710 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
711 uint32_t word = 3;
712 while (entrypoint.word(word) & 0xff000000u) {
713 ++word;
714 }
715 ++word;
716
717 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
718
719 return interfaces;
720}
721
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600722static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600723 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700724 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
725
Chris Forbes47567b72017-06-09 12:09:45 -0700726 std::map<location_t, interface_var> out;
727
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800728 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
729 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700730 assert(insn != src->end());
731 assert(insn.opcode() == spv::OpVariable);
732
733 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800734 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700735 unsigned id = insn.word(2);
736 unsigned type = insn.word(1);
737
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800738 int location = d.location;
739 int builtin = d.builtin;
740 unsigned component = d.component;
741 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
742 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700743
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700744 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700745 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700746 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700747 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
748 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600749 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700750 for (unsigned int offset = 0; offset < num_locations; offset++) {
751 interface_var v = {};
752 v.id = id;
753 v.type_id = type;
754 v.offset = offset;
755 v.is_patch = is_patch;
756 v.is_relaxed_precision = is_relaxed_precision;
757 out[std::make_pair(location + offset, component)] = v;
758 }
Chris Forbes47567b72017-06-09 12:09:45 -0700759 }
760 }
761 }
762
763 return out;
764}
765
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600766static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200767 uint32_t storageClass) {
768 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700769 std::vector<uint32_t> builtin_struct_members;
770 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200771
772 for (auto insn : *src) {
773 switch (insn.opcode()) {
774 // Find all built-in member decorations
775 case spv::OpMemberDecorate:
776 if (insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700777 builtin_struct_members.push_back(insn.word(1));
Ari Suonpaa696b3432019-03-11 14:02:57 +0200778 }
779 break;
780 // Find all built-in decorations
781 case spv::OpDecorate:
782 switch (insn.word(2)) {
783 case spv::DecorationBlock: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700784 uint32_t block_id = insn.word(1);
785 for (auto built_in_block_id : builtin_struct_members) {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200786 // Check if one of the members of the block are built-in -> the block is built-in
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700787 if (block_id == built_in_block_id) {
788 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200789 break;
790 }
791 }
792 break;
793 }
794 case spv::DecorationBuiltIn:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700795 builtin_decorations.push_back(insn.word(1));
Ari Suonpaa696b3432019-03-11 14:02:57 +0200796 break;
797 default:
798 break;
799 }
800 break;
801 default:
802 break;
803 }
804 }
805
806 // Find all interface variables belonging to the entrypoint and matching the storage class
807 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
808 auto def = src->get_def(id);
809 assert(def != src->end());
810 assert(def.opcode() == spv::OpVariable);
811
812 if (def.word(3) == storageClass) variables.push_back(def.word(1));
813 }
814
815 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700816 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200817 for (auto &var : variables) {
818 auto def = src->get_def(src->get_def(var).word(3));
819
820 // It could be an array of IO blocks. The element type should be the struct defining the block contents
821 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
822
823 // Now find all members belonging to the struct defining the IO block
824 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700825 for (auto built_in_id : builtin_decorations) {
826 if (built_in_id == def.word(1)) {
827 for (int i = 2; i < static_cast<int>(def.len()); i++) {
828 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
829 }
830 // These shouldn't be left after replacing.
Ari Suonpaa696b3432019-03-11 14:02:57 +0200831 for (auto insn : *src) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700832 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == built_in_id &&
Ari Suonpaa696b3432019-03-11 14:02:57 +0200833 insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700834 auto struct_index = insn.word(2);
835 assert(struct_index < builtin_block_members.size());
836 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200837 }
838 }
839 }
840 }
841 }
842 }
843
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700844 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200845}
846
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600847static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600848 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700849 std::vector<std::pair<uint32_t, interface_var>> out;
850
851 for (auto insn : *src) {
852 if (insn.opcode() == spv::OpDecorate) {
853 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
854 auto attachment_index = insn.word(3);
855 auto id = insn.word(1);
856
857 if (accessible_ids.count(id)) {
858 auto def = src->get_def(id);
859 assert(def != src->end());
locke-lunarg9a16ebb2020-07-30 16:56:33 -0600860 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600861 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700862 for (unsigned int offset = 0; offset < num_locations; offset++) {
863 interface_var v = {};
864 v.id = id;
865 v.type_id = def.word(1);
866 v.offset = offset;
867 out.emplace_back(attachment_index + offset, v);
868 }
869 }
870 }
871 }
872 }
873 }
874
875 return out;
876}
877
locke-lunarg25b6c352020-08-06 17:44:18 -0600878static bool AtomicOperation(uint32_t opcode) {
879 switch (opcode) {
880 case spv::OpAtomicLoad:
881 case spv::OpAtomicStore:
882 case spv::OpAtomicExchange:
883 case spv::OpAtomicCompareExchange:
884 case spv::OpAtomicCompareExchangeWeak:
885 case spv::OpAtomicIIncrement:
886 case spv::OpAtomicIDecrement:
887 case spv::OpAtomicIAdd:
888 case spv::OpAtomicISub:
889 case spv::OpAtomicSMin:
890 case spv::OpAtomicUMin:
891 case spv::OpAtomicSMax:
892 case spv::OpAtomicUMax:
893 case spv::OpAtomicAnd:
894 case spv::OpAtomicOr:
895 case spv::OpAtomicXor:
896 case spv::OpAtomicFAddEXT:
897 return true;
898 default:
899 return false;
900 }
901 return false;
902}
903
sfricke-samsung0065ce02020-12-03 22:46:37 -0800904// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
905// covered with VUID 01090
906static bool GroupOperation(uint32_t opcode) {
907 switch (opcode) {
908 case spv::OpGroupNonUniformElect:
909 case spv::OpGroupNonUniformAll:
910 case spv::OpGroupNonUniformAny:
911 case spv::OpGroupNonUniformAllEqual:
912 case spv::OpGroupNonUniformBroadcast:
913 case spv::OpGroupNonUniformBroadcastFirst:
914 case spv::OpGroupNonUniformBallot:
915 case spv::OpGroupNonUniformInverseBallot:
916 case spv::OpGroupNonUniformBallotBitExtract:
917 case spv::OpGroupNonUniformBallotBitCount:
918 case spv::OpGroupNonUniformBallotFindLSB:
919 case spv::OpGroupNonUniformBallotFindMSB:
920 case spv::OpGroupNonUniformShuffle:
921 case spv::OpGroupNonUniformShuffleXor:
922 case spv::OpGroupNonUniformShuffleUp:
923 case spv::OpGroupNonUniformShuffleDown:
924 case spv::OpGroupNonUniformIAdd:
925 case spv::OpGroupNonUniformFAdd:
926 case spv::OpGroupNonUniformIMul:
927 case spv::OpGroupNonUniformFMul:
928 case spv::OpGroupNonUniformSMin:
929 case spv::OpGroupNonUniformUMin:
930 case spv::OpGroupNonUniformFMin:
931 case spv::OpGroupNonUniformSMax:
932 case spv::OpGroupNonUniformUMax:
933 case spv::OpGroupNonUniformFMax:
934 case spv::OpGroupNonUniformBitwiseAnd:
935 case spv::OpGroupNonUniformBitwiseOr:
936 case spv::OpGroupNonUniformBitwiseXor:
937 case spv::OpGroupNonUniformLogicalAnd:
938 case spv::OpGroupNonUniformLogicalOr:
939 case spv::OpGroupNonUniformLogicalXor:
940 case spv::OpGroupNonUniformQuadBroadcast:
941 case spv::OpGroupNonUniformQuadSwap:
942 case spv::OpGroupNonUniformPartitionNV:
943 return true;
944 default:
945 return false;
946 }
947 return false;
948}
949
locke-lunarg12d20992020-09-21 12:46:49 -0600950bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
951 const std::unordered_map<unsigned, unsigned> &load_members,
952 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
953 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600954 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600955 auto load_it = load_members.find(load_id);
956 if (load_it == load_members.end()) {
957 continue;
958 }
959 if (load_it->second == object_id) {
960 return true;
961 }
962
963 auto accesschain_it = accesschain_members.find(load_it->second);
964 if (accesschain_it == accesschain_members.end()) {
965 continue;
966 }
967 if (accesschain_it->second.first == object_id) {
968 return true;
969 }
970 }
971 return false;
972}
973
locke-lunargae2a43c2020-09-22 17:21:57 -0600974bool CheckImageOperandsBiasOffset(uint32_t type) {
975 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
976 spv::ImageOperandsConstOffsetsMask)
977 ? true
978 : false;
979}
980
locke-lunargd3da0422020-09-23 01:02:11 -0600981struct shader_module_used_operators {
982 bool updated;
983 std::vector<unsigned> imagwrite_members;
984 std::vector<unsigned> atomic_members;
985 std::vector<unsigned> store_members;
986 std::vector<unsigned> atomic_store_members;
987 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
988 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -0800989 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
locke-lunargd3da0422020-09-23 01:02:11 -0600990 std::unordered_map<unsigned, unsigned> load_members;
991 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
992 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
993
994 shader_module_used_operators() : updated(false) {}
995
996 void update(SHADER_MODULE_STATE const *module) {
997 if (updated) return;
998 updated = true;
999
1000 for (auto insn : *module) {
1001 switch (insn.opcode()) {
1002 case spv::OpImageSampleImplicitLod:
1003 case spv::OpImageSampleProjImplicitLod:
1004 case spv::OpImageSampleProjExplicitLod:
1005 case spv::OpImageSparseSampleImplicitLod:
1006 case spv::OpImageSparseSampleProjImplicitLod:
1007 case spv::OpImageSparseSampleProjExplicitLod: {
1008 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1009 // ImageOperands in index: 5
1010 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1011 sampler_bias_offset_members.emplace_back(insn.word(3));
1012 }
1013 break;
1014 }
1015 case spv::OpImageSampleDrefImplicitLod:
1016 case spv::OpImageSampleDrefExplicitLod:
1017 case spv::OpImageSampleProjDrefImplicitLod:
1018 case spv::OpImageSampleProjDrefExplicitLod:
1019 case spv::OpImageSparseSampleDrefImplicitLod:
1020 case spv::OpImageSparseSampleDrefExplicitLod:
1021 case spv::OpImageSparseSampleProjDrefImplicitLod:
1022 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1023 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1024 // ImageOperands in index: 6
1025 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1026 sampler_bias_offset_members.emplace_back(insn.word(3));
1027 }
1028 break;
1029 }
1030 case spv::OpImageSampleExplicitLod:
1031 case spv::OpImageSparseSampleExplicitLod: {
1032 // ImageOperands in index: 5
1033 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1034 sampler_bias_offset_members.emplace_back(insn.word(3));
1035 }
1036 break;
1037 }
1038 case spv::OpStore: {
1039 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1040 break;
1041 }
1042 case spv::OpImageWrite: {
1043 imagwrite_members.emplace_back(insn.word(1)); // Load id
1044 break;
1045 }
1046 case spv::OpSampledImage: {
1047 // 3: image load id, 4: sampler load id
1048 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1049 break;
1050 }
1051 case spv::OpLoad: {
1052 // 2: Load id, 3: object id or AccessChain id
1053 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1054 break;
1055 }
1056 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001057 if (insn.len() == 4) {
1058 // If it is for struct, the length is only 4.
1059 // 2: AccessChain id, 3: object id
1060 accesschain_members.insert(std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0)));
1061 } else {
1062 // 2: AccessChain id, 3: object id, 4: object id of array index
1063 accesschain_members.insert(
1064 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1065 }
locke-lunargd3da0422020-09-23 01:02:11 -06001066 break;
1067 }
1068 case spv::OpImageTexelPointer: {
1069 // 2: ImageTexelPointer id, 3: object id
1070 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1071 break;
1072 }
1073 default: {
1074 if (AtomicOperation(insn.opcode())) {
1075 if (insn.opcode() == spv::OpAtomicStore) {
1076 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1077 } else {
1078 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1079 }
1080 }
1081 break;
1082 }
1083 }
1084 }
1085 }
1086};
1087
sfricke-samsung691299b2021-01-01 20:48:48 -08001088// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1089// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001090static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001091 bool is_check_writable, interface_var &out_interface_var,
1092 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001093 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001094 unsigned int id = id_it.word(2);
1095
Chris Forbes8af24522018-03-07 11:37:45 -08001096 auto type = module->get_def(type_id);
1097
1098 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
locke-lunarg12d20992020-09-21 12:46:49 -06001099 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1100 type.opcode() == spv::OpTypeSampledImage) {
1101 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1102 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001103 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001104 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001105 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001106 }
1107 }
Chris Forbes8af24522018-03-07 11:37:45 -08001108 switch (type.opcode()) {
1109 case spv::OpTypeImage: {
1110 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001111 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001112 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001113
locke-lunargd3da0422020-09-23 01:02:11 -06001114 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1115 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001116 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001117 }
1118 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1119 used_operators.accesschain_members)) {
1120 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001121 }
locke-lunargd3da0422020-09-23 01:02:11 -06001122 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1123 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001124 out_interface_var.is_sampler_bias_offset = true;
1125 }
locke-lunargd3da0422020-09-23 01:02:11 -06001126 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1127 used_operators.accesschain_members) ||
1128 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1129 used_operators.accesschain_members)) {
1130 out_interface_var.is_atomic_operation = true;
1131 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001132
locke-lunargd3da0422020-09-23 01:02:11 -06001133 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001134 // Find if image id match.
1135 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001136 auto load_it = used_operators.load_members.find(itp_id.first);
1137 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001138 continue;
1139 } else {
1140 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001141 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1142 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001143 continue;
1144 } else {
1145 if (accesschain_it->second.first != id) {
1146 continue;
1147 }
locke-lunarg025daa72020-10-13 11:07:51 -06001148 if (used_operators.load_members.end() !=
1149 used_operators.load_members.find(accesschain_it->second.second)) {
1150 // image_index isn't a constant, skip.
1151 break;
1152 }
locke-lunarg36045992020-08-20 16:54:37 -06001153 image_index = GetConstantValue(module, accesschain_it->second.second);
1154 }
1155 }
1156 }
1157 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001158 load_it = used_operators.load_members.find(itp_id.second);
1159 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001160 continue;
1161 } else {
1162 uint32_t sampler_id = load_it->second;
1163 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001164 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1165 if (accesschain_it != used_operators.accesschain_members.end()) {
locke-lunarg025daa72020-10-13 11:07:51 -06001166 if (used_operators.load_members.end() !=
1167 used_operators.load_members.find(accesschain_it->second.second)) {
1168 // sampler_index isn't a constant, skip.
1169 break;
1170 }
locke-lunarg36045992020-08-20 16:54:37 -06001171 sampler_id = accesschain_it->second.first;
1172 sampler_index = GetConstantValue(module, accesschain_it->second.second);
1173 }
1174 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001175 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1176 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1177 }
1178 out_interface_var.samplers_used_by_image[image_index].emplace(
1179 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001180 }
1181 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001182 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001183 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001184 }
1185
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001186 case spv::OpTypeStruct: {
1187 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001188 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -08001189 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001190 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
1191 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001192 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001193 }
1194 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001195
1196 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1197 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001198 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001199 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001200
locke-lunargd3da0422020-09-23 01:02:11 -06001201 for (auto oid : used_operators.store_members) {
1202 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001203 out_interface_var.is_writable = true;
1204 return;
1205 }
locke-lunargd3da0422020-09-23 01:02:11 -06001206 auto accesschain_it = used_operators.accesschain_members.find(oid);
1207 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001208 continue;
1209 }
locke-lunargd3da0422020-09-23 01:02:11 -06001210 if (accesschain_it->second.first == id) {
1211 out_interface_var.is_writable = true;
1212 return;
1213 }
1214 }
1215 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1216 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001217 out_interface_var.is_writable = true;
1218 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001219 }
1220 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001221 }
Chris Forbes8af24522018-03-07 11:37:45 -08001222 }
Chris Forbes8af24522018-03-07 11:37:45 -08001223}
1224
locke-lunargd9a069d2019-09-17 01:50:19 -06001225std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001226 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1227 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001228 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001229 shader_module_used_operators operators;
1230
Chris Forbes47567b72017-06-09 12:09:45 -07001231 for (auto id : accessible_ids) {
1232 auto insn = src->get_def(id);
1233 assert(insn != src->end());
1234
1235 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001236 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1237 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001238 auto d = src->get_decorations(insn.word(2));
1239 unsigned set = d.descriptor_set;
1240 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001241
1242 interface_var v = {};
1243 v.id = insn.word(2);
1244 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001245
locke-lunarg25b6c352020-08-06 17:44:18 -06001246 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001247 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001248 if (v.is_writable) *has_writable_descriptor = true;
1249 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001250 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001251 }
1252 }
1253
1254 return out;
1255}
1256
locke-lunargde3f0fa2020-09-10 11:55:31 -06001257void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1258 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1259 const auto struct_it = GetStructType(&src, it, false);
1260 assert(struct_it != src.end());
1261 data.size = 0;
1262
1263 shader_struct_member data1;
1264 uint32_t i = 2;
1265 uint32_t local_offset = 0;
1266 std::vector<uint32_t> offsets;
1267 offsets.resize(struct_it.len() - i);
1268
1269 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1270 for (const auto offset : memberDecorate_offsets) {
1271 const auto member_decorate = src.at(offset);
1272 if (member_decorate.word(1) != struct_it.word(1)) {
1273 continue;
1274 }
1275
1276 offsets[member_decorate.word(2)] = member_decorate.word(4);
1277 }
1278
1279 for (const auto offset : offsets) {
1280 local_offset = offset;
1281 data1 = {};
1282 data1.root = data.root;
1283 data1.offset = local_offset;
1284 auto def_member = src.get_def(struct_it.word(i));
1285
1286 // Array could be multi-dimensional
1287 while (def_member.opcode() == spv::OpTypeArray) {
1288 const auto len_id = def_member.word(3);
1289 const auto def_len = src.get_def(len_id);
1290 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1291 def_member = src.get_def(def_member.word(2));
1292 }
1293
1294 if (def_member.opcode() == spv::OpTypeStruct || def_member.opcode() == spv::OpTypePointer) {
1295 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1296 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1297 } else {
1298 if (def_member.opcode() == spv::OpTypeMatrix) {
1299 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1300 def_member = src.get_def(def_member.word(2));
1301 }
1302
1303 if (def_member.opcode() == spv::OpTypeVector) {
1304 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1305 def_member = src.get_def(def_member.word(2));
1306 }
1307
1308 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1309 data1.size = (def_member.word(2) / 8);
1310 }
1311 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1312 if (array_length_hierarchy_szie > 0) {
1313 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1314
1315 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1316 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1317 }
1318 }
1319 data.struct_members.emplace_back(data1);
1320 ++i;
1321 }
1322 uint32_t total_array_length = 1;
1323 for (const auto length : data1.array_length_hierarchy) {
1324 total_array_length *= length;
1325 }
1326 data.size = local_offset + data1.size * total_array_length;
1327}
1328
1329uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1330 int array_indices_size = static_cast<int>(array_indices.size());
1331 if (array_indices_size) {
1332 uint32_t array_index = 0;
1333 uint32_t i = 0;
1334 for (const auto index : array_indices) {
1335 array_index += (data.array_block_size[i] * index);
1336 ++i;
1337 }
1338 offset += (array_index * data.size);
1339 }
1340 return offset;
1341}
1342
1343void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1344 int array_indices_size = static_cast<int>(array_indices.size());
1345 uint32_t block_memory_size = data.size;
1346 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1347 block_memory_size *= data.array_length_hierarchy[i];
1348 }
1349
1350 offset = UpdateOffset(offset, array_indices, data);
1351
1352 uint32_t end = offset + block_memory_size;
1353 auto used_bytes = data.GetUsedbytes();
1354 if (used_bytes->size() < end) {
1355 used_bytes->resize(end, 0);
1356 }
1357 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1358}
1359
1360void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1361 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1362 if (access_chain_word_index < access_chain_it.len()) {
1363 if (data.array_length_hierarchy.size() > array_indices.size()) {
1364 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1365 ++access_chain_word_index;
1366
1367 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1368 array_indices.emplace_back(def_it.word(3));
1369 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1370 } else {
1371 // If it is a variable, set the all array is used.
1372 if (access_chain_word_index < access_chain_it.len()) {
1373 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1374 for (uint32_t i = 0; i < array_length; ++i) {
1375 auto array_indices2 = array_indices;
1376 array_indices2.emplace_back(i);
1377 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1378 }
1379 } else {
1380 SetUsedBytes(offset, array_indices, data);
1381 }
1382 }
1383 } else {
1384 offset = UpdateOffset(offset, array_indices, data);
1385 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1386 }
1387 } else {
1388 SetUsedBytes(offset, array_indices, data);
1389 }
1390}
1391
1392void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1393 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1394 std::vector<uint32_t> array_indices_emptry;
1395
1396 if (access_chain_word_index < access_chain_it.len()) {
1397 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1398 ++access_chain_word_index;
1399
1400 auto data1 = data.struct_members[strcut_member_index];
1401 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1402 }
1403}
1404
1405void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1406 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1407 for (const auto &func_set : function_set_list) {
1408 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1409 for (auto it = range.first; it != range.second; ++it) {
1410 auto access_chain = src.at(it->second);
1411 if (access_chain.word(3) == variable_id) {
1412 RunUsedStruct(src, 0, 4, access_chain, data);
1413 }
1414 }
1415 }
1416}
1417
1418void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1419 for (auto &entrypoint : src.entry_points) {
1420 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1421 for (auto it = range.first; it != range.second; ++it) {
1422 const auto def_insn = src.at(it->second);
1423
1424 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1425 spirv_inst_iter type = src.get_def(def_insn.word(1));
1426 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1427 std::vector<uint32_t> offsets;
1428
1429 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1430 auto member_decorate = src.at(it2->second);
1431 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1432 offsets.emplace_back(member_decorate.offset());
1433 }
1434 }
1435 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1436 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1437 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1438 entrypoint.second.push_constant_used_in_shader);
1439 }
1440 }
1441 }
1442}
1443
locke-lunarg96dc9632020-06-10 17:22:18 -06001444std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1445 const VkPipelineShaderStageCreateInfo &stage_info) {
1446 std::unordered_set<uint32_t> location_list;
1447 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1448 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1449 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1450 std::unordered_set<unsigned> store_members;
1451 std::unordered_map<unsigned, unsigned> accesschain_members;
1452
1453 for (auto insn : module) {
1454 switch (insn.opcode()) {
1455 case spv::OpStore:
1456 case spv::OpAtomicStore: {
1457 store_members.insert(insn.word(1)); // object id or AccessChain id
1458 break;
1459 }
1460 case spv::OpAccessChain: {
1461 // 2: AccessChain id, 3: object id
1462 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1463 break;
1464 }
1465 default:
1466 break;
1467 }
1468 }
1469 if (store_members.empty()) {
1470 return location_list;
1471 }
1472 for (auto output : outputs) {
1473 auto store_it = store_members.find(output.second.id);
1474 if (store_it != store_members.end()) {
1475 location_list.insert(output.first.first);
1476 store_members.erase(store_it);
1477 continue;
1478 }
1479 store_it = store_members.begin();
1480 while (store_it != store_members.end()) {
1481 auto accesschain_it = accesschain_members.find(*store_it);
1482 if (accesschain_it == accesschain_members.end()) {
1483 ++store_it;
1484 continue;
1485 }
1486 if (accesschain_it->second == output.second.id) {
1487 location_list.insert(output.first.first);
1488 store_members.erase(store_it);
1489 accesschain_members.erase(accesschain_it);
1490 break;
1491 }
1492 ++store_it;
1493 }
1494 }
1495 return location_list;
1496}
1497
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001498bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001499 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1500 // be specified only once.
1501 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1502 bool skip = false;
1503
1504 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1505 auto desc = &vi->pVertexBindingDescriptions[i];
1506 auto &binding = bindings[desc->binding];
1507 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001508 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001509 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1510 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001511 } else {
1512 binding = desc;
1513 }
1514 }
1515
1516 return skip;
1517}
1518
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001519bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1520 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001521 bool skip = false;
1522
Petr Kraus25810d02019-08-27 17:41:15 +02001523 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001524
1525 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001526 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001527 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001528 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1529 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1530 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001531 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1532 }
1533 }
1534 }
1535
Petr Kraus25810d02019-08-27 17:41:15 +02001536 struct AttribInputPair {
1537 const VkVertexInputAttributeDescription *attrib = nullptr;
1538 const interface_var *input = nullptr;
1539 };
1540 std::map<uint32_t, AttribInputPair> location_map;
1541 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1542 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001543
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001544 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001545 const auto location = location_it.first;
1546 const auto attrib = location_it.second.attrib;
1547 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001548
Petr Kraus25810d02019-08-27 17:41:15 +02001549 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001550 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1551 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001552 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001553 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1554 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001555 } else if (attrib && input) {
1556 const auto attrib_type = GetFormatType(attrib->format);
1557 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001558
1559 // Type checking
1560 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001561 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1562 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1563 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001564 }
Petr Kraus25810d02019-08-27 17:41:15 +02001565 } else { // !attrib && !input
1566 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001567 }
1568 }
1569
1570 return skip;
1571}
1572
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001573bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1574 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001575 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001576
Petr Kraus25810d02019-08-27 17:41:15 +02001577 const auto rpci = pipeline->rp_state->createInfo.ptr();
1578
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001579 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001580 const VkAttachmentReference2 *reference = nullptr;
1581 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001582 const interface_var *output = nullptr;
1583 };
1584 std::map<uint32_t, Attachment> location_map;
1585
Petr Kraus25810d02019-08-27 17:41:15 +02001586 const auto subpass = rpci->pSubpasses[subpass_index];
1587 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001588 auto const &reference = subpass.pColorAttachments[i];
1589 location_map[i].reference = &reference;
1590 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1591 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1592 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001593 }
1594 }
1595
Chris Forbes47567b72017-06-09 12:09:45 -07001596 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1597
Petr Kraus25810d02019-08-27 17:41:15 +02001598 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001599 for (const auto &output_it : outputs) {
1600 auto const location = output_it.first.first;
1601 location_map[location].output = &output_it.second;
1602 }
Chris Forbes47567b72017-06-09 12:09:45 -07001603
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001604 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1605 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001606
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001607 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001608 const auto reference = location_it.second.reference;
1609 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1610 continue;
1611 }
1612
Petr Kraus25810d02019-08-27 17:41:15 +02001613 const auto location = location_it.first;
1614 const auto attachment = location_it.second.attachment;
1615 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001616 if (attachment && !output) {
1617 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001618 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1619 "Attachment %" PRIu32
1620 " not written by fragment shader; undefined values will be written to attachment",
1621 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001622 }
1623 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001624 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001625 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1626 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001627 }
Petr Kraus25810d02019-08-27 17:41:15 +02001628 } else if (attachment && output) {
1629 const auto attachment_type = GetFormatType(attachment->format);
1630 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001631
1632 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001633 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001634 skip |=
1635 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1636 "Attachment %" PRIu32
1637 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1638 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001639 }
Petr Kraus25810d02019-08-27 17:41:15 +02001640 } else { // !attachment && !output
1641 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001642 }
1643 }
1644
Petr Kraus25810d02019-08-27 17:41:15 +02001645 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001646 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1647 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1648 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001649 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1650 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001651 }
1652
Chris Forbes47567b72017-06-09 12:09:45 -07001653 return skip;
1654}
1655
Tobias Hector6663c9b2020-11-05 10:18:02 +00001656// For some built-in analysis we need to know if the variable decorated with as the built-in was actually written to.
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001657// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001658static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001659 auto type = builtin_instr.opcode();
1660 uint32_t target_id = builtin_instr.word(1);
1661 bool init_complete = false;
1662
1663 if (type == spv::OpMemberDecorate) {
1664 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1665 auto insn = entrypoint;
1666 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1667 switch (insn.opcode()) {
1668 case spv::OpTypePointer:
1669 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1670 target_id = insn.word(1);
1671 }
1672 break;
1673 case spv::OpVariable:
1674 if (insn.word(1) == target_id) {
1675 target_id = insn.word(2);
1676 init_complete = true;
1677 }
1678 break;
1679 }
1680 insn++;
1681 }
1682 }
1683
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001684 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1685
1686 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001687 std::unordered_set<uint32_t> worklist;
1688 worklist.insert(entrypoint.word(2));
1689
1690 // Follow instructions in call graph looking for writes to target
1691 while (!worklist.empty() && !found_write) {
1692 auto id_iter = worklist.begin();
1693 auto id = *id_iter;
1694 worklist.erase(id_iter);
1695
1696 auto insn = src->get_def(id);
1697 if (insn == src->end()) {
1698 continue;
1699 }
1700
1701 if (insn.opcode() == spv::OpFunction) {
1702 // Scan body of function looking for other function calls or items in our ID chain
1703 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1704 switch (insn.opcode()) {
1705 case spv::OpAccessChain:
1706 if (insn.word(3) == target_id) {
1707 if (type == spv::OpMemberDecorate) {
1708 auto value = GetConstantValue(src, insn.word(4));
1709 if (value == builtin_instr.word(2)) {
1710 target_id = insn.word(2);
1711 }
1712 } else {
1713 target_id = insn.word(2);
1714 }
1715 }
1716 break;
1717 case spv::OpStore:
1718 if (insn.word(1) == target_id) {
1719 found_write = true;
1720 }
1721 break;
1722 case spv::OpFunctionCall:
1723 worklist.insert(insn.word(3));
1724 break;
1725 }
1726 }
1727 }
1728 }
1729 return found_write;
1730}
1731
Chris Forbes47567b72017-06-09 12:09:45 -07001732// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1733// important for identifying the set of shader resources actually used by an entrypoint, for example.
1734// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1735// - NOT the shader input/output interfaces.
1736//
1737// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1738// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001739std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001740 std::unordered_set<uint32_t> ids;
1741 std::unordered_set<uint32_t> worklist;
1742 worklist.insert(entrypoint.word(2));
1743
1744 while (!worklist.empty()) {
1745 auto id_iter = worklist.begin();
1746 auto id = *id_iter;
1747 worklist.erase(id_iter);
1748
1749 auto insn = src->get_def(id);
1750 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001751 // 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 -07001752 // that we may not care about.
1753 continue;
1754 }
1755
1756 // Try to add to the output set
1757 if (!ids.insert(id).second) {
1758 continue; // If we already saw this id, we don't want to walk it again.
1759 }
1760
1761 switch (insn.opcode()) {
1762 case spv::OpFunction:
1763 // Scan whole body of the function, enlisting anything interesting
1764 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1765 switch (insn.opcode()) {
1766 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001767 worklist.insert(insn.word(3)); // ptr
1768 break;
1769 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001770 worklist.insert(insn.word(1)); // ptr
1771 break;
1772 case spv::OpAccessChain:
1773 case spv::OpInBoundsAccessChain:
1774 worklist.insert(insn.word(3)); // base ptr
1775 break;
1776 case spv::OpSampledImage:
1777 case spv::OpImageSampleImplicitLod:
1778 case spv::OpImageSampleExplicitLod:
1779 case spv::OpImageSampleDrefImplicitLod:
1780 case spv::OpImageSampleDrefExplicitLod:
1781 case spv::OpImageSampleProjImplicitLod:
1782 case spv::OpImageSampleProjExplicitLod:
1783 case spv::OpImageSampleProjDrefImplicitLod:
1784 case spv::OpImageSampleProjDrefExplicitLod:
1785 case spv::OpImageFetch:
1786 case spv::OpImageGather:
1787 case spv::OpImageDrefGather:
1788 case spv::OpImageRead:
1789 case spv::OpImage:
1790 case spv::OpImageQueryFormat:
1791 case spv::OpImageQueryOrder:
1792 case spv::OpImageQuerySizeLod:
1793 case spv::OpImageQuerySize:
1794 case spv::OpImageQueryLod:
1795 case spv::OpImageQueryLevels:
1796 case spv::OpImageQuerySamples:
1797 case spv::OpImageSparseSampleImplicitLod:
1798 case spv::OpImageSparseSampleExplicitLod:
1799 case spv::OpImageSparseSampleDrefImplicitLod:
1800 case spv::OpImageSparseSampleDrefExplicitLod:
1801 case spv::OpImageSparseSampleProjImplicitLod:
1802 case spv::OpImageSparseSampleProjExplicitLod:
1803 case spv::OpImageSparseSampleProjDrefImplicitLod:
1804 case spv::OpImageSparseSampleProjDrefExplicitLod:
1805 case spv::OpImageSparseFetch:
1806 case spv::OpImageSparseGather:
1807 case spv::OpImageSparseDrefGather:
1808 case spv::OpImageTexelPointer:
1809 worklist.insert(insn.word(3)); // Image or sampled image
1810 break;
1811 case spv::OpImageWrite:
1812 worklist.insert(insn.word(1)); // Image -- different operand order to above
1813 break;
1814 case spv::OpFunctionCall:
1815 for (uint32_t i = 3; i < insn.len(); i++) {
1816 worklist.insert(insn.word(i)); // fn itself, and all args
1817 }
1818 break;
1819
1820 case spv::OpExtInst:
1821 for (uint32_t i = 5; i < insn.len(); i++) {
1822 worklist.insert(insn.word(i)); // Operands to ext inst
1823 }
1824 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001825
1826 default: {
1827 if (AtomicOperation(insn.opcode())) {
1828 if (insn.opcode() == spv::OpAtomicStore) {
1829 worklist.insert(insn.word(1)); // ptr
1830 } else {
1831 worklist.insert(insn.word(3)); // ptr
1832 }
1833 }
1834 break;
1835 }
Chris Forbes47567b72017-06-09 12:09:45 -07001836 }
1837 }
1838 break;
1839 }
1840 }
1841
1842 return ids;
1843}
1844
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001845PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1846 const shader_struct_member &push_constant_used_in_shader,
1847 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001848 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001849 const auto used_bytes_size = used_bytes->size();
1850 if (used_bytes_size == 0) return PC_Byte_Updated;
1851
1852 const auto push_constant_data_update_size = push_constant_data_update.size();
1853 const auto *data = push_constant_data_update.data();
1854 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1855 if (used_bytes_size <= push_constant_data_update_size) {
1856 return PC_Byte_Updated;
1857 }
1858 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1859
1860 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1861 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1862 return PC_Byte_Updated;
1863 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001864 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001865
locke-lunargde3f0fa2020-09-10 11:55:31 -06001866 uint32_t i = 0;
1867 for (const auto used : *used_bytes) {
1868 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001869 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001870 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001871 return PC_Byte_Not_Set;
1872 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001873 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001874 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001875 }
1876 }
1877 ++i;
1878 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001879 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001880}
1881
1882bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1883 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001884 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001885 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
locke-lunargde3f0fa2020-09-10 11:55:31 -06001886 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1887 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1888 return skip;
1889 }
1890 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001891
locke-lunargde3f0fa2020-09-10 11:55:31 -06001892 bool found_stage = false;
1893 for (auto const &range : *push_constant_ranges) {
1894 if (range.stageFlags & pStage->stage) {
1895 found_stage = true;
1896 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001897 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001898 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001899 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001900 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001901 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001902 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001903 const auto ret =
1904 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001905
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001906 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001907 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1908 LogObjectList objlist(src->vk_shader_module);
1909 objlist.add(pipeline.pipeline_layout->layout);
1910 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1911 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1912 string_VkShaderStageFlags(pStage->stage).c_str(),
1913 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1914 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001915 }
1916 }
1917 }
1918
locke-lunargde3f0fa2020-09-10 11:55:31 -06001919 if (!found_stage) {
1920 LogObjectList objlist(src->vk_shader_module);
1921 objlist.add(pipeline.pipeline_layout->layout);
1922 skip |= LogError(
1923 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1924 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1925 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001926 }
Chris Forbes47567b72017-06-09 12:09:45 -07001927 return skip;
1928}
1929
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001930bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1931 VkShaderStageFlagBits stage) const {
1932 bool skip = false;
1933
1934 // Currently all builtin tested are only found in fragment shaders
1935 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1936 return skip;
1937 }
1938
1939 for (const auto id : accessible_ids) {
1940 auto insn = src->get_def(id);
1941 const decoration_set decorations = src->get_decorations(insn.word(2));
1942
1943 // Built-ins are obtained from OpVariable
1944 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1945 auto type_pointer = src->get_def(insn.word(1));
1946 assert(type_pointer.opcode() == spv::OpTypePointer);
1947
1948 auto type = src->get_def(type_pointer.word(3));
1949 if (type.opcode() == spv::OpTypeArray) {
1950 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1951
1952 switch (decorations.builtin) {
1953 case spv::BuiltInSampleMask:
1954 // Handles both the input and output sampleMask
1955 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1956 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1957 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1958 "maxSampleMaskWords of %u in %s.",
1959 length, phys_dev_props.limits.maxSampleMaskWords,
1960 report_data->FormatHandle(src->vk_shader_module).c_str());
1961 }
1962 break;
1963 }
1964 }
1965 }
1966 }
1967
1968 return skip;
1969}
1970
Chris Forbes47567b72017-06-09 12:09:45 -07001971// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001972bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001973 bool skip = false;
1974
1975 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1976
1977 if (spec) {
1978 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001979 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001980 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1981 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1982 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1983 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1984 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001985
1986 continue;
1987 }
Chris Forbes47567b72017-06-09 12:09:45 -07001988 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001989 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
1990 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1991 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1992 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1993 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001994 }
1995 }
1996 }
1997
1998 return skip;
1999}
2000
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002001// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002002static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2003 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002004 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002005 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002006 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002007 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002008
2009 // 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 -05002010 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2011 if (type.opcode() == spv::OpTypeRuntimeArray) {
2012 descriptor_count = 0;
2013 type = module->get_def(type.word(2));
2014 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002015 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002016 type = module->get_def(type.word(2));
2017 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002018 if (type.word(2) == spv::StorageClassStorageBuffer) {
2019 is_storage_buffer = true;
2020 }
Chris Forbes47567b72017-06-09 12:09:45 -07002021 type = module->get_def(type.word(3));
2022 }
2023 }
2024
2025 switch (type.opcode()) {
2026 case spv::OpTypeStruct: {
2027 for (auto insn : *module) {
2028 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
2029 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002030 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002031 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2032 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2033 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002034 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002035 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2036 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2037 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2038 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002039 }
Chris Forbes47567b72017-06-09 12:09:45 -07002040 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002041 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2042 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2043 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002044 }
2045 }
2046 }
2047
2048 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002049 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002050 }
2051
2052 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002053 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2054 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2055 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002056
Chris Forbes73c00bf2018-06-22 16:28:06 -07002057 case spv::OpTypeSampledImage: {
2058 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2059 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2060 auto image_type = module->get_def(type.word(2));
2061 auto dim = image_type.word(3);
2062 auto sampled = image_type.word(7);
2063 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002064 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2065 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002066 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002067 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002068 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2069 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002070
2071 case spv::OpTypeImage: {
2072 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2073 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2074 auto dim = type.word(3);
2075 auto sampled = type.word(7);
2076
2077 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002078 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2079 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002080 } else if (dim == spv::DimBuffer) {
2081 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002082 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2083 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002084 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002085 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2086 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002087 }
2088 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002089 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2090 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2091 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002092 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002093 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2094 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002095 }
2096 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002097 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002098 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2099 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002100 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002101
2102 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2103 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002104 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002105 }
2106}
2107
Jeff Bolze54ae892018-09-08 12:16:29 -05002108static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002109 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002110 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2111 if (ss.tellp()) ss << ", ";
2112 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002113 }
2114 return ss.str();
2115}
2116
sfricke-samsung0065ce02020-12-03 22:46:37 -08002117bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002118 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002119 if (LogError(device, vuid, "Shader requires flag %s set in %s but it is not set on the device", flag, structure)) {
Jeff Bolzee743412019-06-20 22:24:32 -05002120 return true;
2121 }
2122 }
2123
2124 return false;
2125}
2126
sfricke-samsung0065ce02020-12-03 22:46:37 -08002127bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002128 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002129 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002130 return true;
2131 }
2132 }
2133
2134 return false;
2135}
2136
locke-lunarg63e4daf2020-08-17 17:53:25 -06002137bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2138 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002139 bool skip = false;
2140
locke-lunarg63e4daf2020-08-17 17:53:25 -06002141 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002142 switch (stage) {
2143 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002144 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2145 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2146 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2147 case VK_SHADER_STAGE_MISS_BIT_NV:
2148 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2149 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2150 case VK_SHADER_STAGE_TASK_BIT_NV:
2151 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002152 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002153 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002154 break;
2155 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002156 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2157 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002158 break;
2159 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002160 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2161 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002162 break;
2163 }
2164 }
2165
Chris Forbes47567b72017-06-09 12:09:45 -07002166 return skip;
2167}
2168
Jeff Bolz526f2d52019-09-18 13:18:08 -05002169bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002170 bool skip = false;
2171
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002172 auto const subgroup_props = phys_dev_props_core11;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002173 const VkSubgroupFeatureFlags supported_stages = subgroup_props.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05002174
Jeff Bolz526f2d52019-09-18 13:18:08 -05002175 for (auto inst : *module) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002176 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2177 if (GroupOperation(inst.opcode()) == true) {
2178 // Check the quad operations.
2179 if ((inst.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (inst.opcode() == spv::OpGroupNonUniformQuadSwap)) {
Jeff Bolzee743412019-06-20 22:24:32 -05002180 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002181 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
sfricke-samsung0065ce02020-12-03 22:46:37 -08002182 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2183 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolzee743412019-06-20 22:24:32 -05002184 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002185 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002186
sfricke-samsung0065ce02020-12-03 22:46:37 -08002187 uint32_t scope_type = spv::ScopeMax;
sfricke-samsung95180142020-12-10 20:58:20 -08002188 if (inst.opcode() == spv::OpGroupNonUniformPartitionNV) {
2189 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2190 scope_type = spv::ScopeSubgroup;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002191 } else {
sfricke-samsung95180142020-12-10 20:58:20 -08002192 auto scope_id = module->get_def(inst.word(3));
2193 if ((scope_id.opcode() == spv::OpSpecConstant) || (scope_id.opcode() == spv::OpConstant)) {
2194 scope_type = scope_id.word(3);
2195 } else {
2196 // TODO - Look if this is check by spirv-val
2197 skip |= LogWarning(device, "UNASSIGNED-spirv-group-scopeId",
2198 "Expecting group operation (%u) scope id operand to point to a OpConstant or OpSpecConstant "
2199 "opcode but instead it is pointing to opcode (%u)",
2200 inst.opcode(), scope_id.opcode());
2201 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002202 }
2203
2204 if (scope_type == spv::ScopeSubgroup) {
2205 // "Group operations with subgroup scope" must have stage support
2206 skip |=
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002207 RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002208 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
2209 }
2210
2211 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2212 auto type = module->get_def(inst.word(1));
2213
2214 if (type.opcode() == spv::OpTypeVector) {
2215 // Get the element type
2216 type = module->get_def(type.word(2));
2217 }
2218
2219 if (type.opcode() == spv::OpTypeBool) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05002220 break;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002221 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002222
sfricke-samsung0065ce02020-12-03 22:46:37 -08002223 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2224 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002225
sfricke-samsung0065ce02020-12-03 22:46:37 -08002226 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2227 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2228 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2229 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2230 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002231 }
2232 }
2233 }
Jeff Bolzee743412019-06-20 22:24:32 -05002234 }
2235
2236 return skip;
2237}
2238
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002239bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002240 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002241 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2242 pStage->stage == VK_SHADER_STAGE_ALL) {
2243 return false;
2244 }
2245
2246 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002247 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002248
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002249 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002250 struct Variable {
2251 uint32_t baseTypePtrID;
2252 uint32_t ID;
2253 uint32_t storageClass;
2254 };
2255 std::vector<Variable> variables;
2256
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002257 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002258 bool is_iso_lines = false;
2259 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002260
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002261 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002262
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002263 for (auto insn : *src) {
2264 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002265 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002266 case spv::OpDecorate:
2267 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002268 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002269 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002270 break;
2271 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002272 default:
2273 break;
2274 }
2275 break;
2276 // Find all input and output variables
2277 case spv::OpVariable: {
2278 Variable var = {};
2279 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002280 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2281 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002282 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002283 var.baseTypePtrID = insn.word(1);
2284 var.ID = insn.word(2);
2285 variables.push_back(var);
2286 }
2287 break;
2288 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002289 case spv::OpExecutionMode:
2290 if (insn.word(1) == entrypoint.word(2)) {
2291 switch (insn.word(2)) {
2292 default:
2293 break;
2294 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002295 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002296 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002297 case spv::ExecutionModeIsolines:
2298 is_iso_lines = true;
2299 break;
2300 case spv::ExecutionModePointMode:
2301 is_point_mode = true;
2302 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002303 }
2304 }
2305 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002306 default:
2307 break;
2308 }
2309 }
2310
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002311 bool strip_output_array_level =
2312 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2313 bool strip_input_array_level =
2314 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2315 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2316
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002317 uint32_t num_comp_in = 0, num_comp_out = 0;
2318 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002319
2320 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2321 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2322
2323 // Find max component location used for input variables.
2324 for (auto &var : inputs) {
2325 int location = var.first.first;
2326 int component = var.first.second;
2327 interface_var &iv = var.second;
2328
2329 // Only need to look at the first location, since we use the type's whole size
2330 if (iv.offset != 0) {
2331 continue;
2332 }
2333
2334 if (iv.is_patch) {
2335 continue;
2336 }
2337
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002338 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2339 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002340 }
2341
2342 // Find max component location used for output variables.
2343 for (auto &var : outputs) {
2344 int location = var.first.first;
2345 int component = var.first.second;
2346 interface_var &iv = var.second;
2347
2348 // Only need to look at the first location, since we use the type's whole size
2349 if (iv.offset != 0) {
2350 continue;
2351 }
2352
2353 if (iv.is_patch) {
2354 continue;
2355 }
2356
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002357 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2358 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002359 }
2360
2361 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2362 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002363 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002364 // Check if the variable is a patch. Patches can also be members of blocks,
2365 // but if they are then the top-level arrayness has already been stripped
2366 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002367 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002368
2369 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002370 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002371 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002372 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002373 }
2374 }
2375
2376 switch (pStage->stage) {
2377 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002378 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002379 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2380 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2381 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2382 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002383 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002384 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002385 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002386 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2387 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2388 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2389 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002390 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002391 break;
2392
2393 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002394 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002395 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2396 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2397 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2398 "components by %u components",
2399 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002400 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002401 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002402 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002403 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002404 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2405 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2406 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2407 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002408 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002409 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002410 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2411 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2412 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2413 "components by %u components",
2414 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002415 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002416 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002417 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002418 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002419 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2420 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2421 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2422 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002423 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002424 break;
2425
2426 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002427 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002428 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2429 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2430 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2431 "components by %u components",
2432 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002433 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002434 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002435 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002436 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002437 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2438 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2439 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2440 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002441 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002442 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002443 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2444 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2445 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2446 "components by %u components",
2447 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002448 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002449 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002450 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002451 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002452 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2453 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2454 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2455 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002456 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002457 // Portability validation
2458 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2459 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2460 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2461 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2462 " is using abstract patch type IsoLines, but this is not supported on this platform");
2463 }
2464 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2465 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2466 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2467 " is using abstract patch type PointMode, but this is not supported on this platform");
2468 }
2469 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002470 break;
2471
2472 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002473 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002474 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2475 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2476 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2477 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002478 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002479 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002480 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002481 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2482 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2483 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2484 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002485 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002486 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002487 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2488 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2489 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2490 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002491 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002492 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002493 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002494 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2495 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2496 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2497 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002498 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002499 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002500 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2501 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2502 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2503 "components by %u components",
2504 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002505 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002506 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002507 break;
2508
2509 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002510 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002511 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2512 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2513 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2514 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002515 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002516 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002517 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002518 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2519 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2520 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2521 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002522 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002523 break;
2524
Jeff Bolz148d94e2018-12-13 21:25:56 -06002525 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2526 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2527 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2528 case VK_SHADER_STAGE_MISS_BIT_NV:
2529 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2530 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2531 case VK_SHADER_STAGE_TASK_BIT_NV:
2532 case VK_SHADER_STAGE_MESH_BIT_NV:
2533 break;
2534
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002535 default:
2536 assert(false); // This should never happen
2537 }
2538 return skip;
2539}
2540
sfricke-samsungdc96f302020-03-18 20:42:10 -07002541bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2542 bool skip = false;
2543 uint32_t total_resources = 0;
2544
2545 // Only currently testing for graphics and compute pipelines
2546 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2547 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2548 return false;
2549 }
2550
2551 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2552 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2553 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2554 }
2555
2556 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2557 // input from CreatePipeline and CreatePipelineLayout level
2558 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2559 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2560 continue;
2561 }
2562
2563 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2564 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2565 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2566 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2567 // Check only descriptor types listed in maxPerStageResources description in spec
2568 switch (binding->descriptorType) {
2569 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2570 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2571 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2572 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2573 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2574 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2575 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2576 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2577 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2578 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2579 total_resources += binding->descriptorCount;
2580 break;
2581 default:
2582 break;
2583 }
2584 }
2585 }
2586 }
2587
2588 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2589 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2590 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2591 skip |= LogError(pipeline->pipeline, vuid,
2592 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2593 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2594 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2595 }
2596
2597 return skip;
2598}
2599
Jeff Bolze4356752019-03-07 11:23:46 -06002600// copy the specialization constant value into buf, if it is present
2601void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2602 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2603
2604 if (spec && spec_id < spec->mapEntryCount) {
2605 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2606 }
2607}
2608
2609// Fill in value with the constant or specialization constant value, if available.
2610// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002611static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002612 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2613 auto type_id = src->get_def(insn.word(1));
2614 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2615 return false;
2616 }
2617 switch (insn.opcode()) {
2618 case spv::OpSpecConstant:
2619 *value = insn.word(3);
2620 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2621 return true;
2622 case spv::OpConstant:
2623 *value = insn.word(3);
2624 return true;
2625 default:
2626 return false;
2627 }
2628}
2629
2630// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002631VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002632 switch (insn.opcode()) {
2633 case spv::OpTypeInt:
2634 switch (insn.word(2)) {
2635 case 8:
2636 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2637 case 16:
2638 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2639 case 32:
2640 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2641 case 64:
2642 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2643 default:
2644 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2645 }
2646 case spv::OpTypeFloat:
2647 switch (insn.word(2)) {
2648 case 16:
2649 return VK_COMPONENT_TYPE_FLOAT16_NV;
2650 case 32:
2651 return VK_COMPONENT_TYPE_FLOAT32_NV;
2652 case 64:
2653 return VK_COMPONENT_TYPE_FLOAT64_NV;
2654 default:
2655 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2656 }
2657 default:
2658 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2659 }
2660}
2661
2662// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2663// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002664bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002665 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002666 bool skip = false;
2667
2668 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2669 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2670 // Map SPIR-V result ID to the ID of its type.
2671 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2672
2673 struct CoopMatType {
2674 uint32_t scope, rows, cols;
2675 VkComponentTypeNV component_type;
2676 bool all_constant;
2677
2678 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2679
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002680 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002681 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2682 spirv_inst_iter insn = src->get_def(id);
2683 uint32_t component_type_id = insn.word(2);
2684 uint32_t scope_id = insn.word(3);
2685 uint32_t rows_id = insn.word(4);
2686 uint32_t cols_id = insn.word(5);
2687 auto component_type_iter = src->get_def(component_type_id);
2688 auto scope_iter = src->get_def(scope_id);
2689 auto rows_iter = src->get_def(rows_id);
2690 auto cols_iter = src->get_def(cols_id);
2691
2692 all_constant = true;
2693 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2694 all_constant = false;
2695 }
2696 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2697 all_constant = false;
2698 }
2699 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2700 all_constant = false;
2701 }
2702 component_type = GetComponentType(component_type_iter, src);
2703 }
2704 };
2705
2706 bool seen_coopmat_capability = false;
2707
2708 for (auto insn : *src) {
2709 // Whitelist instructions whose result can be a cooperative matrix type, and
2710 // keep track of their types. It would be nice if SPIRV-Headers generated code
2711 // to identify which instructions have a result type and result id. Lacking that,
2712 // this whitelist is based on the set of instructions that
2713 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2714 switch (insn.opcode()) {
2715 case spv::OpLoad:
2716 case spv::OpCooperativeMatrixLoadNV:
2717 case spv::OpCooperativeMatrixMulAddNV:
2718 case spv::OpSNegate:
2719 case spv::OpFNegate:
2720 case spv::OpIAdd:
2721 case spv::OpFAdd:
2722 case spv::OpISub:
2723 case spv::OpFSub:
2724 case spv::OpFDiv:
2725 case spv::OpSDiv:
2726 case spv::OpUDiv:
2727 case spv::OpMatrixTimesScalar:
2728 case spv::OpConstantComposite:
2729 case spv::OpCompositeConstruct:
2730 case spv::OpConvertFToU:
2731 case spv::OpConvertFToS:
2732 case spv::OpConvertSToF:
2733 case spv::OpConvertUToF:
2734 case spv::OpUConvert:
2735 case spv::OpSConvert:
2736 case spv::OpFConvert:
2737 id_to_type_id[insn.word(2)] = insn.word(1);
2738 break;
2739 default:
2740 break;
2741 }
2742
2743 switch (insn.opcode()) {
2744 case spv::OpDecorate:
2745 if (insn.word(2) == spv::DecorationSpecId) {
2746 id_to_spec_id[insn.word(1)] = insn.word(3);
2747 }
2748 break;
2749 case spv::OpCapability:
2750 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2751 seen_coopmat_capability = true;
2752
2753 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002754 skip |= LogError(
2755 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2756 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2757 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002758 }
2759 }
2760 break;
2761 case spv::OpMemoryModel:
2762 // If the capability isn't enabled, don't bother with the rest of this function.
2763 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2764 if (!seen_coopmat_capability) {
2765 return skip;
2766 }
2767 break;
2768 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002769 CoopMatType m;
2770 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002771
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002772 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002773 // Validate that the type parameters are all supported for one of the
2774 // operands of a cooperative matrix property.
2775 bool valid = false;
2776 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002777 if (cooperative_matrix_properties[i].AType == m.component_type &&
2778 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2779 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002780 valid = true;
2781 break;
2782 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002783 if (cooperative_matrix_properties[i].BType == m.component_type &&
2784 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2785 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002786 valid = true;
2787 break;
2788 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002789 if (cooperative_matrix_properties[i].CType == m.component_type &&
2790 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2791 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002792 valid = true;
2793 break;
2794 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002795 if (cooperative_matrix_properties[i].DType == m.component_type &&
2796 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2797 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002798 valid = true;
2799 break;
2800 }
2801 }
2802 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002803 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2804 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2805 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002806 }
2807 }
2808 break;
2809 }
2810 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002811 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002812 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2813 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2814 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2815 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002816 // Couldn't find type of matrix
2817 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002818 break;
2819 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002820 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2821 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2822 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2823 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002824
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002825 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002826 // Validate that the type parameters are all supported for the same
2827 // cooperative matrix property.
2828 bool valid = false;
2829 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002830 if (cooperative_matrix_properties[i].AType == a.component_type &&
2831 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2832 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002833
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002834 cooperative_matrix_properties[i].BType == b.component_type &&
2835 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2836 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002837
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002838 cooperative_matrix_properties[i].CType == c.component_type &&
2839 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2840 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002841
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002842 cooperative_matrix_properties[i].DType == d.component_type &&
2843 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2844 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002845 valid = true;
2846 break;
2847 }
2848 }
2849 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002850 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2851 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2852 "VkCooperativeMatrixPropertiesNV",
2853 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002854 }
2855 }
2856 break;
2857 }
2858 default:
2859 break;
2860 }
2861 }
2862
2863 return skip;
2864}
2865
John Zulaufac4c6e12019-07-01 16:05:58 -06002866bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002867 auto entrypoint_id = entrypoint.word(2);
2868
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002869 // The first denorm execution mode encountered, along with its bit width.
2870 // Used to check if SeparateDenormSettings is respected.
2871 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002872
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002873 // The first rounding mode encountered, along with its bit width.
2874 // Used to check if SeparateRoundingModeSettings is respected.
2875 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002876
2877 bool skip = false;
2878
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002879 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002880 uint32_t invocations = 0;
2881
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002882 for (auto insn : *src) {
2883 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2884 auto mode = insn.word(2);
2885 switch (mode) {
2886 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2887 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002888 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2889 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2890 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002891 skip |= LogError(
2892 device, kVUID_Core_Shader_FeatureNotEnabled,
2893 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2894 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002895 }
2896 break;
2897 }
2898
2899 case spv::ExecutionModeDenormPreserve: {
2900 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002901 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2902 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2903 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002904 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2905 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2906 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002907 }
2908
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002909 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2910 // Register the first denorm execution mode found
2911 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002912 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002913 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002914 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002915 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002916 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2917 "Shader uses different denorm execution modes for 16 and 64-bit but "
2918 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002919 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002920 }
2921 break;
2922
Mike Schuchardt2df08912020-12-15 16:28:09 -08002923 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002924 break;
2925
Mike Schuchardt2df08912020-12-15 16:28:09 -08002926 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002927 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2928 "Shader uses different denorm execution modes for different bit widths but "
2929 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002930 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002931 break;
2932
2933 default:
2934 break;
2935 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002936 }
2937 break;
2938 }
2939
2940 case spv::ExecutionModeDenormFlushToZero: {
2941 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002942 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2943 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2944 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002945 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2946 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2947 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002948 }
2949
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002950 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2951 // Register the first denorm execution mode found
2952 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002953 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002954 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002955 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002956 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002957 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2958 "Shader uses different denorm execution modes for 16 and 64-bit but "
2959 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002960 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002961 }
2962 break;
2963
Mike Schuchardt2df08912020-12-15 16:28:09 -08002964 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002965 break;
2966
Mike Schuchardt2df08912020-12-15 16:28:09 -08002967 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002968 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2969 "Shader uses different denorm execution modes for different bit widths but "
2970 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002971 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002972 break;
2973
2974 default:
2975 break;
2976 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002977 }
2978 break;
2979 }
2980
2981 case spv::ExecutionModeRoundingModeRTE: {
2982 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002983 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2984 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2985 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002986 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2987 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2988 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002989 }
2990
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002991 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2992 // Register the first rounding mode found
2993 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002994 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002995 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002996 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002997 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002998 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2999 "Shader uses different rounding modes for 16 and 64-bit but "
3000 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003001 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003002 }
3003 break;
3004
Mike Schuchardt2df08912020-12-15 16:28:09 -08003005 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003006 break;
3007
Mike Schuchardt2df08912020-12-15 16:28:09 -08003008 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003009 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3010 "Shader uses different rounding modes for different bit widths but "
3011 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003012 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003013 break;
3014
3015 default:
3016 break;
3017 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003018 }
3019 break;
3020 }
3021
3022 case spv::ExecutionModeRoundingModeRTZ: {
3023 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003024 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3025 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3026 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003027 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3028 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3029 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003030 }
3031
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003032 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3033 // Register the first rounding mode found
3034 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003035 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003036 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003037 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003038 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003039 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3040 "Shader uses different rounding modes for 16 and 64-bit but "
3041 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003042 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003043 }
3044 break;
3045
Mike Schuchardt2df08912020-12-15 16:28:09 -08003046 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003047 break;
3048
Mike Schuchardt2df08912020-12-15 16:28:09 -08003049 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003050 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3051 "Shader uses different rounding modes for different bit widths but "
3052 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003053 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003054 break;
3055
3056 default:
3057 break;
3058 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003059 }
3060 break;
3061 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003062
3063 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003064 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003065 break;
3066 }
3067
3068 case spv::ExecutionModeInvocations: {
3069 invocations = insn.word(3);
3070 break;
3071 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003072 }
3073 }
3074 }
3075
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003076 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003077 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003078 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3079 "Geometry shader entry point must have an OpExecutionMode instruction that "
3080 "specifies a maximum output vertex count that is greater than 0 and less "
3081 "than or equal to maxGeometryOutputVertices. "
3082 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003083 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003084 }
3085
3086 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003087 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3088 "Geometry shader entry point must have an OpExecutionMode instruction that "
3089 "specifies an invocation count that is greater than 0 and less "
3090 "than or equal to maxGeometryShaderInvocations. "
3091 "Invocations=%d, maxGeometryShaderInvocations=%d",
3092 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003093 }
3094 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003095 return skip;
3096}
3097
locke-lunargd9a069d2019-09-17 01:50:19 -06003098uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003099 auto type = module->get_def(type_id);
3100
3101 while (true) {
3102 switch (type.opcode()) {
3103 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003104 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003105 case spv::OpTypeSampledImage:
3106 type = module->get_def(type.word(2));
3107 break;
3108 case spv::OpTypePointer:
3109 type = module->get_def(type.word(3));
3110 break;
3111 case spv::OpTypeImage: {
3112 auto dim = type.word(3);
3113 auto arrayed = type.word(5);
3114 auto msaa = type.word(6);
3115
Chris Forbes74ba2232018-08-27 15:19:27 -07003116 uint32_t bits = 0;
3117 switch (GetFundamentalType(module, type.word(2))) {
3118 case FORMAT_TYPE_FLOAT:
3119 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3120 break;
3121 case FORMAT_TYPE_UINT:
3122 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3123 break;
3124 case FORMAT_TYPE_SINT:
3125 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3126 break;
3127 default:
3128 break;
3129 }
3130
Chris Forbes47567b72017-06-09 12:09:45 -07003131 switch (dim) {
3132 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003133 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3134 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003135 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003136 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3137 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3138 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003139 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003140 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3141 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003142 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003143 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3144 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003145 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003146 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3147 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003148 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003149 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003150 }
3151 }
3152 default:
3153 return 0;
3154 }
3155 }
3156}
3157
3158// For given pipelineLayout verify that the set_layout_node at slot.first
3159// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003160static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003161 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003162 if (!pipelineLayout) return nullptr;
3163
3164 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3165
3166 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3167}
3168
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003169int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3170 if (module == nullptr) return -1;
3171
3172 auto type = module->get_def(resource.type_id);
3173 while (true) {
3174 switch (type.opcode()) {
3175 case spv::OpTypeSampledImage:
3176 type = module->get_def(type.word(2));
3177 break;
3178 case spv::OpTypePointer:
3179 type = module->get_def(type.word(3));
3180 break;
3181 case spv::OpTypeImage:
3182 return type.word(3);
3183 default:
3184 return -1;
3185 }
3186 }
3187}
3188
3189bool 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 -06003190 for (auto insn : *src) {
3191 if (insn.opcode() == spv::OpEntryPoint) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003192 auto execution_model = insn.word(1);
3193 auto entrypoint_stage_bits = ExecutionModelToShaderStageFlagBits(execution_model);
3194 if (entrypoint_stage_bits == VK_SHADER_STAGE_COMPUTE_BIT) {
Locke1ec6d952019-04-02 11:57:21 -06003195 auto entrypoint_id = insn.word(2);
3196 for (auto insn1 : *src) {
3197 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3198 insn1.word(2) == spv::ExecutionModeLocalSize) {
3199 local_size_x = insn1.word(3);
3200 local_size_y = insn1.word(4);
3201 local_size_z = insn1.word(5);
3202 return true;
3203 }
3204 }
3205 }
3206 }
3207 }
3208 return false;
3209}
3210
locke-lunargd9a069d2019-09-17 01:50:19 -06003211void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003212 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003213 bool is_point_mode = false;
3214
3215 for (auto insn : *src) {
3216 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3217 switch (insn.word(2)) {
3218 case spv::ExecutionModePointMode:
3219 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3220 is_point_mode = true;
3221 break;
3222
3223 case spv::ExecutionModeOutputPoints:
3224 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3225 break;
3226
3227 case spv::ExecutionModeIsolines:
3228 case spv::ExecutionModeOutputLineStrip:
3229 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3230 break;
3231
3232 case spv::ExecutionModeTriangles:
3233 case spv::ExecutionModeQuads:
3234 case spv::ExecutionModeOutputTriangleStrip:
3235 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3236 break;
3237 }
3238 }
3239 }
3240
3241 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3242}
3243
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003244// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3245// o If there is only a vertex shader : gl_PointSize must be written when using points
3246// o If there is a geometry or tessellation shader:
3247// - If shaderTessellationAndGeometryPointSize feature is enabled:
3248// * gl_PointSize must be written in the final geometry stage
3249// - If shaderTessellationAndGeometryPointSize feature is disabled:
3250// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003251bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003252 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003253 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3254 return false;
3255 }
3256
3257 bool pointsize_written = false;
3258 bool skip = false;
3259
3260 // Search for PointSize built-in decorations
3261 std::vector<uint32_t> pointsize_builtin_offsets;
3262 spirv_inst_iter insn = entrypoint;
3263 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3264 if (insn.opcode() == spv::OpMemberDecorate) {
3265 if (insn.word(3) == spv::DecorationBuiltIn) {
3266 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003267 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003268 }
3269 }
3270 } else if (insn.opcode() == spv::OpDecorate) {
3271 if (insn.word(2) == spv::DecorationBuiltIn) {
3272 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003273 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003274 }
3275 }
3276 }
3277
3278 insn++;
3279 }
3280
3281 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003282 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003283 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003284 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3285 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3286 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003287 }
3288 } else if (!pointsize_written) {
3289 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003290 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3291 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3292 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003293 }
3294 return skip;
3295}
John Zulauf14c355b2019-06-27 16:09:37 -06003296
Tobias Hector6663c9b2020-11-05 10:18:02 +00003297bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3298 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3299 bool primitiverate_written = false;
3300 bool viewportindex_written = false;
3301 bool viewportmask_written = false;
3302 bool skip = false;
3303
3304 // Check if the primitive shading rate is written
3305 spirv_inst_iter insn = entrypoint;
3306 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3307 if (insn.opcode() == spv::OpMemberDecorate) {
3308 if (insn.word(3) == spv::DecorationBuiltIn) {
3309 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3310 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3311 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3312 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3313 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3314 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3315 }
3316 }
3317 } else if (insn.opcode() == spv::OpDecorate) {
3318 if (insn.word(2) == spv::DecorationBuiltIn) {
3319 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3320 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3321 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3322 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3323 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3324 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3325 }
3326 }
3327 }
3328
3329 insn++;
3330 }
3331
3332 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports) {
3333 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3334 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003335 skip |= LogError(pipeline->pipeline,
3336 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3337 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3338 "multiple viewports "
3339 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3340 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003341 }
3342
3343 if (primitiverate_written && viewportindex_written) {
3344 skip |= LogError(pipeline->pipeline,
3345 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3346 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3347 "ViewportIndex built-ins,"
3348 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3349 string_VkShaderStageFlagBits(stage));
3350 }
3351
3352 if (primitiverate_written && viewportmask_written) {
3353 skip |= LogError(pipeline->pipeline,
3354 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3355 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3356 "ViewportMaskNV built-ins,"
3357 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3358 string_VkShaderStageFlagBits(stage));
3359 }
3360 }
3361 return skip;
3362}
3363
John Zulauf14c355b2019-06-27 16:09:37 -06003364bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3365 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003366 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003367 bool skip = false;
3368
3369 // Check the module
3370 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003371 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3372 "%s does not contain valid spirv for stage %s.",
3373 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003374 }
3375
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003376 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3377 // specializations should be applied and validated.
3378 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3379 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3380 // Gather the specialization-constant values.
3381 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003382 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003383 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3384 id_value_map.reserve(specialization_info->mapEntryCount);
3385 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3386 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003387
Jeremy Hayes521221d2020-01-15 16:48:49 -07003388 // Expect only scalar types.
3389 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3390 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3391 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003392 }
3393
3394 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003395 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003396 spvtools::Optimizer optimizer(spirv_environment);
3397 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3398 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003399 skip |= LogError(
3400 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003401 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3402 };
3403 optimizer.SetMessageConsumer(consumer);
3404 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3405 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3406 std::vector<uint32_t> specialized_spirv;
3407 auto const optimized =
3408 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3409 assert(optimized == true);
3410
3411 if (optimized) {
3412 spv_context ctx = spvContextCreate(spirv_environment);
3413 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3414 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003415 spvtools::ValidatorOptions options;
3416 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003417 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3418 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003419 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003420 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3421 report_data->FormatHandle(module->vk_shader_module).c_str(),
3422 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003423 }
3424
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003425 spvDiagnosticDestroy(diag);
3426 spvContextDestroy(ctx);
3427 }
3428 }
3429
John Zulauf14c355b2019-06-27 16:09:37 -06003430 // Check the entrypoint
3431 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003432 skip |=
3433 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3434 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003435 }
3436 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3437
3438 // Mark accessible ids
3439 auto &accessible_ids = stage_state.accessible_ids;
3440
Chris Forbes47567b72017-06-09 12:09:45 -07003441 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003442 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3443 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003444
Chris Forbes349b3132018-03-07 11:38:08 -08003445 // Validate shader capabilities against enabled device features
sfricke-samsung0065ce02020-12-03 22:46:37 -08003446 skip |= ValidateShaderCapabilitiesAndExtensions(module);
locke-lunarg63e4daf2020-08-17 17:53:25 -06003447 skip |=
3448 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003449 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003450 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05003451 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003452 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003453 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003454 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003455 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003456 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003457 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003458 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003459 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003460 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3461 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3462 }
Chris Forbes47567b72017-06-09 12:09:45 -07003463
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003464 std::string vuid_layout_mismatch;
3465 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3466 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3467 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3468 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3469 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3470 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3471 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3472 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3473 }
3474
Chris Forbes47567b72017-06-09 12:09:45 -07003475 // Validate descriptor use
3476 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003477 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003478 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003479 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003480 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3481 std::set<uint32_t> descriptor_types =
3482 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003483
3484 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003485 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003486 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3487 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003488 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003489 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003490 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3491 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003492 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003493 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003494 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3495 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3496 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003497 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003498 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003499 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3500 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003501 }
3502 }
3503
3504 // Validate use of input attachments against subpass structure
3505 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003506 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003507
Petr Krause91f7a12017-12-14 20:57:36 +01003508 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003509 auto subpass = pipeline->graphicsPipelineCI.subpass;
3510
3511 for (auto use : input_attachment_uses) {
3512 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3513 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003514 ? input_attachments[use.first].attachment
3515 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003516
3517 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003518 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3519 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003520 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003521 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003522 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3523 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3524 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003525 }
3526 }
3527 }
Lockeaa8fdc02019-04-02 11:59:20 -06003528 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3529 skip |= ValidateComputeWorkGroupSizes(module);
3530 }
Chris Forbes47567b72017-06-09 12:09:45 -07003531 return skip;
3532}
3533
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003534bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3535 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3536 spirv_inst_iter consumer_entrypoint,
3537 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003538 bool skip = false;
3539
3540 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003541 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3542 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003543
3544 auto a_it = outputs.begin();
3545 auto b_it = inputs.begin();
3546
3547 // Maps sorted by key (location); walk them together to find mismatches
3548 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3549 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3550 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3551 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3552 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3553
3554 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003555 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3556 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3557 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003558 a_it++;
3559 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003560 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3561 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3562 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003563 b_it++;
3564 } else {
3565 // subtleties of arrayed interfaces:
3566 // - if is_patch, then the member is not arrayed, even though the interface may be.
3567 // - if is_block_member, then the extra array level of an arrayed interface is not
3568 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003569 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3570 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3571 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003572 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3573 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3574 DescribeType(producer, a_it->second.type_id).c_str(),
3575 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003576 }
3577 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003578 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3579 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3580 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3581 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003582 }
3583 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003584 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3585 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3586 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003587 }
3588 a_it++;
3589 b_it++;
3590 }
3591 }
3592
Ari Suonpaa696b3432019-03-11 14:02:57 +02003593 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3594 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3595 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3596
3597 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3598 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003599 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3600 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003601 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3602 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003603 } else {
3604 auto it_producer = builtins_producer.begin();
3605 auto it_consumer = builtins_consumer.begin();
3606 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3607 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003608 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3609 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3610 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003611 break;
3612 }
3613 it_producer++;
3614 it_consumer++;
3615 }
3616 }
3617 }
3618 }
3619
Chris Forbes47567b72017-06-09 12:09:45 -07003620 return skip;
3621}
3622
John Zulauf14c355b2019-06-27 16:09:37 -06003623static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003624 uint32_t stage_mask = 0;
3625 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3626 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3627 stage_mask |= pCreateInfo->pStages[i].stage;
3628 }
3629 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003630 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3631 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3632 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003633 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3634 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3635 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3636 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3637 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003638 }
3639 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003640 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003641}
3642
Chris Forbes47567b72017-06-09 12:09:45 -07003643// Validate that the shaders used by the given pipeline and store the active_slots
3644// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003645bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003646 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003647 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3648 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003649
John Zulauf14c355b2019-06-27 16:09:37 -06003650 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003651 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003652 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003653 bool skip = false;
3654
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003655 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003656
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003657 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3658 auto stage = &create_info->pStages[i];
3659 auto stage_id = GetShaderStageId(stage->stage);
3660 shaders[stage_id] = GetShaderModuleState(stage->module);
3661 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3662 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3663 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003664 }
3665
3666 // if the shader stages are no good individually, cross-stage validation is pointless.
3667 if (skip) return true;
3668
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003669 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003670
3671 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003672 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003673 }
3674
3675 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003676 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003677 }
3678
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003679 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3680 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003681
3682 while (!shaders[producer] && producer != fragment_stage) {
3683 producer++;
3684 consumer++;
3685 }
3686
3687 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3688 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003689 if (shaders[consumer]) {
3690 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003691 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3692 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003693 }
Chris Forbes47567b72017-06-09 12:09:45 -07003694
3695 producer = consumer;
3696 }
3697 }
3698
3699 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003700 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003701 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003702 }
3703
3704 return skip;
3705}
3706
Tobias Hector6663c9b2020-11-05 10:18:02 +00003707bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3708 const char *caller, const DrawDispatchVuid &vuid) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003709 auto create_info = pipeline->graphicsPipelineCI.ptr();
Tobias Hector6663c9b2020-11-05 10:18:02 +00003710
3711 const SHADER_MODULE_STATE *shaders[32];
3712 memset(shaders, 0, sizeof(shaders));
3713 spirv_inst_iter entrypoints[32];
3714 memset(entrypoints, 0, sizeof(entrypoints));
3715 bool skip = false;
3716
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003717 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3718 auto stage = &create_info->pStages[i];
3719 auto stage_id = GetShaderStageId(stage->stage);
3720 shaders[stage_id] = GetShaderModuleState(stage->module);
3721 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003722
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003723 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3724 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003725 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3726 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3727 spirv_inst_iter insn = entrypoints[stage_id];
3728 bool primitiverate_written = false;
3729
3730 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3731 if (insn.opcode() == spv::OpMemberDecorate) {
3732 if (insn.word(3) == spv::DecorationBuiltIn) {
3733 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3734 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3735 }
3736 }
3737 } else if (insn.opcode() == spv::OpDecorate) {
3738 if (insn.word(2) == spv::DecorationBuiltIn) {
3739 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3740 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3741 }
3742 }
3743 }
3744
3745 insn++;
3746 }
3747
3748 if (primitiverate_written) {
3749 skip |=
3750 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3751 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3752 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3753 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003754 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003755 }
3756 }
3757 }
3758 }
3759
3760 return skip;
3761}
3762
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003763bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003764 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003765
John Zulauf14c355b2019-06-27 16:09:37 -06003766 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3767 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003768
John Zulauf14c355b2019-06-27 16:09:37 -06003769 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003770}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003771
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003772uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3773 uint32_t total = 0;
3774
3775 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3776 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3777 if (stages[stage_index].stage == stageBit) {
3778 total++;
3779 }
3780 }
3781
3782 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3783 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3784 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3785 total += CalcShaderStageCount(library_pipeline, stageBit);
3786 }
3787 }
3788
3789 return total;
3790}
3791
sourav parmarcd5fb182020-07-17 12:58:44 -07003792bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003793 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003794
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003795 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003796 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3797 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3798 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3799 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3800 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3801 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3802 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003803 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003804 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3805 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003806 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003807 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003808 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003809 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3810 skip |= LogError(
3811 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3812 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3813 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003814 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003815 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3816 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003817 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3818 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003819 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003820 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003821 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3822 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3823 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3824 "member must have been created with values of the maxPipelineRayPayloadSize and "
3825 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3826 }
3827 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003828 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003829 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3830 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3831 "vkCreateRayTracingPipelinesKHR: If flags includes "
3832 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3833 "the pLibraries member of libraries must have been created with the "
3834 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3835 }
sourav parmar83c31b12020-05-06 12:30:54 -07003836 }
3837 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003838 } else {
3839 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003840 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3841 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3842 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003843 pipeline->raytracingPipelineCI.maxRecursionDepth,
3844 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3845 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003846 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003847 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3848 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3849
John Zulaufe4474e72019-07-01 17:28:27 -06003850 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003851 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003852
John Zulaufe4474e72019-07-01 17:28:27 -06003853 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3854 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003855
John Zulaufe4474e72019-07-01 17:28:27 -06003856 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003857 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003858
3859 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3860 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3861 if (raygen_stages_count == 0) {
3862 skip |= LogError(
3863 device,
3864 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3865 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3866 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003867 }
3868
3869 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3870 const auto &group = groups[group_index];
3871
3872 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3873 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3874 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3875 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3876 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003877 skip |= LogError(device,
3878 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3879 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3880 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003881 }
3882 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3883 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003884 skip |= LogError(device,
3885 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3886 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3887 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003888 }
3889 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3890 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3891 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003892 skip |= LogError(device,
3893 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3894 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3895 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003896 }
3897 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3898 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003899 skip |= LogError(device,
3900 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3901 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3902 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003903 }
3904 }
3905
3906 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3907 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3908 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3909 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003910 skip |= LogError(device,
3911 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3912 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3913 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003914 }
3915 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3916 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3917 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003918 skip |= LogError(device,
3919 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3920 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3921 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003922 }
3923 }
John Zulaufe4474e72019-07-01 17:28:27 -06003924 }
3925 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003926}
3927
Dave Houltona9df0ce2018-02-07 10:51:23 -07003928uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003929
Dave Houltona9df0ce2018-02-07 10:51:23 -07003930static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003931 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003932 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003933 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003934 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003935 return nullptr;
3936}
3937
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003938bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003939 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003940 bool skip = false;
3941 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003942
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003943 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003944 return false;
3945 }
3946
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003947 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003948
3949 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003950 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3951 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3952 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003953 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003954 auto cache = GetValidationCacheInfo(pCreateInfo);
3955 uint32_t hash = 0;
3956 if (cache) {
3957 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003958 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003959 }
3960
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003961 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
3962 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003963 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06003964 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003965 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003966 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003967 spvtools::ValidatorOptions options;
3968 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06003969 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003970 if (spv_valid != SPV_SUCCESS) {
3971 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003972 if (spv_valid == SPV_WARNING) {
3973 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3974 diag && diag->error ? diag->error : "(no error text)");
3975 } else {
3976 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3977 diag && diag->error ? diag->error : "(no error text)");
3978 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003979 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003980 } else {
3981 if (cache) {
3982 cache->Insert(hash);
3983 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003984 }
3985
3986 spvDiagnosticDestroy(diag);
3987 spvContextDestroy(ctx);
3988 }
3989
Chris Forbes4ae55b32017-06-09 14:42:56 -07003990 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003991}
3992
John Zulaufac4c6e12019-07-01 16:05:58 -06003993bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003994 bool skip = false;
3995 uint32_t local_size_x = 0;
3996 uint32_t local_size_y = 0;
3997 uint32_t local_size_z = 0;
3998 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3999 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004000 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4001 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4002 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4003 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004004 }
4005 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004006 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4007 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4008 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4009 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004010 }
4011 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004012 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4013 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4014 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4015 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004016 }
4017
4018 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4019 uint64_t invocations = local_size_x * local_size_y;
4020 // Prevent overflow.
4021 bool fail = false;
4022 if (invocations > UINT32_MAX || invocations > limit) {
4023 fail = true;
4024 }
4025 if (!fail) {
4026 invocations *= local_size_z;
4027 if (invocations > UINT32_MAX || invocations > limit) {
4028 fail = true;
4029 }
4030 }
4031 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004032 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4033 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4034 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4035 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4036 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004037 }
4038 }
4039 return skip;
4040}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004041
4042spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4043 if (api_version >= VK_API_VERSION_1_2) {
4044 return SPV_ENV_VULKAN_1_2;
4045 } else if (api_version >= VK_API_VERSION_1_1) {
4046 if (spirv_1_4) {
4047 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4048 } else {
4049 return SPV_ENV_VULKAN_1_1;
4050 }
4051 }
4052 return SPV_ENV_VULKAN_1_0;
4053}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004054
4055void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4056 spvtools::ValidatorOptions &options) {
4057 if (device_extensions.vk_khr_relaxed_block_layout) {
4058 options.SetRelaxBlockLayout(true);
4059 }
4060 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4061 options.SetUniformBufferStandardLayout(true);
4062 }
4063 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4064 options.SetScalarBlockLayout(true);
4065 }
4066}