blob: c2fa37f9d74e7d2d17e2a55a989591bfe32f73db [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
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001294 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001295 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001296 } else if (def_member.opcode() == spv::OpTypePointer) {
1297 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1298 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1299 // that "points to something."
1300 data1.size = 8;
1301 } else {
1302 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1303 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1304 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001305 } else {
1306 if (def_member.opcode() == spv::OpTypeMatrix) {
1307 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1308 def_member = src.get_def(def_member.word(2));
1309 }
1310
1311 if (def_member.opcode() == spv::OpTypeVector) {
1312 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1313 def_member = src.get_def(def_member.word(2));
1314 }
1315
1316 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1317 data1.size = (def_member.word(2) / 8);
1318 }
1319 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1320 if (array_length_hierarchy_szie > 0) {
1321 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1322
1323 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1324 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1325 }
1326 }
1327 data.struct_members.emplace_back(data1);
1328 ++i;
1329 }
1330 uint32_t total_array_length = 1;
1331 for (const auto length : data1.array_length_hierarchy) {
1332 total_array_length *= length;
1333 }
1334 data.size = local_offset + data1.size * total_array_length;
1335}
1336
1337uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1338 int array_indices_size = static_cast<int>(array_indices.size());
1339 if (array_indices_size) {
1340 uint32_t array_index = 0;
1341 uint32_t i = 0;
1342 for (const auto index : array_indices) {
1343 array_index += (data.array_block_size[i] * index);
1344 ++i;
1345 }
1346 offset += (array_index * data.size);
1347 }
1348 return offset;
1349}
1350
1351void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1352 int array_indices_size = static_cast<int>(array_indices.size());
1353 uint32_t block_memory_size = data.size;
1354 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1355 block_memory_size *= data.array_length_hierarchy[i];
1356 }
1357
1358 offset = UpdateOffset(offset, array_indices, data);
1359
1360 uint32_t end = offset + block_memory_size;
1361 auto used_bytes = data.GetUsedbytes();
1362 if (used_bytes->size() < end) {
1363 used_bytes->resize(end, 0);
1364 }
1365 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1366}
1367
1368void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1369 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1370 if (access_chain_word_index < access_chain_it.len()) {
1371 if (data.array_length_hierarchy.size() > array_indices.size()) {
1372 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1373 ++access_chain_word_index;
1374
1375 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1376 array_indices.emplace_back(def_it.word(3));
1377 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1378 } else {
1379 // If it is a variable, set the all array is used.
1380 if (access_chain_word_index < access_chain_it.len()) {
1381 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1382 for (uint32_t i = 0; i < array_length; ++i) {
1383 auto array_indices2 = array_indices;
1384 array_indices2.emplace_back(i);
1385 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1386 }
1387 } else {
1388 SetUsedBytes(offset, array_indices, data);
1389 }
1390 }
1391 } else {
1392 offset = UpdateOffset(offset, array_indices, data);
1393 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1394 }
1395 } else {
1396 SetUsedBytes(offset, array_indices, data);
1397 }
1398}
1399
1400void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1401 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1402 std::vector<uint32_t> array_indices_emptry;
1403
1404 if (access_chain_word_index < access_chain_it.len()) {
1405 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1406 ++access_chain_word_index;
1407
1408 auto data1 = data.struct_members[strcut_member_index];
1409 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1410 }
1411}
1412
1413void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1414 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1415 for (const auto &func_set : function_set_list) {
1416 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1417 for (auto it = range.first; it != range.second; ++it) {
1418 auto access_chain = src.at(it->second);
1419 if (access_chain.word(3) == variable_id) {
1420 RunUsedStruct(src, 0, 4, access_chain, data);
1421 }
1422 }
1423 }
1424}
1425
1426void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1427 for (auto &entrypoint : src.entry_points) {
1428 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1429 for (auto it = range.first; it != range.second; ++it) {
1430 const auto def_insn = src.at(it->second);
1431
1432 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1433 spirv_inst_iter type = src.get_def(def_insn.word(1));
1434 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1435 std::vector<uint32_t> offsets;
1436
1437 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1438 auto member_decorate = src.at(it2->second);
1439 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1440 offsets.emplace_back(member_decorate.offset());
1441 }
1442 }
1443 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1444 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1445 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1446 entrypoint.second.push_constant_used_in_shader);
1447 }
1448 }
1449 }
1450}
1451
locke-lunarg96dc9632020-06-10 17:22:18 -06001452std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1453 const VkPipelineShaderStageCreateInfo &stage_info) {
1454 std::unordered_set<uint32_t> location_list;
1455 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1456 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1457 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1458 std::unordered_set<unsigned> store_members;
1459 std::unordered_map<unsigned, unsigned> accesschain_members;
1460
1461 for (auto insn : module) {
1462 switch (insn.opcode()) {
1463 case spv::OpStore:
1464 case spv::OpAtomicStore: {
1465 store_members.insert(insn.word(1)); // object id or AccessChain id
1466 break;
1467 }
1468 case spv::OpAccessChain: {
1469 // 2: AccessChain id, 3: object id
1470 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1471 break;
1472 }
1473 default:
1474 break;
1475 }
1476 }
1477 if (store_members.empty()) {
1478 return location_list;
1479 }
1480 for (auto output : outputs) {
1481 auto store_it = store_members.find(output.second.id);
1482 if (store_it != store_members.end()) {
1483 location_list.insert(output.first.first);
1484 store_members.erase(store_it);
1485 continue;
1486 }
1487 store_it = store_members.begin();
1488 while (store_it != store_members.end()) {
1489 auto accesschain_it = accesschain_members.find(*store_it);
1490 if (accesschain_it == accesschain_members.end()) {
1491 ++store_it;
1492 continue;
1493 }
1494 if (accesschain_it->second == output.second.id) {
1495 location_list.insert(output.first.first);
1496 store_members.erase(store_it);
1497 accesschain_members.erase(accesschain_it);
1498 break;
1499 }
1500 ++store_it;
1501 }
1502 }
1503 return location_list;
1504}
1505
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001506bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001507 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1508 // be specified only once.
1509 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1510 bool skip = false;
1511
1512 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1513 auto desc = &vi->pVertexBindingDescriptions[i];
1514 auto &binding = bindings[desc->binding];
1515 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001516 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001517 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1518 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001519 } else {
1520 binding = desc;
1521 }
1522 }
1523
1524 return skip;
1525}
1526
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001527bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1528 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001529 bool skip = false;
1530
Petr Kraus25810d02019-08-27 17:41:15 +02001531 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001532
1533 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001534 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001535 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001536 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1537 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1538 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001539 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1540 }
1541 }
1542 }
1543
Petr Kraus25810d02019-08-27 17:41:15 +02001544 struct AttribInputPair {
1545 const VkVertexInputAttributeDescription *attrib = nullptr;
1546 const interface_var *input = nullptr;
1547 };
1548 std::map<uint32_t, AttribInputPair> location_map;
1549 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1550 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001551
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001552 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001553 const auto location = location_it.first;
1554 const auto attrib = location_it.second.attrib;
1555 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001556
Petr Kraus25810d02019-08-27 17:41:15 +02001557 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001558 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1559 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001560 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001561 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1562 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001563 } else if (attrib && input) {
1564 const auto attrib_type = GetFormatType(attrib->format);
1565 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001566
1567 // Type checking
1568 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001569 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1570 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1571 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001572 }
Petr Kraus25810d02019-08-27 17:41:15 +02001573 } else { // !attrib && !input
1574 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001575 }
1576 }
1577
1578 return skip;
1579}
1580
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001581bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1582 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001583 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001584
Petr Kraus25810d02019-08-27 17:41:15 +02001585 const auto rpci = pipeline->rp_state->createInfo.ptr();
1586
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001587 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001588 const VkAttachmentReference2 *reference = nullptr;
1589 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001590 const interface_var *output = nullptr;
1591 };
1592 std::map<uint32_t, Attachment> location_map;
1593
Petr Kraus25810d02019-08-27 17:41:15 +02001594 const auto subpass = rpci->pSubpasses[subpass_index];
1595 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001596 auto const &reference = subpass.pColorAttachments[i];
1597 location_map[i].reference = &reference;
1598 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1599 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1600 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001601 }
1602 }
1603
Chris Forbes47567b72017-06-09 12:09:45 -07001604 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1605
Petr Kraus25810d02019-08-27 17:41:15 +02001606 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001607 for (const auto &output_it : outputs) {
1608 auto const location = output_it.first.first;
1609 location_map[location].output = &output_it.second;
1610 }
Chris Forbes47567b72017-06-09 12:09:45 -07001611
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001612 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1613 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001614
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001615 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001616 const auto reference = location_it.second.reference;
1617 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1618 continue;
1619 }
1620
Petr Kraus25810d02019-08-27 17:41:15 +02001621 const auto location = location_it.first;
1622 const auto attachment = location_it.second.attachment;
1623 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001624 if (attachment && !output) {
1625 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001626 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1627 "Attachment %" PRIu32
1628 " not written by fragment shader; undefined values will be written to attachment",
1629 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001630 }
1631 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001632 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001633 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1634 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001635 }
Petr Kraus25810d02019-08-27 17:41:15 +02001636 } else if (attachment && output) {
1637 const auto attachment_type = GetFormatType(attachment->format);
1638 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001639
1640 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001641 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001642 skip |=
1643 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1644 "Attachment %" PRIu32
1645 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1646 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001647 }
Petr Kraus25810d02019-08-27 17:41:15 +02001648 } else { // !attachment && !output
1649 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001650 }
1651 }
1652
Petr Kraus25810d02019-08-27 17:41:15 +02001653 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001654 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1655 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1656 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001657 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1658 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001659 }
1660
Chris Forbes47567b72017-06-09 12:09:45 -07001661 return skip;
1662}
1663
Tobias Hector6663c9b2020-11-05 10:18:02 +00001664// 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 -06001665// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001666static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001667 auto type = builtin_instr.opcode();
1668 uint32_t target_id = builtin_instr.word(1);
1669 bool init_complete = false;
1670
1671 if (type == spv::OpMemberDecorate) {
1672 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1673 auto insn = entrypoint;
1674 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1675 switch (insn.opcode()) {
1676 case spv::OpTypePointer:
1677 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1678 target_id = insn.word(1);
1679 }
1680 break;
1681 case spv::OpVariable:
1682 if (insn.word(1) == target_id) {
1683 target_id = insn.word(2);
1684 init_complete = true;
1685 }
1686 break;
1687 }
1688 insn++;
1689 }
1690 }
1691
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001692 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1693
1694 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001695 std::unordered_set<uint32_t> worklist;
1696 worklist.insert(entrypoint.word(2));
1697
1698 // Follow instructions in call graph looking for writes to target
1699 while (!worklist.empty() && !found_write) {
1700 auto id_iter = worklist.begin();
1701 auto id = *id_iter;
1702 worklist.erase(id_iter);
1703
1704 auto insn = src->get_def(id);
1705 if (insn == src->end()) {
1706 continue;
1707 }
1708
1709 if (insn.opcode() == spv::OpFunction) {
1710 // Scan body of function looking for other function calls or items in our ID chain
1711 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1712 switch (insn.opcode()) {
1713 case spv::OpAccessChain:
1714 if (insn.word(3) == target_id) {
1715 if (type == spv::OpMemberDecorate) {
1716 auto value = GetConstantValue(src, insn.word(4));
1717 if (value == builtin_instr.word(2)) {
1718 target_id = insn.word(2);
1719 }
1720 } else {
1721 target_id = insn.word(2);
1722 }
1723 }
1724 break;
1725 case spv::OpStore:
1726 if (insn.word(1) == target_id) {
1727 found_write = true;
1728 }
1729 break;
1730 case spv::OpFunctionCall:
1731 worklist.insert(insn.word(3));
1732 break;
1733 }
1734 }
1735 }
1736 }
1737 return found_write;
1738}
1739
Chris Forbes47567b72017-06-09 12:09:45 -07001740// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1741// important for identifying the set of shader resources actually used by an entrypoint, for example.
1742// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1743// - NOT the shader input/output interfaces.
1744//
1745// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1746// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001747std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001748 std::unordered_set<uint32_t> ids;
1749 std::unordered_set<uint32_t> worklist;
1750 worklist.insert(entrypoint.word(2));
1751
1752 while (!worklist.empty()) {
1753 auto id_iter = worklist.begin();
1754 auto id = *id_iter;
1755 worklist.erase(id_iter);
1756
1757 auto insn = src->get_def(id);
1758 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001759 // 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 -07001760 // that we may not care about.
1761 continue;
1762 }
1763
1764 // Try to add to the output set
1765 if (!ids.insert(id).second) {
1766 continue; // If we already saw this id, we don't want to walk it again.
1767 }
1768
1769 switch (insn.opcode()) {
1770 case spv::OpFunction:
1771 // Scan whole body of the function, enlisting anything interesting
1772 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1773 switch (insn.opcode()) {
1774 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001775 worklist.insert(insn.word(3)); // ptr
1776 break;
1777 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001778 worklist.insert(insn.word(1)); // ptr
1779 break;
1780 case spv::OpAccessChain:
1781 case spv::OpInBoundsAccessChain:
1782 worklist.insert(insn.word(3)); // base ptr
1783 break;
1784 case spv::OpSampledImage:
1785 case spv::OpImageSampleImplicitLod:
1786 case spv::OpImageSampleExplicitLod:
1787 case spv::OpImageSampleDrefImplicitLod:
1788 case spv::OpImageSampleDrefExplicitLod:
1789 case spv::OpImageSampleProjImplicitLod:
1790 case spv::OpImageSampleProjExplicitLod:
1791 case spv::OpImageSampleProjDrefImplicitLod:
1792 case spv::OpImageSampleProjDrefExplicitLod:
1793 case spv::OpImageFetch:
1794 case spv::OpImageGather:
1795 case spv::OpImageDrefGather:
1796 case spv::OpImageRead:
1797 case spv::OpImage:
1798 case spv::OpImageQueryFormat:
1799 case spv::OpImageQueryOrder:
1800 case spv::OpImageQuerySizeLod:
1801 case spv::OpImageQuerySize:
1802 case spv::OpImageQueryLod:
1803 case spv::OpImageQueryLevels:
1804 case spv::OpImageQuerySamples:
1805 case spv::OpImageSparseSampleImplicitLod:
1806 case spv::OpImageSparseSampleExplicitLod:
1807 case spv::OpImageSparseSampleDrefImplicitLod:
1808 case spv::OpImageSparseSampleDrefExplicitLod:
1809 case spv::OpImageSparseSampleProjImplicitLod:
1810 case spv::OpImageSparseSampleProjExplicitLod:
1811 case spv::OpImageSparseSampleProjDrefImplicitLod:
1812 case spv::OpImageSparseSampleProjDrefExplicitLod:
1813 case spv::OpImageSparseFetch:
1814 case spv::OpImageSparseGather:
1815 case spv::OpImageSparseDrefGather:
1816 case spv::OpImageTexelPointer:
1817 worklist.insert(insn.word(3)); // Image or sampled image
1818 break;
1819 case spv::OpImageWrite:
1820 worklist.insert(insn.word(1)); // Image -- different operand order to above
1821 break;
1822 case spv::OpFunctionCall:
1823 for (uint32_t i = 3; i < insn.len(); i++) {
1824 worklist.insert(insn.word(i)); // fn itself, and all args
1825 }
1826 break;
1827
1828 case spv::OpExtInst:
1829 for (uint32_t i = 5; i < insn.len(); i++) {
1830 worklist.insert(insn.word(i)); // Operands to ext inst
1831 }
1832 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001833
1834 default: {
1835 if (AtomicOperation(insn.opcode())) {
1836 if (insn.opcode() == spv::OpAtomicStore) {
1837 worklist.insert(insn.word(1)); // ptr
1838 } else {
1839 worklist.insert(insn.word(3)); // ptr
1840 }
1841 }
1842 break;
1843 }
Chris Forbes47567b72017-06-09 12:09:45 -07001844 }
1845 }
1846 break;
1847 }
1848 }
1849
1850 return ids;
1851}
1852
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001853PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1854 const shader_struct_member &push_constant_used_in_shader,
1855 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001856 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001857 const auto used_bytes_size = used_bytes->size();
1858 if (used_bytes_size == 0) return PC_Byte_Updated;
1859
1860 const auto push_constant_data_update_size = push_constant_data_update.size();
1861 const auto *data = push_constant_data_update.data();
1862 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1863 if (used_bytes_size <= push_constant_data_update_size) {
1864 return PC_Byte_Updated;
1865 }
1866 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1867
1868 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1869 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1870 return PC_Byte_Updated;
1871 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001872 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001873
locke-lunargde3f0fa2020-09-10 11:55:31 -06001874 uint32_t i = 0;
1875 for (const auto used : *used_bytes) {
1876 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001877 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001878 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001879 return PC_Byte_Not_Set;
1880 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001881 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001882 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001883 }
1884 }
1885 ++i;
1886 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001887 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001888}
1889
1890bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1891 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001892 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001893 // 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 -06001894 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1895 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1896 return skip;
1897 }
1898 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001899
locke-lunargde3f0fa2020-09-10 11:55:31 -06001900 bool found_stage = false;
1901 for (auto const &range : *push_constant_ranges) {
1902 if (range.stageFlags & pStage->stage) {
1903 found_stage = true;
1904 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001905 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001906 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001907 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001908 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001909 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001910 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001911 const auto ret =
1912 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001913
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001914 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001915 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1916 LogObjectList objlist(src->vk_shader_module);
1917 objlist.add(pipeline.pipeline_layout->layout);
1918 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1919 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1920 string_VkShaderStageFlags(pStage->stage).c_str(),
1921 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1922 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001923 }
1924 }
1925 }
1926
locke-lunargde3f0fa2020-09-10 11:55:31 -06001927 if (!found_stage) {
1928 LogObjectList objlist(src->vk_shader_module);
1929 objlist.add(pipeline.pipeline_layout->layout);
1930 skip |= LogError(
1931 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1932 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1933 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001934 }
Chris Forbes47567b72017-06-09 12:09:45 -07001935 return skip;
1936}
1937
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001938bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1939 VkShaderStageFlagBits stage) const {
1940 bool skip = false;
1941
1942 // Currently all builtin tested are only found in fragment shaders
1943 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1944 return skip;
1945 }
1946
1947 for (const auto id : accessible_ids) {
1948 auto insn = src->get_def(id);
1949 const decoration_set decorations = src->get_decorations(insn.word(2));
1950
1951 // Built-ins are obtained from OpVariable
1952 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1953 auto type_pointer = src->get_def(insn.word(1));
1954 assert(type_pointer.opcode() == spv::OpTypePointer);
1955
1956 auto type = src->get_def(type_pointer.word(3));
1957 if (type.opcode() == spv::OpTypeArray) {
1958 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1959
1960 switch (decorations.builtin) {
1961 case spv::BuiltInSampleMask:
1962 // Handles both the input and output sampleMask
1963 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1964 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1965 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1966 "maxSampleMaskWords of %u in %s.",
1967 length, phys_dev_props.limits.maxSampleMaskWords,
1968 report_data->FormatHandle(src->vk_shader_module).c_str());
1969 }
1970 break;
1971 }
1972 }
1973 }
1974 }
1975
1976 return skip;
1977}
1978
Chris Forbes47567b72017-06-09 12:09:45 -07001979// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001980bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001981 bool skip = false;
1982
1983 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1984
1985 if (spec) {
1986 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001987 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001988 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1989 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1990 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1991 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1992 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001993
1994 continue;
1995 }
Chris Forbes47567b72017-06-09 12:09:45 -07001996 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001997 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
1998 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1999 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2000 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2001 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002002 }
2003 }
2004 }
2005
2006 return skip;
2007}
2008
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002009// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002010static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2011 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002012 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002013 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002014 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002015 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002016
2017 // 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 -05002018 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2019 if (type.opcode() == spv::OpTypeRuntimeArray) {
2020 descriptor_count = 0;
2021 type = module->get_def(type.word(2));
2022 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002023 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002024 type = module->get_def(type.word(2));
2025 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002026 if (type.word(2) == spv::StorageClassStorageBuffer) {
2027 is_storage_buffer = true;
2028 }
Chris Forbes47567b72017-06-09 12:09:45 -07002029 type = module->get_def(type.word(3));
2030 }
2031 }
2032
2033 switch (type.opcode()) {
2034 case spv::OpTypeStruct: {
2035 for (auto insn : *module) {
2036 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
2037 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002038 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002039 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2040 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2041 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002042 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002043 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2044 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2045 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2046 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002047 }
Chris Forbes47567b72017-06-09 12:09:45 -07002048 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002049 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2050 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2051 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002052 }
2053 }
2054 }
2055
2056 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002057 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002058 }
2059
2060 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002061 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2062 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2063 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002064
Chris Forbes73c00bf2018-06-22 16:28:06 -07002065 case spv::OpTypeSampledImage: {
2066 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2067 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2068 auto image_type = module->get_def(type.word(2));
2069 auto dim = image_type.word(3);
2070 auto sampled = image_type.word(7);
2071 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002072 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2073 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002074 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002075 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002076 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2077 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002078
2079 case spv::OpTypeImage: {
2080 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2081 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2082 auto dim = type.word(3);
2083 auto sampled = type.word(7);
2084
2085 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002086 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2087 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002088 } else if (dim == spv::DimBuffer) {
2089 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002090 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
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_TEXEL_BUFFER);
2094 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002095 }
2096 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002097 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2098 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2099 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002100 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002101 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2102 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002103 }
2104 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002105 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002106 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2107 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002108 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002109
2110 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2111 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002112 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002113 }
2114}
2115
Jeff Bolze54ae892018-09-08 12:16:29 -05002116static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002117 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002118 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2119 if (ss.tellp()) ss << ", ";
2120 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002121 }
2122 return ss.str();
2123}
2124
sfricke-samsung0065ce02020-12-03 22:46:37 -08002125bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002126 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002127 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 -05002128 return true;
2129 }
2130 }
2131
2132 return false;
2133}
2134
sfricke-samsung0065ce02020-12-03 22:46:37 -08002135bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002136 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002137 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002138 return true;
2139 }
2140 }
2141
2142 return false;
2143}
2144
locke-lunarg63e4daf2020-08-17 17:53:25 -06002145bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2146 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002147 bool skip = false;
2148
locke-lunarg63e4daf2020-08-17 17:53:25 -06002149 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002150 switch (stage) {
2151 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002152 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2153 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2154 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2155 case VK_SHADER_STAGE_MISS_BIT_NV:
2156 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2157 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2158 case VK_SHADER_STAGE_TASK_BIT_NV:
2159 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002160 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002161 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002162 break;
2163 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002164 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2165 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002166 break;
2167 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002168 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2169 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002170 break;
2171 }
2172 }
2173
Chris Forbes47567b72017-06-09 12:09:45 -07002174 return skip;
2175}
2176
Jeff Bolz526f2d52019-09-18 13:18:08 -05002177bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002178 bool skip = false;
2179
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002180 auto const subgroup_props = phys_dev_props_core11;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002181 const VkSubgroupFeatureFlags supported_stages = subgroup_props.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05002182
Jeff Bolz526f2d52019-09-18 13:18:08 -05002183 for (auto inst : *module) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002184 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2185 if (GroupOperation(inst.opcode()) == true) {
2186 // Check the quad operations.
2187 if ((inst.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (inst.opcode() == spv::OpGroupNonUniformQuadSwap)) {
Jeff Bolzee743412019-06-20 22:24:32 -05002188 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002189 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
sfricke-samsung0065ce02020-12-03 22:46:37 -08002190 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2191 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolzee743412019-06-20 22:24:32 -05002192 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002193 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002194
sfricke-samsung0065ce02020-12-03 22:46:37 -08002195 uint32_t scope_type = spv::ScopeMax;
sfricke-samsung95180142020-12-10 20:58:20 -08002196 if (inst.opcode() == spv::OpGroupNonUniformPartitionNV) {
2197 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2198 scope_type = spv::ScopeSubgroup;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002199 } else {
sfricke-samsung486a51e2021-01-02 00:10:15 -08002200 // "All <id> used for Scope <id> must be of an OpConstant"
sfricke-samsung95180142020-12-10 20:58:20 -08002201 auto scope_id = module->get_def(inst.word(3));
sfricke-samsung486a51e2021-01-02 00:10:15 -08002202 scope_type = scope_id.word(3);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002203 }
2204
2205 if (scope_type == spv::ScopeSubgroup) {
2206 // "Group operations with subgroup scope" must have stage support
2207 skip |=
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002208 RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002209 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
2210 }
2211
2212 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2213 auto type = module->get_def(inst.word(1));
2214
2215 if (type.opcode() == spv::OpTypeVector) {
2216 // Get the element type
2217 type = module->get_def(type.word(2));
2218 }
2219
2220 if (type.opcode() == spv::OpTypeBool) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05002221 break;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002222 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002223
sfricke-samsung0065ce02020-12-03 22:46:37 -08002224 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2225 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002226
sfricke-samsung0065ce02020-12-03 22:46:37 -08002227 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2228 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2229 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2230 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2231 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002232 }
2233 }
2234 }
Jeff Bolzee743412019-06-20 22:24:32 -05002235 }
2236
2237 return skip;
2238}
2239
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002240bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002241 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002242 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2243 pStage->stage == VK_SHADER_STAGE_ALL) {
2244 return false;
2245 }
2246
2247 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002248 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002249
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002250 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002251 struct Variable {
2252 uint32_t baseTypePtrID;
2253 uint32_t ID;
2254 uint32_t storageClass;
2255 };
2256 std::vector<Variable> variables;
2257
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002258 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002259 bool is_iso_lines = false;
2260 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002261
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002262 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002263
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002264 for (auto insn : *src) {
2265 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002266 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002267 case spv::OpDecorate:
2268 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002269 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002270 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002271 break;
2272 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002273 default:
2274 break;
2275 }
2276 break;
2277 // Find all input and output variables
2278 case spv::OpVariable: {
2279 Variable var = {};
2280 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002281 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2282 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002283 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002284 var.baseTypePtrID = insn.word(1);
2285 var.ID = insn.word(2);
2286 variables.push_back(var);
2287 }
2288 break;
2289 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002290 case spv::OpExecutionMode:
2291 if (insn.word(1) == entrypoint.word(2)) {
2292 switch (insn.word(2)) {
2293 default:
2294 break;
2295 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002296 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002297 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002298 case spv::ExecutionModeIsolines:
2299 is_iso_lines = true;
2300 break;
2301 case spv::ExecutionModePointMode:
2302 is_point_mode = true;
2303 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002304 }
2305 }
2306 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002307 default:
2308 break;
2309 }
2310 }
2311
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002312 bool strip_output_array_level =
2313 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2314 bool strip_input_array_level =
2315 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2316 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2317
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002318 uint32_t num_comp_in = 0, num_comp_out = 0;
2319 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002320
2321 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2322 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2323
2324 // Find max component location used for input variables.
2325 for (auto &var : inputs) {
2326 int location = var.first.first;
2327 int component = var.first.second;
2328 interface_var &iv = var.second;
2329
2330 // Only need to look at the first location, since we use the type's whole size
2331 if (iv.offset != 0) {
2332 continue;
2333 }
2334
2335 if (iv.is_patch) {
2336 continue;
2337 }
2338
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002339 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2340 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002341 }
2342
2343 // Find max component location used for output variables.
2344 for (auto &var : outputs) {
2345 int location = var.first.first;
2346 int component = var.first.second;
2347 interface_var &iv = var.second;
2348
2349 // Only need to look at the first location, since we use the type's whole size
2350 if (iv.offset != 0) {
2351 continue;
2352 }
2353
2354 if (iv.is_patch) {
2355 continue;
2356 }
2357
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002358 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2359 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002360 }
2361
2362 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2363 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002364 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002365 // Check if the variable is a patch. Patches can also be members of blocks,
2366 // but if they are then the top-level arrayness has already been stripped
2367 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002368 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002369
2370 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002371 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002372 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002373 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002374 }
2375 }
2376
2377 switch (pStage->stage) {
2378 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002379 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002380 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2381 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2382 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2383 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002384 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002385 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002386 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002387 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2388 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2389 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2390 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002391 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002392 break;
2393
2394 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002395 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002396 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2397 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2398 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2399 "components by %u components",
2400 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002401 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002402 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002403 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002404 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002405 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2406 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2407 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2408 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002409 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002410 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002411 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2412 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2413 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2414 "components by %u components",
2415 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002416 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002417 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002418 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002419 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002420 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2421 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2422 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2423 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002424 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002425 break;
2426
2427 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002429 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2430 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2431 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2432 "components by %u components",
2433 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002435 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002436 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002437 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002438 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2439 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2440 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2441 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002442 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002443 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002444 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2445 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2446 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2447 "components by %u components",
2448 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002449 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002450 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002451 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002452 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002453 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2454 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2455 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2456 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002457 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002458 // Portability validation
2459 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2460 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2461 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2462 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2463 " is using abstract patch type IsoLines, but this is not supported on this platform");
2464 }
2465 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2466 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2467 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2468 " is using abstract patch type PointMode, but this is not supported on this platform");
2469 }
2470 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002471 break;
2472
2473 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002474 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002475 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2476 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2477 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2478 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002479 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002480 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002481 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002482 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2483 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2484 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2485 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002486 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002487 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002488 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2489 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2490 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2491 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002493 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002494 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002495 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2496 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2497 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2498 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002499 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002500 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002501 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2502 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2503 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2504 "components by %u components",
2505 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002506 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002507 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002508 break;
2509
2510 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002511 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002512 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2513 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2514 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2515 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002516 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002517 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002518 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002519 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2520 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2521 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2522 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002523 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002524 break;
2525
Jeff Bolz148d94e2018-12-13 21:25:56 -06002526 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2527 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2528 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2529 case VK_SHADER_STAGE_MISS_BIT_NV:
2530 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2531 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2532 case VK_SHADER_STAGE_TASK_BIT_NV:
2533 case VK_SHADER_STAGE_MESH_BIT_NV:
2534 break;
2535
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002536 default:
2537 assert(false); // This should never happen
2538 }
2539 return skip;
2540}
2541
sfricke-samsungdc96f302020-03-18 20:42:10 -07002542bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2543 bool skip = false;
2544 uint32_t total_resources = 0;
2545
2546 // Only currently testing for graphics and compute pipelines
2547 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2548 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2549 return false;
2550 }
2551
2552 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2553 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2554 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2555 }
2556
2557 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2558 // input from CreatePipeline and CreatePipelineLayout level
2559 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2560 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2561 continue;
2562 }
2563
2564 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2565 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2566 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2567 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2568 // Check only descriptor types listed in maxPerStageResources description in spec
2569 switch (binding->descriptorType) {
2570 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2571 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2572 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2573 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2574 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2575 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2576 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2577 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2578 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2579 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2580 total_resources += binding->descriptorCount;
2581 break;
2582 default:
2583 break;
2584 }
2585 }
2586 }
2587 }
2588
2589 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2590 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2591 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2592 skip |= LogError(pipeline->pipeline, vuid,
2593 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2594 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2595 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2596 }
2597
2598 return skip;
2599}
2600
Jeff Bolze4356752019-03-07 11:23:46 -06002601// copy the specialization constant value into buf, if it is present
2602void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2603 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2604
2605 if (spec && spec_id < spec->mapEntryCount) {
2606 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2607 }
2608}
2609
2610// Fill in value with the constant or specialization constant value, if available.
2611// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002612static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002613 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2614 auto type_id = src->get_def(insn.word(1));
2615 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2616 return false;
2617 }
2618 switch (insn.opcode()) {
2619 case spv::OpSpecConstant:
2620 *value = insn.word(3);
2621 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2622 return true;
2623 case spv::OpConstant:
2624 *value = insn.word(3);
2625 return true;
2626 default:
2627 return false;
2628 }
2629}
2630
2631// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002632VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002633 switch (insn.opcode()) {
2634 case spv::OpTypeInt:
2635 switch (insn.word(2)) {
2636 case 8:
2637 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2638 case 16:
2639 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2640 case 32:
2641 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2642 case 64:
2643 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2644 default:
2645 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2646 }
2647 case spv::OpTypeFloat:
2648 switch (insn.word(2)) {
2649 case 16:
2650 return VK_COMPONENT_TYPE_FLOAT16_NV;
2651 case 32:
2652 return VK_COMPONENT_TYPE_FLOAT32_NV;
2653 case 64:
2654 return VK_COMPONENT_TYPE_FLOAT64_NV;
2655 default:
2656 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2657 }
2658 default:
2659 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2660 }
2661}
2662
2663// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2664// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002665bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002666 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002667 bool skip = false;
2668
2669 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2670 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2671 // Map SPIR-V result ID to the ID of its type.
2672 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2673
2674 struct CoopMatType {
2675 uint32_t scope, rows, cols;
2676 VkComponentTypeNV component_type;
2677 bool all_constant;
2678
2679 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2680
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002681 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002682 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2683 spirv_inst_iter insn = src->get_def(id);
2684 uint32_t component_type_id = insn.word(2);
2685 uint32_t scope_id = insn.word(3);
2686 uint32_t rows_id = insn.word(4);
2687 uint32_t cols_id = insn.word(5);
2688 auto component_type_iter = src->get_def(component_type_id);
2689 auto scope_iter = src->get_def(scope_id);
2690 auto rows_iter = src->get_def(rows_id);
2691 auto cols_iter = src->get_def(cols_id);
2692
2693 all_constant = true;
2694 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2695 all_constant = false;
2696 }
2697 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2698 all_constant = false;
2699 }
2700 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2701 all_constant = false;
2702 }
2703 component_type = GetComponentType(component_type_iter, src);
2704 }
2705 };
2706
2707 bool seen_coopmat_capability = false;
2708
2709 for (auto insn : *src) {
2710 // Whitelist instructions whose result can be a cooperative matrix type, and
2711 // keep track of their types. It would be nice if SPIRV-Headers generated code
2712 // to identify which instructions have a result type and result id. Lacking that,
2713 // this whitelist is based on the set of instructions that
2714 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2715 switch (insn.opcode()) {
2716 case spv::OpLoad:
2717 case spv::OpCooperativeMatrixLoadNV:
2718 case spv::OpCooperativeMatrixMulAddNV:
2719 case spv::OpSNegate:
2720 case spv::OpFNegate:
2721 case spv::OpIAdd:
2722 case spv::OpFAdd:
2723 case spv::OpISub:
2724 case spv::OpFSub:
2725 case spv::OpFDiv:
2726 case spv::OpSDiv:
2727 case spv::OpUDiv:
2728 case spv::OpMatrixTimesScalar:
2729 case spv::OpConstantComposite:
2730 case spv::OpCompositeConstruct:
2731 case spv::OpConvertFToU:
2732 case spv::OpConvertFToS:
2733 case spv::OpConvertSToF:
2734 case spv::OpConvertUToF:
2735 case spv::OpUConvert:
2736 case spv::OpSConvert:
2737 case spv::OpFConvert:
2738 id_to_type_id[insn.word(2)] = insn.word(1);
2739 break;
2740 default:
2741 break;
2742 }
2743
2744 switch (insn.opcode()) {
2745 case spv::OpDecorate:
2746 if (insn.word(2) == spv::DecorationSpecId) {
2747 id_to_spec_id[insn.word(1)] = insn.word(3);
2748 }
2749 break;
2750 case spv::OpCapability:
2751 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2752 seen_coopmat_capability = true;
2753
2754 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002755 skip |= LogError(
2756 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2757 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2758 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002759 }
2760 }
2761 break;
2762 case spv::OpMemoryModel:
2763 // If the capability isn't enabled, don't bother with the rest of this function.
2764 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2765 if (!seen_coopmat_capability) {
2766 return skip;
2767 }
2768 break;
2769 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002770 CoopMatType m;
2771 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002772
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002773 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002774 // Validate that the type parameters are all supported for one of the
2775 // operands of a cooperative matrix property.
2776 bool valid = false;
2777 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002778 if (cooperative_matrix_properties[i].AType == m.component_type &&
2779 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2780 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002781 valid = true;
2782 break;
2783 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002784 if (cooperative_matrix_properties[i].BType == m.component_type &&
2785 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2786 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002787 valid = true;
2788 break;
2789 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002790 if (cooperative_matrix_properties[i].CType == m.component_type &&
2791 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2792 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002793 valid = true;
2794 break;
2795 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002796 if (cooperative_matrix_properties[i].DType == m.component_type &&
2797 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2798 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002799 valid = true;
2800 break;
2801 }
2802 }
2803 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002804 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2805 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2806 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002807 }
2808 }
2809 break;
2810 }
2811 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002812 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002813 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2814 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2815 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2816 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002817 // Couldn't find type of matrix
2818 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002819 break;
2820 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002821 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2822 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2823 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2824 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002825
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002826 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002827 // Validate that the type parameters are all supported for the same
2828 // cooperative matrix property.
2829 bool valid = false;
2830 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002831 if (cooperative_matrix_properties[i].AType == a.component_type &&
2832 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2833 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002834
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002835 cooperative_matrix_properties[i].BType == b.component_type &&
2836 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2837 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002838
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002839 cooperative_matrix_properties[i].CType == c.component_type &&
2840 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2841 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002842
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002843 cooperative_matrix_properties[i].DType == d.component_type &&
2844 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2845 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002846 valid = true;
2847 break;
2848 }
2849 }
2850 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002851 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2852 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2853 "VkCooperativeMatrixPropertiesNV",
2854 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002855 }
2856 }
2857 break;
2858 }
2859 default:
2860 break;
2861 }
2862 }
2863
2864 return skip;
2865}
2866
John Zulaufac4c6e12019-07-01 16:05:58 -06002867bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002868 auto entrypoint_id = entrypoint.word(2);
2869
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002870 // The first denorm execution mode encountered, along with its bit width.
2871 // Used to check if SeparateDenormSettings is respected.
2872 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002873
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002874 // The first rounding mode encountered, along with its bit width.
2875 // Used to check if SeparateRoundingModeSettings is respected.
2876 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002877
2878 bool skip = false;
2879
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002880 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002881 uint32_t invocations = 0;
2882
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002883 for (auto insn : *src) {
2884 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2885 auto mode = insn.word(2);
2886 switch (mode) {
2887 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2888 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002889 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2890 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2891 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002892 skip |= LogError(
2893 device, kVUID_Core_Shader_FeatureNotEnabled,
2894 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2895 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002896 }
2897 break;
2898 }
2899
2900 case spv::ExecutionModeDenormPreserve: {
2901 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002902 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2903 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2904 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002905 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2906 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2907 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002908 }
2909
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002910 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2911 // Register the first denorm execution mode found
2912 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002913 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002914 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002915 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002916 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002917 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2918 "Shader uses different denorm execution modes for 16 and 64-bit but "
2919 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002920 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002921 }
2922 break;
2923
Mike Schuchardt2df08912020-12-15 16:28:09 -08002924 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002925 break;
2926
Mike Schuchardt2df08912020-12-15 16:28:09 -08002927 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002928 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2929 "Shader uses different denorm execution modes for different bit widths but "
2930 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002931 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002932 break;
2933
2934 default:
2935 break;
2936 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002937 }
2938 break;
2939 }
2940
2941 case spv::ExecutionModeDenormFlushToZero: {
2942 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002943 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2944 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2945 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002946 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2947 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2948 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002949 }
2950
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002951 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2952 // Register the first denorm execution mode found
2953 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002954 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002955 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002956 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002957 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002958 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2959 "Shader uses different denorm execution modes for 16 and 64-bit but "
2960 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002961 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002962 }
2963 break;
2964
Mike Schuchardt2df08912020-12-15 16:28:09 -08002965 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002966 break;
2967
Mike Schuchardt2df08912020-12-15 16:28:09 -08002968 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002969 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2970 "Shader uses different denorm execution modes for different bit widths but "
2971 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002972 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002973 break;
2974
2975 default:
2976 break;
2977 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002978 }
2979 break;
2980 }
2981
2982 case spv::ExecutionModeRoundingModeRTE: {
2983 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002984 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2985 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2986 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002987 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2988 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2989 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002990 }
2991
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002992 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2993 // Register the first rounding mode found
2994 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002995 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002996 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002997 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002998 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002999 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3000 "Shader uses different rounding modes for 16 and 64-bit but "
3001 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003002 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003003 }
3004 break;
3005
Mike Schuchardt2df08912020-12-15 16:28:09 -08003006 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003007 break;
3008
Mike Schuchardt2df08912020-12-15 16:28:09 -08003009 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003010 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3011 "Shader uses different rounding modes for different bit widths but "
3012 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003013 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003014 break;
3015
3016 default:
3017 break;
3018 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003019 }
3020 break;
3021 }
3022
3023 case spv::ExecutionModeRoundingModeRTZ: {
3024 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003025 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3026 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3027 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003028 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3029 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3030 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003031 }
3032
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003033 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3034 // Register the first rounding mode found
3035 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003036 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003037 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003038 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003039 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003040 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3041 "Shader uses different rounding modes for 16 and 64-bit but "
3042 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003043 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003044 }
3045 break;
3046
Mike Schuchardt2df08912020-12-15 16:28:09 -08003047 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003048 break;
3049
Mike Schuchardt2df08912020-12-15 16:28:09 -08003050 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003051 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3052 "Shader uses different rounding modes for different bit widths but "
3053 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003054 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003055 break;
3056
3057 default:
3058 break;
3059 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003060 }
3061 break;
3062 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003063
3064 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003065 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003066 break;
3067 }
3068
3069 case spv::ExecutionModeInvocations: {
3070 invocations = insn.word(3);
3071 break;
3072 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003073 }
3074 }
3075 }
3076
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003077 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003078 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003079 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3080 "Geometry shader entry point must have an OpExecutionMode instruction that "
3081 "specifies a maximum output vertex count that is greater than 0 and less "
3082 "than or equal to maxGeometryOutputVertices. "
3083 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003084 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003085 }
3086
3087 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003088 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3089 "Geometry shader entry point must have an OpExecutionMode instruction that "
3090 "specifies an invocation count that is greater than 0 and less "
3091 "than or equal to maxGeometryShaderInvocations. "
3092 "Invocations=%d, maxGeometryShaderInvocations=%d",
3093 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003094 }
3095 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003096 return skip;
3097}
3098
locke-lunargd9a069d2019-09-17 01:50:19 -06003099uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003100 auto type = module->get_def(type_id);
3101
3102 while (true) {
3103 switch (type.opcode()) {
3104 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003105 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003106 case spv::OpTypeSampledImage:
3107 type = module->get_def(type.word(2));
3108 break;
3109 case spv::OpTypePointer:
3110 type = module->get_def(type.word(3));
3111 break;
3112 case spv::OpTypeImage: {
3113 auto dim = type.word(3);
3114 auto arrayed = type.word(5);
3115 auto msaa = type.word(6);
3116
Chris Forbes74ba2232018-08-27 15:19:27 -07003117 uint32_t bits = 0;
3118 switch (GetFundamentalType(module, type.word(2))) {
3119 case FORMAT_TYPE_FLOAT:
3120 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3121 break;
3122 case FORMAT_TYPE_UINT:
3123 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3124 break;
3125 case FORMAT_TYPE_SINT:
3126 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3127 break;
3128 default:
3129 break;
3130 }
3131
Chris Forbes47567b72017-06-09 12:09:45 -07003132 switch (dim) {
3133 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003134 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3135 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003136 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003137 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3138 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3139 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003140 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003141 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3142 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003143 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003144 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3145 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003146 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003147 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3148 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003149 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003150 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003151 }
3152 }
3153 default:
3154 return 0;
3155 }
3156 }
3157}
3158
3159// For given pipelineLayout verify that the set_layout_node at slot.first
3160// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003161static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003162 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003163 if (!pipelineLayout) return nullptr;
3164
3165 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3166
3167 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3168}
3169
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003170int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3171 if (module == nullptr) return -1;
3172
3173 auto type = module->get_def(resource.type_id);
3174 while (true) {
3175 switch (type.opcode()) {
3176 case spv::OpTypeSampledImage:
3177 type = module->get_def(type.word(2));
3178 break;
3179 case spv::OpTypePointer:
3180 type = module->get_def(type.word(3));
3181 break;
3182 case spv::OpTypeImage:
3183 return type.word(3);
3184 default:
3185 return -1;
3186 }
3187 }
3188}
3189
3190bool 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 -06003191 for (auto insn : *src) {
3192 if (insn.opcode() == spv::OpEntryPoint) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003193 auto execution_model = insn.word(1);
3194 auto entrypoint_stage_bits = ExecutionModelToShaderStageFlagBits(execution_model);
3195 if (entrypoint_stage_bits == VK_SHADER_STAGE_COMPUTE_BIT) {
Locke1ec6d952019-04-02 11:57:21 -06003196 auto entrypoint_id = insn.word(2);
3197 for (auto insn1 : *src) {
3198 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3199 insn1.word(2) == spv::ExecutionModeLocalSize) {
3200 local_size_x = insn1.word(3);
3201 local_size_y = insn1.word(4);
3202 local_size_z = insn1.word(5);
3203 return true;
3204 }
3205 }
3206 }
3207 }
3208 }
3209 return false;
3210}
3211
locke-lunargd9a069d2019-09-17 01:50:19 -06003212void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003213 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003214 bool is_point_mode = false;
3215
3216 for (auto insn : *src) {
3217 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3218 switch (insn.word(2)) {
3219 case spv::ExecutionModePointMode:
3220 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3221 is_point_mode = true;
3222 break;
3223
3224 case spv::ExecutionModeOutputPoints:
3225 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3226 break;
3227
3228 case spv::ExecutionModeIsolines:
3229 case spv::ExecutionModeOutputLineStrip:
3230 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3231 break;
3232
3233 case spv::ExecutionModeTriangles:
3234 case spv::ExecutionModeQuads:
3235 case spv::ExecutionModeOutputTriangleStrip:
3236 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3237 break;
3238 }
3239 }
3240 }
3241
3242 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3243}
3244
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003245// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3246// o If there is only a vertex shader : gl_PointSize must be written when using points
3247// o If there is a geometry or tessellation shader:
3248// - If shaderTessellationAndGeometryPointSize feature is enabled:
3249// * gl_PointSize must be written in the final geometry stage
3250// - If shaderTessellationAndGeometryPointSize feature is disabled:
3251// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003252bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003253 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003254 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3255 return false;
3256 }
3257
3258 bool pointsize_written = false;
3259 bool skip = false;
3260
3261 // Search for PointSize built-in decorations
3262 std::vector<uint32_t> pointsize_builtin_offsets;
3263 spirv_inst_iter insn = entrypoint;
3264 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3265 if (insn.opcode() == spv::OpMemberDecorate) {
3266 if (insn.word(3) == spv::DecorationBuiltIn) {
3267 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003268 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003269 }
3270 }
3271 } else if (insn.opcode() == spv::OpDecorate) {
3272 if (insn.word(2) == spv::DecorationBuiltIn) {
3273 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003274 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003275 }
3276 }
3277 }
3278
3279 insn++;
3280 }
3281
3282 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003283 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003284 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003285 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3286 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3287 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003288 }
3289 } else if (!pointsize_written) {
3290 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003291 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3292 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3293 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003294 }
3295 return skip;
3296}
John Zulauf14c355b2019-06-27 16:09:37 -06003297
Tobias Hector6663c9b2020-11-05 10:18:02 +00003298bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3299 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3300 bool primitiverate_written = false;
3301 bool viewportindex_written = false;
3302 bool viewportmask_written = false;
3303 bool skip = false;
3304
3305 // Check if the primitive shading rate is written
3306 spirv_inst_iter insn = entrypoint;
3307 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3308 if (insn.opcode() == spv::OpMemberDecorate) {
3309 if (insn.word(3) == spv::DecorationBuiltIn) {
3310 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3311 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3312 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3313 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3314 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3315 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3316 }
3317 }
3318 } else if (insn.opcode() == spv::OpDecorate) {
3319 if (insn.word(2) == spv::DecorationBuiltIn) {
3320 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3321 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3322 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3323 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3324 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3325 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3326 }
3327 }
3328 }
3329
3330 insn++;
3331 }
3332
Tony-LunarGd44844c2021-01-22 13:24:37 -07003333 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3334 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003335 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3336 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003337 skip |= LogError(pipeline->pipeline,
3338 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3339 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3340 "multiple viewports "
3341 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3342 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003343 }
3344
3345 if (primitiverate_written && viewportindex_written) {
3346 skip |= LogError(pipeline->pipeline,
3347 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3348 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3349 "ViewportIndex built-ins,"
3350 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3351 string_VkShaderStageFlagBits(stage));
3352 }
3353
3354 if (primitiverate_written && viewportmask_written) {
3355 skip |= LogError(pipeline->pipeline,
3356 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3357 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3358 "ViewportMaskNV built-ins,"
3359 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3360 string_VkShaderStageFlagBits(stage));
3361 }
3362 }
3363 return skip;
3364}
3365
sfricke-samsung486a51e2021-01-02 00:10:15 -08003366// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
3367bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module) const {
3368 bool skip = false;
3369
3370 for (auto insn : *module) {
3371 switch (insn.opcode()) {
3372 case spv::OpReadClockKHR: {
3373 auto scope_id = module->get_def(insn.word(3));
3374 auto scope_type = scope_id.word(3);
3375 // if scope isn't Subgroup or Device, spirv-val will catch
3376 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3377 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3378 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3379 report_data->FormatHandle(module->vk_shader_module).c_str());
3380 } else if ((scope_type == spv::ScopeDevice) &&
3381 (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3382 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3383 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3384 report_data->FormatHandle(module->vk_shader_module).c_str());
3385 }
3386 break;
3387 }
3388 }
3389 }
3390 return skip;
3391}
3392
John Zulauf14c355b2019-06-27 16:09:37 -06003393bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3394 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003395 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003396 bool skip = false;
3397
3398 // Check the module
3399 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003400 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3401 "%s does not contain valid spirv for stage %s.",
3402 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003403 }
3404
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003405 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3406 // specializations should be applied and validated.
3407 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3408 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3409 // Gather the specialization-constant values.
3410 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003411 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003412 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3413 id_value_map.reserve(specialization_info->mapEntryCount);
3414 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3415 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003416
Jeremy Hayes521221d2020-01-15 16:48:49 -07003417 // Expect only scalar types.
3418 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3419 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3420 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003421 }
3422
3423 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003424 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003425 spvtools::Optimizer optimizer(spirv_environment);
3426 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3427 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003428 skip |= LogError(
3429 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003430 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3431 };
3432 optimizer.SetMessageConsumer(consumer);
3433 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3434 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3435 std::vector<uint32_t> specialized_spirv;
3436 auto const optimized =
3437 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3438 assert(optimized == true);
3439
3440 if (optimized) {
3441 spv_context ctx = spvContextCreate(spirv_environment);
3442 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3443 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003444 spvtools::ValidatorOptions options;
3445 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003446 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3447 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003448 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003449 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3450 report_data->FormatHandle(module->vk_shader_module).c_str(),
3451 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003452 }
3453
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003454 spvDiagnosticDestroy(diag);
3455 spvContextDestroy(ctx);
3456 }
3457 }
3458
John Zulauf14c355b2019-06-27 16:09:37 -06003459 // Check the entrypoint
3460 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003461 skip |=
3462 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3463 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003464 }
3465 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3466
3467 // Mark accessible ids
3468 auto &accessible_ids = stage_state.accessible_ids;
3469
Chris Forbes47567b72017-06-09 12:09:45 -07003470 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003471 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3472 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003473
Chris Forbes349b3132018-03-07 11:38:08 -08003474 // Validate shader capabilities against enabled device features
sfricke-samsung0065ce02020-12-03 22:46:37 -08003475 skip |= ValidateShaderCapabilitiesAndExtensions(module);
locke-lunarg63e4daf2020-08-17 17:53:25 -06003476 skip |=
3477 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003478 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003479 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05003480 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003481 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003482 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003483 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003484 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003485 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003486 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003487 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003488 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003489 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3490 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3491 }
sfricke-samsung486a51e2021-01-02 00:10:15 -08003492 skip |= ValidatePropertiesAndFeatures(module);
Chris Forbes47567b72017-06-09 12:09:45 -07003493
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003494 std::string vuid_layout_mismatch;
3495 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3496 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3497 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3498 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3499 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3500 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3501 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3502 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3503 }
3504
Chris Forbes47567b72017-06-09 12:09:45 -07003505 // Validate descriptor use
3506 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003507 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003508 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003509 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003510 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3511 std::set<uint32_t> descriptor_types =
3512 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003513
3514 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003515 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003516 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3517 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003518 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003519 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003520 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3521 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003522 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003523 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003524 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3525 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3526 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003527 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003528 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003529 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3530 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003531 }
3532 }
3533
3534 // Validate use of input attachments against subpass structure
3535 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003536 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003537
Petr Krause91f7a12017-12-14 20:57:36 +01003538 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003539 auto subpass = pipeline->graphicsPipelineCI.subpass;
3540
3541 for (auto use : input_attachment_uses) {
3542 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3543 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003544 ? input_attachments[use.first].attachment
3545 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003546
3547 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003548 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3549 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003550 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003551 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003552 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3553 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3554 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003555 }
3556 }
3557 }
Lockeaa8fdc02019-04-02 11:59:20 -06003558 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3559 skip |= ValidateComputeWorkGroupSizes(module);
3560 }
Chris Forbes47567b72017-06-09 12:09:45 -07003561 return skip;
3562}
3563
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003564bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3565 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3566 spirv_inst_iter consumer_entrypoint,
3567 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003568 bool skip = false;
3569
3570 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003571 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3572 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003573
3574 auto a_it = outputs.begin();
3575 auto b_it = inputs.begin();
3576
3577 // Maps sorted by key (location); walk them together to find mismatches
3578 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3579 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3580 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3581 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3582 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3583
3584 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003585 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3586 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3587 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003588 a_it++;
3589 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003590 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3591 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3592 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003593 b_it++;
3594 } else {
3595 // subtleties of arrayed interfaces:
3596 // - if is_patch, then the member is not arrayed, even though the interface may be.
3597 // - if is_block_member, then the extra array level of an arrayed interface is not
3598 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003599 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3600 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3601 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003602 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3603 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3604 DescribeType(producer, a_it->second.type_id).c_str(),
3605 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003606 }
3607 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003608 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3609 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3610 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3611 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003612 }
3613 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003614 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3615 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3616 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003617 }
3618 a_it++;
3619 b_it++;
3620 }
3621 }
3622
Ari Suonpaa696b3432019-03-11 14:02:57 +02003623 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3624 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3625 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3626
3627 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3628 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003629 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3630 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003631 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3632 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003633 } else {
3634 auto it_producer = builtins_producer.begin();
3635 auto it_consumer = builtins_consumer.begin();
3636 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3637 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003638 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3639 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3640 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003641 break;
3642 }
3643 it_producer++;
3644 it_consumer++;
3645 }
3646 }
3647 }
3648 }
3649
Chris Forbes47567b72017-06-09 12:09:45 -07003650 return skip;
3651}
3652
John Zulauf14c355b2019-06-27 16:09:37 -06003653static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003654 uint32_t stage_mask = 0;
3655 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3656 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3657 stage_mask |= pCreateInfo->pStages[i].stage;
3658 }
3659 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003660 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3661 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3662 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003663 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3664 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3665 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3666 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3667 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003668 }
3669 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003670 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003671}
3672
Chris Forbes47567b72017-06-09 12:09:45 -07003673// Validate that the shaders used by the given pipeline and store the active_slots
3674// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003675bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003676 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003677 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3678 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003679
John Zulauf14c355b2019-06-27 16:09:37 -06003680 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003681 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003682 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003683 bool skip = false;
3684
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003685 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003686
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003687 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3688 auto stage = &create_info->pStages[i];
3689 auto stage_id = GetShaderStageId(stage->stage);
3690 shaders[stage_id] = GetShaderModuleState(stage->module);
3691 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3692 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3693 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003694 }
3695
3696 // if the shader stages are no good individually, cross-stage validation is pointless.
3697 if (skip) return true;
3698
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003699 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003700
3701 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003702 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003703 }
3704
3705 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003706 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003707 }
3708
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003709 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3710 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003711
3712 while (!shaders[producer] && producer != fragment_stage) {
3713 producer++;
3714 consumer++;
3715 }
3716
3717 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3718 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003719 if (shaders[consumer]) {
3720 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003721 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3722 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003723 }
Chris Forbes47567b72017-06-09 12:09:45 -07003724
3725 producer = consumer;
3726 }
3727 }
3728
3729 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003730 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003731 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003732 }
3733
3734 return skip;
3735}
3736
Tony-LunarGb2ded512021-02-02 16:03:30 -07003737void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3738 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3739
3740 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3741 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3742 return;
3743 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003744
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003745 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3746 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003747 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003748
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003749 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3750 auto stage = &create_info->pStages[i];
3751 auto stage_id = GetShaderStageId(stage->stage);
3752 shaders[stage_id] = GetShaderModuleState(stage->module);
3753 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003754
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003755 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3756 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003757 spirv_inst_iter insn = entrypoints[stage_id];
3758 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003759
Tony-LunarGb2ded512021-02-02 16:03:30 -07003760 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3761 if (insn.opcode() == spv::OpMemberDecorate) {
3762 if (insn.word(3) == spv::DecorationBuiltIn) {
3763 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3764 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003765 }
3766 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003767 } else if (insn.opcode() == spv::OpDecorate) {
3768 if (insn.word(2) == spv::DecorationBuiltIn) {
3769 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3770 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3771 }
3772 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003773 }
3774
Tony-LunarGb2ded512021-02-02 16:03:30 -07003775 insn++;
3776 }
3777 if (primitiverate_written) {
3778 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3779 }
3780 }
3781 }
3782}
3783
3784bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3785 const char *caller, const DrawDispatchVuid &vuid) const {
3786 auto create_info = pipeline->graphicsPipelineCI.ptr();
3787 bool skip = false;
3788
3789 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3790 auto stage = &create_info->pStages[i];
3791 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3792 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3793 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3794 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3795 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003796 skip |=
3797 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3798 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3799 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3800 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003801 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003802 }
3803 }
3804 }
3805 }
3806
3807 return skip;
3808}
3809
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003810bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003811 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003812
John Zulauf14c355b2019-06-27 16:09:37 -06003813 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3814 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003815
John Zulauf14c355b2019-06-27 16:09:37 -06003816 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003817}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003818
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003819uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3820 uint32_t total = 0;
3821
3822 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3823 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3824 if (stages[stage_index].stage == stageBit) {
3825 total++;
3826 }
3827 }
3828
3829 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3830 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3831 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3832 total += CalcShaderStageCount(library_pipeline, stageBit);
3833 }
3834 }
3835
3836 return total;
3837}
3838
sourav parmarcd5fb182020-07-17 12:58:44 -07003839bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003840 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003841
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003842 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003843 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3844 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3845 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3846 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3847 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3848 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3849 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003850 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003851 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3852 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003853 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003854 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003855 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003856 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3857 skip |= LogError(
3858 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3859 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3860 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003861 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003862 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3863 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003864 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3865 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003866 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003867 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003868 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3869 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3870 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3871 "member must have been created with values of the maxPipelineRayPayloadSize and "
3872 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3873 }
3874 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3877 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3878 "vkCreateRayTracingPipelinesKHR: If flags includes "
3879 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3880 "the pLibraries member of libraries must have been created with the "
3881 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3882 }
sourav parmar83c31b12020-05-06 12:30:54 -07003883 }
3884 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003885 } else {
3886 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003887 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3888 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3889 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003890 pipeline->raytracingPipelineCI.maxRecursionDepth,
3891 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3892 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003893 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003894 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3895 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3896
John Zulaufe4474e72019-07-01 17:28:27 -06003897 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003898 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003899
John Zulaufe4474e72019-07-01 17:28:27 -06003900 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3901 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003902
John Zulaufe4474e72019-07-01 17:28:27 -06003903 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003904 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003905
3906 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3907 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3908 if (raygen_stages_count == 0) {
3909 skip |= LogError(
3910 device,
3911 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3912 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3913 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003914 }
3915
3916 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3917 const auto &group = groups[group_index];
3918
3919 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3920 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3921 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3922 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3923 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003924 skip |= LogError(device,
3925 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3926 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3927 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003928 }
3929 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3930 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003931 skip |= LogError(device,
3932 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3933 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3934 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003935 }
3936 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3937 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3938 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003939 skip |= LogError(device,
3940 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3941 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3942 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003943 }
3944 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3945 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003946 skip |= LogError(device,
3947 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3948 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3949 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003950 }
3951 }
3952
3953 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3954 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3955 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3956 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003957 skip |= LogError(device,
3958 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3959 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3960 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003961 }
3962 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3963 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3964 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003965 skip |= LogError(device,
3966 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3967 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3968 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003969 }
3970 }
John Zulaufe4474e72019-07-01 17:28:27 -06003971 }
3972 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003973}
3974
Dave Houltona9df0ce2018-02-07 10:51:23 -07003975uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003976
Dave Houltona9df0ce2018-02-07 10:51:23 -07003977static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003978 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003979 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003980 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003981 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003982 return nullptr;
3983}
3984
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003985bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003986 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003987 bool skip = false;
3988 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003989
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003990 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003991 return false;
3992 }
3993
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003994 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003995
3996 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003997 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3998 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3999 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004000 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004001 auto cache = GetValidationCacheInfo(pCreateInfo);
4002 uint32_t hash = 0;
4003 if (cache) {
4004 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004005 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004006 }
4007
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004008 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4009 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004010 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004011 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004012 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004013 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004014 spvtools::ValidatorOptions options;
4015 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004016 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004017 if (spv_valid != SPV_SUCCESS) {
4018 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004019 if (spv_valid == SPV_WARNING) {
4020 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4021 diag && diag->error ? diag->error : "(no error text)");
4022 } else {
4023 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4024 diag && diag->error ? diag->error : "(no error text)");
4025 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004026 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004027 } else {
4028 if (cache) {
4029 cache->Insert(hash);
4030 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004031 }
4032
4033 spvDiagnosticDestroy(diag);
4034 spvContextDestroy(ctx);
4035 }
4036
Chris Forbes4ae55b32017-06-09 14:42:56 -07004037 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004038}
4039
John Zulaufac4c6e12019-07-01 16:05:58 -06004040bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004041 bool skip = false;
4042 uint32_t local_size_x = 0;
4043 uint32_t local_size_y = 0;
4044 uint32_t local_size_z = 0;
4045 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
4046 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004047 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4048 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4049 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4050 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004051 }
4052 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004053 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4054 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4055 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4056 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004057 }
4058 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004059 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4060 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4061 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4062 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004063 }
4064
4065 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4066 uint64_t invocations = local_size_x * local_size_y;
4067 // Prevent overflow.
4068 bool fail = false;
4069 if (invocations > UINT32_MAX || invocations > limit) {
4070 fail = true;
4071 }
4072 if (!fail) {
4073 invocations *= local_size_z;
4074 if (invocations > UINT32_MAX || invocations > limit) {
4075 fail = true;
4076 }
4077 }
4078 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004079 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4080 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4081 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4082 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4083 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004084 }
4085 }
4086 return skip;
4087}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004088
4089spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4090 if (api_version >= VK_API_VERSION_1_2) {
4091 return SPV_ENV_VULKAN_1_2;
4092 } else if (api_version >= VK_API_VERSION_1_1) {
4093 if (spirv_1_4) {
4094 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4095 } else {
4096 return SPV_ENV_VULKAN_1_1;
4097 }
4098 }
4099 return SPV_ENV_VULKAN_1_0;
4100}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004101
4102void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4103 spvtools::ValidatorOptions &options) {
4104 if (device_extensions.vk_khr_relaxed_block_layout) {
4105 options.SetRelaxBlockLayout(true);
4106 }
4107 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4108 options.SetUniformBufferStandardLayout(true);
4109 }
4110 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4111 options.SetScalarBlockLayout(true);
4112 }
4113}