blob: 5ae9f04d63bde6314a7eb4112adc7ece0f646088 [file] [log] [blame]
Tony-LunarG73719992020-01-15 10:20:28 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
4 * Copyright (C) 2015-2020 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
989 std::vector<std::pair<unsigned, unsigned>> sampledImage_members;
990 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
locke-lunarg25b6c352020-08-06 17:44:18 -06001088// Check writable, image atomic operation
1089static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001090 bool is_check_writable, interface_var &out_interface_var,
1091 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001092 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001093 unsigned int id = id_it.word(2);
1094
Chris Forbes8af24522018-03-07 11:37:45 -08001095 auto type = module->get_def(type_id);
1096
1097 // 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 -06001098 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1099 type.opcode() == spv::OpTypeSampledImage) {
1100 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1101 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001102 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001103 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001104 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001105 }
1106 }
Chris Forbes8af24522018-03-07 11:37:45 -08001107 switch (type.opcode()) {
1108 case spv::OpTypeImage: {
1109 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001110 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001111 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001112
locke-lunargd3da0422020-09-23 01:02:11 -06001113 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1114 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001115 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001116 }
1117 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1118 used_operators.accesschain_members)) {
1119 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001120 }
locke-lunargd3da0422020-09-23 01:02:11 -06001121 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1122 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001123 out_interface_var.is_sampler_bias_offset = true;
1124 }
locke-lunargd3da0422020-09-23 01:02:11 -06001125 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1126 used_operators.accesschain_members) ||
1127 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1128 used_operators.accesschain_members)) {
1129 out_interface_var.is_atomic_operation = true;
1130 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001131
locke-lunargd3da0422020-09-23 01:02:11 -06001132 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001133 // Find if image id match.
1134 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001135 auto load_it = used_operators.load_members.find(itp_id.first);
1136 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001137 continue;
1138 } else {
1139 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001140 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1141 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001142 continue;
1143 } else {
1144 if (accesschain_it->second.first != id) {
1145 continue;
1146 }
locke-lunarg025daa72020-10-13 11:07:51 -06001147 if (used_operators.load_members.end() !=
1148 used_operators.load_members.find(accesschain_it->second.second)) {
1149 // image_index isn't a constant, skip.
1150 break;
1151 }
locke-lunarg36045992020-08-20 16:54:37 -06001152 image_index = GetConstantValue(module, accesschain_it->second.second);
1153 }
1154 }
1155 }
1156 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001157 load_it = used_operators.load_members.find(itp_id.second);
1158 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001159 continue;
1160 } else {
1161 uint32_t sampler_id = load_it->second;
1162 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001163 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1164 if (accesschain_it != used_operators.accesschain_members.end()) {
locke-lunarg025daa72020-10-13 11:07:51 -06001165 if (used_operators.load_members.end() !=
1166 used_operators.load_members.find(accesschain_it->second.second)) {
1167 // sampler_index isn't a constant, skip.
1168 break;
1169 }
locke-lunarg36045992020-08-20 16:54:37 -06001170 sampler_id = accesschain_it->second.first;
1171 sampler_index = GetConstantValue(module, accesschain_it->second.second);
1172 }
1173 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001174 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1175 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1176 }
1177 out_interface_var.samplers_used_by_image[image_index].emplace(
1178 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001179 }
1180 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001181 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001182 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001183 }
1184
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001185 case spv::OpTypeStruct: {
1186 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001187 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -08001188 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001189 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
1190 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001191 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001192 }
1193 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001194
1195 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1196 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001197 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001198 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001199
locke-lunargd3da0422020-09-23 01:02:11 -06001200 for (auto oid : used_operators.store_members) {
1201 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001202 out_interface_var.is_writable = true;
1203 return;
1204 }
locke-lunargd3da0422020-09-23 01:02:11 -06001205 auto accesschain_it = used_operators.accesschain_members.find(oid);
1206 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001207 continue;
1208 }
locke-lunargd3da0422020-09-23 01:02:11 -06001209 if (accesschain_it->second.first == id) {
1210 out_interface_var.is_writable = true;
1211 return;
1212 }
1213 }
1214 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1215 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001216 out_interface_var.is_writable = true;
1217 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001218 }
1219 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001220 }
Chris Forbes8af24522018-03-07 11:37:45 -08001221 }
Chris Forbes8af24522018-03-07 11:37:45 -08001222}
1223
locke-lunargd9a069d2019-09-17 01:50:19 -06001224std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001225 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1226 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001227 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001228 shader_module_used_operators operators;
1229
Chris Forbes47567b72017-06-09 12:09:45 -07001230 for (auto id : accessible_ids) {
1231 auto insn = src->get_def(id);
1232 assert(insn != src->end());
1233
1234 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001235 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1236 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001237 auto d = src->get_decorations(insn.word(2));
1238 unsigned set = d.descriptor_set;
1239 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001240
1241 interface_var v = {};
1242 v.id = insn.word(2);
1243 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001244
locke-lunarg25b6c352020-08-06 17:44:18 -06001245 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001246 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001247 if (v.is_writable) *has_writable_descriptor = true;
1248 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001249 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001250 }
1251 }
1252
1253 return out;
1254}
1255
locke-lunargde3f0fa2020-09-10 11:55:31 -06001256void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1257 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1258 const auto struct_it = GetStructType(&src, it, false);
1259 assert(struct_it != src.end());
1260 data.size = 0;
1261
1262 shader_struct_member data1;
1263 uint32_t i = 2;
1264 uint32_t local_offset = 0;
1265 std::vector<uint32_t> offsets;
1266 offsets.resize(struct_it.len() - i);
1267
1268 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1269 for (const auto offset : memberDecorate_offsets) {
1270 const auto member_decorate = src.at(offset);
1271 if (member_decorate.word(1) != struct_it.word(1)) {
1272 continue;
1273 }
1274
1275 offsets[member_decorate.word(2)] = member_decorate.word(4);
1276 }
1277
1278 for (const auto offset : offsets) {
1279 local_offset = offset;
1280 data1 = {};
1281 data1.root = data.root;
1282 data1.offset = local_offset;
1283 auto def_member = src.get_def(struct_it.word(i));
1284
1285 // Array could be multi-dimensional
1286 while (def_member.opcode() == spv::OpTypeArray) {
1287 const auto len_id = def_member.word(3);
1288 const auto def_len = src.get_def(len_id);
1289 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1290 def_member = src.get_def(def_member.word(2));
1291 }
1292
1293 if (def_member.opcode() == spv::OpTypeStruct || def_member.opcode() == spv::OpTypePointer) {
1294 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1295 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1296 } else {
1297 if (def_member.opcode() == spv::OpTypeMatrix) {
1298 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1299 def_member = src.get_def(def_member.word(2));
1300 }
1301
1302 if (def_member.opcode() == spv::OpTypeVector) {
1303 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1304 def_member = src.get_def(def_member.word(2));
1305 }
1306
1307 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1308 data1.size = (def_member.word(2) / 8);
1309 }
1310 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1311 if (array_length_hierarchy_szie > 0) {
1312 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1313
1314 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1315 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1316 }
1317 }
1318 data.struct_members.emplace_back(data1);
1319 ++i;
1320 }
1321 uint32_t total_array_length = 1;
1322 for (const auto length : data1.array_length_hierarchy) {
1323 total_array_length *= length;
1324 }
1325 data.size = local_offset + data1.size * total_array_length;
1326}
1327
1328uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1329 int array_indices_size = static_cast<int>(array_indices.size());
1330 if (array_indices_size) {
1331 uint32_t array_index = 0;
1332 uint32_t i = 0;
1333 for (const auto index : array_indices) {
1334 array_index += (data.array_block_size[i] * index);
1335 ++i;
1336 }
1337 offset += (array_index * data.size);
1338 }
1339 return offset;
1340}
1341
1342void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1343 int array_indices_size = static_cast<int>(array_indices.size());
1344 uint32_t block_memory_size = data.size;
1345 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1346 block_memory_size *= data.array_length_hierarchy[i];
1347 }
1348
1349 offset = UpdateOffset(offset, array_indices, data);
1350
1351 uint32_t end = offset + block_memory_size;
1352 auto used_bytes = data.GetUsedbytes();
1353 if (used_bytes->size() < end) {
1354 used_bytes->resize(end, 0);
1355 }
1356 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1357}
1358
1359void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1360 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1361 if (access_chain_word_index < access_chain_it.len()) {
1362 if (data.array_length_hierarchy.size() > array_indices.size()) {
1363 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1364 ++access_chain_word_index;
1365
1366 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1367 array_indices.emplace_back(def_it.word(3));
1368 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1369 } else {
1370 // If it is a variable, set the all array is used.
1371 if (access_chain_word_index < access_chain_it.len()) {
1372 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1373 for (uint32_t i = 0; i < array_length; ++i) {
1374 auto array_indices2 = array_indices;
1375 array_indices2.emplace_back(i);
1376 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1377 }
1378 } else {
1379 SetUsedBytes(offset, array_indices, data);
1380 }
1381 }
1382 } else {
1383 offset = UpdateOffset(offset, array_indices, data);
1384 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1385 }
1386 } else {
1387 SetUsedBytes(offset, array_indices, data);
1388 }
1389}
1390
1391void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1392 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1393 std::vector<uint32_t> array_indices_emptry;
1394
1395 if (access_chain_word_index < access_chain_it.len()) {
1396 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1397 ++access_chain_word_index;
1398
1399 auto data1 = data.struct_members[strcut_member_index];
1400 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1401 }
1402}
1403
1404void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1405 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1406 for (const auto &func_set : function_set_list) {
1407 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1408 for (auto it = range.first; it != range.second; ++it) {
1409 auto access_chain = src.at(it->second);
1410 if (access_chain.word(3) == variable_id) {
1411 RunUsedStruct(src, 0, 4, access_chain, data);
1412 }
1413 }
1414 }
1415}
1416
1417void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1418 for (auto &entrypoint : src.entry_points) {
1419 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1420 for (auto it = range.first; it != range.second; ++it) {
1421 const auto def_insn = src.at(it->second);
1422
1423 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1424 spirv_inst_iter type = src.get_def(def_insn.word(1));
1425 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1426 std::vector<uint32_t> offsets;
1427
1428 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1429 auto member_decorate = src.at(it2->second);
1430 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1431 offsets.emplace_back(member_decorate.offset());
1432 }
1433 }
1434 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1435 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1436 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1437 entrypoint.second.push_constant_used_in_shader);
1438 }
1439 }
1440 }
1441}
1442
locke-lunarg96dc9632020-06-10 17:22:18 -06001443std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1444 const VkPipelineShaderStageCreateInfo &stage_info) {
1445 std::unordered_set<uint32_t> location_list;
1446 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1447 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1448 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1449 std::unordered_set<unsigned> store_members;
1450 std::unordered_map<unsigned, unsigned> accesschain_members;
1451
1452 for (auto insn : module) {
1453 switch (insn.opcode()) {
1454 case spv::OpStore:
1455 case spv::OpAtomicStore: {
1456 store_members.insert(insn.word(1)); // object id or AccessChain id
1457 break;
1458 }
1459 case spv::OpAccessChain: {
1460 // 2: AccessChain id, 3: object id
1461 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1462 break;
1463 }
1464 default:
1465 break;
1466 }
1467 }
1468 if (store_members.empty()) {
1469 return location_list;
1470 }
1471 for (auto output : outputs) {
1472 auto store_it = store_members.find(output.second.id);
1473 if (store_it != store_members.end()) {
1474 location_list.insert(output.first.first);
1475 store_members.erase(store_it);
1476 continue;
1477 }
1478 store_it = store_members.begin();
1479 while (store_it != store_members.end()) {
1480 auto accesschain_it = accesschain_members.find(*store_it);
1481 if (accesschain_it == accesschain_members.end()) {
1482 ++store_it;
1483 continue;
1484 }
1485 if (accesschain_it->second == output.second.id) {
1486 location_list.insert(output.first.first);
1487 store_members.erase(store_it);
1488 accesschain_members.erase(accesschain_it);
1489 break;
1490 }
1491 ++store_it;
1492 }
1493 }
1494 return location_list;
1495}
1496
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001497bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001498 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1499 // be specified only once.
1500 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1501 bool skip = false;
1502
1503 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1504 auto desc = &vi->pVertexBindingDescriptions[i];
1505 auto &binding = bindings[desc->binding];
1506 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001507 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001508 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1509 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001510 } else {
1511 binding = desc;
1512 }
1513 }
1514
1515 return skip;
1516}
1517
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001518bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1519 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001520 bool skip = false;
1521
Petr Kraus25810d02019-08-27 17:41:15 +02001522 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001523
1524 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001525 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001526 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001527 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1528 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1529 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001530 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1531 }
1532 }
1533 }
1534
Petr Kraus25810d02019-08-27 17:41:15 +02001535 struct AttribInputPair {
1536 const VkVertexInputAttributeDescription *attrib = nullptr;
1537 const interface_var *input = nullptr;
1538 };
1539 std::map<uint32_t, AttribInputPair> location_map;
1540 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1541 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001542
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001543 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001544 const auto location = location_it.first;
1545 const auto attrib = location_it.second.attrib;
1546 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001547
Petr Kraus25810d02019-08-27 17:41:15 +02001548 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001549 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1550 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001551 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001552 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1553 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001554 } else if (attrib && input) {
1555 const auto attrib_type = GetFormatType(attrib->format);
1556 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001557
1558 // Type checking
1559 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001560 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1561 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1562 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001563 }
Petr Kraus25810d02019-08-27 17:41:15 +02001564 } else { // !attrib && !input
1565 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001566 }
1567 }
1568
1569 return skip;
1570}
1571
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001572bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1573 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001574 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001575
Petr Kraus25810d02019-08-27 17:41:15 +02001576 const auto rpci = pipeline->rp_state->createInfo.ptr();
1577
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001578 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001579 const VkAttachmentReference2 *reference = nullptr;
1580 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001581 const interface_var *output = nullptr;
1582 };
1583 std::map<uint32_t, Attachment> location_map;
1584
Petr Kraus25810d02019-08-27 17:41:15 +02001585 const auto subpass = rpci->pSubpasses[subpass_index];
1586 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001587 auto const &reference = subpass.pColorAttachments[i];
1588 location_map[i].reference = &reference;
1589 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1590 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1591 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001592 }
1593 }
1594
Chris Forbes47567b72017-06-09 12:09:45 -07001595 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1596
Petr Kraus25810d02019-08-27 17:41:15 +02001597 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001598 for (const auto &output_it : outputs) {
1599 auto const location = output_it.first.first;
1600 location_map[location].output = &output_it.second;
1601 }
Chris Forbes47567b72017-06-09 12:09:45 -07001602
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001603 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1604 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001605
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001606 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001607 const auto reference = location_it.second.reference;
1608 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1609 continue;
1610 }
1611
Petr Kraus25810d02019-08-27 17:41:15 +02001612 const auto location = location_it.first;
1613 const auto attachment = location_it.second.attachment;
1614 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001615 if (attachment && !output) {
1616 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001617 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1618 "Attachment %" PRIu32
1619 " not written by fragment shader; undefined values will be written to attachment",
1620 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001621 }
1622 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001623 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001624 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1625 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001626 }
Petr Kraus25810d02019-08-27 17:41:15 +02001627 } else if (attachment && output) {
1628 const auto attachment_type = GetFormatType(attachment->format);
1629 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001630
1631 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001632 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001633 skip |=
1634 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1635 "Attachment %" PRIu32
1636 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1637 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001638 }
Petr Kraus25810d02019-08-27 17:41:15 +02001639 } else { // !attachment && !output
1640 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001641 }
1642 }
1643
Petr Kraus25810d02019-08-27 17:41:15 +02001644 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001645 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1646 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1647 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001648 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1649 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001650 }
1651
Chris Forbes47567b72017-06-09 12:09:45 -07001652 return skip;
1653}
1654
Tobias Hector6663c9b2020-11-05 10:18:02 +00001655// 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 -06001656// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001657static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001658 auto type = builtin_instr.opcode();
1659 uint32_t target_id = builtin_instr.word(1);
1660 bool init_complete = false;
1661
1662 if (type == spv::OpMemberDecorate) {
1663 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1664 auto insn = entrypoint;
1665 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1666 switch (insn.opcode()) {
1667 case spv::OpTypePointer:
1668 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1669 target_id = insn.word(1);
1670 }
1671 break;
1672 case spv::OpVariable:
1673 if (insn.word(1) == target_id) {
1674 target_id = insn.word(2);
1675 init_complete = true;
1676 }
1677 break;
1678 }
1679 insn++;
1680 }
1681 }
1682
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001683 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1684
1685 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001686 std::unordered_set<uint32_t> worklist;
1687 worklist.insert(entrypoint.word(2));
1688
1689 // Follow instructions in call graph looking for writes to target
1690 while (!worklist.empty() && !found_write) {
1691 auto id_iter = worklist.begin();
1692 auto id = *id_iter;
1693 worklist.erase(id_iter);
1694
1695 auto insn = src->get_def(id);
1696 if (insn == src->end()) {
1697 continue;
1698 }
1699
1700 if (insn.opcode() == spv::OpFunction) {
1701 // Scan body of function looking for other function calls or items in our ID chain
1702 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1703 switch (insn.opcode()) {
1704 case spv::OpAccessChain:
1705 if (insn.word(3) == target_id) {
1706 if (type == spv::OpMemberDecorate) {
1707 auto value = GetConstantValue(src, insn.word(4));
1708 if (value == builtin_instr.word(2)) {
1709 target_id = insn.word(2);
1710 }
1711 } else {
1712 target_id = insn.word(2);
1713 }
1714 }
1715 break;
1716 case spv::OpStore:
1717 if (insn.word(1) == target_id) {
1718 found_write = true;
1719 }
1720 break;
1721 case spv::OpFunctionCall:
1722 worklist.insert(insn.word(3));
1723 break;
1724 }
1725 }
1726 }
1727 }
1728 return found_write;
1729}
1730
Chris Forbes47567b72017-06-09 12:09:45 -07001731// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1732// important for identifying the set of shader resources actually used by an entrypoint, for example.
1733// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1734// - NOT the shader input/output interfaces.
1735//
1736// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1737// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001738std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001739 std::unordered_set<uint32_t> ids;
1740 std::unordered_set<uint32_t> worklist;
1741 worklist.insert(entrypoint.word(2));
1742
1743 while (!worklist.empty()) {
1744 auto id_iter = worklist.begin();
1745 auto id = *id_iter;
1746 worklist.erase(id_iter);
1747
1748 auto insn = src->get_def(id);
1749 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001750 // 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 -07001751 // that we may not care about.
1752 continue;
1753 }
1754
1755 // Try to add to the output set
1756 if (!ids.insert(id).second) {
1757 continue; // If we already saw this id, we don't want to walk it again.
1758 }
1759
1760 switch (insn.opcode()) {
1761 case spv::OpFunction:
1762 // Scan whole body of the function, enlisting anything interesting
1763 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1764 switch (insn.opcode()) {
1765 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001766 worklist.insert(insn.word(3)); // ptr
1767 break;
1768 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001769 worklist.insert(insn.word(1)); // ptr
1770 break;
1771 case spv::OpAccessChain:
1772 case spv::OpInBoundsAccessChain:
1773 worklist.insert(insn.word(3)); // base ptr
1774 break;
1775 case spv::OpSampledImage:
1776 case spv::OpImageSampleImplicitLod:
1777 case spv::OpImageSampleExplicitLod:
1778 case spv::OpImageSampleDrefImplicitLod:
1779 case spv::OpImageSampleDrefExplicitLod:
1780 case spv::OpImageSampleProjImplicitLod:
1781 case spv::OpImageSampleProjExplicitLod:
1782 case spv::OpImageSampleProjDrefImplicitLod:
1783 case spv::OpImageSampleProjDrefExplicitLod:
1784 case spv::OpImageFetch:
1785 case spv::OpImageGather:
1786 case spv::OpImageDrefGather:
1787 case spv::OpImageRead:
1788 case spv::OpImage:
1789 case spv::OpImageQueryFormat:
1790 case spv::OpImageQueryOrder:
1791 case spv::OpImageQuerySizeLod:
1792 case spv::OpImageQuerySize:
1793 case spv::OpImageQueryLod:
1794 case spv::OpImageQueryLevels:
1795 case spv::OpImageQuerySamples:
1796 case spv::OpImageSparseSampleImplicitLod:
1797 case spv::OpImageSparseSampleExplicitLod:
1798 case spv::OpImageSparseSampleDrefImplicitLod:
1799 case spv::OpImageSparseSampleDrefExplicitLod:
1800 case spv::OpImageSparseSampleProjImplicitLod:
1801 case spv::OpImageSparseSampleProjExplicitLod:
1802 case spv::OpImageSparseSampleProjDrefImplicitLod:
1803 case spv::OpImageSparseSampleProjDrefExplicitLod:
1804 case spv::OpImageSparseFetch:
1805 case spv::OpImageSparseGather:
1806 case spv::OpImageSparseDrefGather:
1807 case spv::OpImageTexelPointer:
1808 worklist.insert(insn.word(3)); // Image or sampled image
1809 break;
1810 case spv::OpImageWrite:
1811 worklist.insert(insn.word(1)); // Image -- different operand order to above
1812 break;
1813 case spv::OpFunctionCall:
1814 for (uint32_t i = 3; i < insn.len(); i++) {
1815 worklist.insert(insn.word(i)); // fn itself, and all args
1816 }
1817 break;
1818
1819 case spv::OpExtInst:
1820 for (uint32_t i = 5; i < insn.len(); i++) {
1821 worklist.insert(insn.word(i)); // Operands to ext inst
1822 }
1823 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001824
1825 default: {
1826 if (AtomicOperation(insn.opcode())) {
1827 if (insn.opcode() == spv::OpAtomicStore) {
1828 worklist.insert(insn.word(1)); // ptr
1829 } else {
1830 worklist.insert(insn.word(3)); // ptr
1831 }
1832 }
1833 break;
1834 }
Chris Forbes47567b72017-06-09 12:09:45 -07001835 }
1836 }
1837 break;
1838 }
1839 }
1840
1841 return ids;
1842}
1843
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001844PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1845 const shader_struct_member &push_constant_used_in_shader,
1846 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001847 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001848 const auto used_bytes_size = used_bytes->size();
1849 if (used_bytes_size == 0) return PC_Byte_Updated;
1850
1851 const auto push_constant_data_update_size = push_constant_data_update.size();
1852 const auto *data = push_constant_data_update.data();
1853 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1854 if (used_bytes_size <= push_constant_data_update_size) {
1855 return PC_Byte_Updated;
1856 }
1857 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1858
1859 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1860 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1861 return PC_Byte_Updated;
1862 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001863 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001864
locke-lunargde3f0fa2020-09-10 11:55:31 -06001865 uint32_t i = 0;
1866 for (const auto used : *used_bytes) {
1867 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001868 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001869 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001870 return PC_Byte_Not_Set;
1871 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001872 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001873 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001874 }
1875 }
1876 ++i;
1877 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001878 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001879}
1880
1881bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1882 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001883 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001884 // 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 -06001885 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1886 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1887 return skip;
1888 }
1889 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001890
locke-lunargde3f0fa2020-09-10 11:55:31 -06001891 bool found_stage = false;
1892 for (auto const &range : *push_constant_ranges) {
1893 if (range.stageFlags & pStage->stage) {
1894 found_stage = true;
1895 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001896 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001897 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001898 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001899 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001900 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001901 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001902 const auto ret =
1903 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001904
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001905 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001906 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1907 LogObjectList objlist(src->vk_shader_module);
1908 objlist.add(pipeline.pipeline_layout->layout);
1909 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1910 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1911 string_VkShaderStageFlags(pStage->stage).c_str(),
1912 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1913 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001914 }
1915 }
1916 }
1917
locke-lunargde3f0fa2020-09-10 11:55:31 -06001918 if (!found_stage) {
1919 LogObjectList objlist(src->vk_shader_module);
1920 objlist.add(pipeline.pipeline_layout->layout);
1921 skip |= LogError(
1922 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1923 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1924 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001925 }
Chris Forbes47567b72017-06-09 12:09:45 -07001926 return skip;
1927}
1928
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001929bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1930 VkShaderStageFlagBits stage) const {
1931 bool skip = false;
1932
1933 // Currently all builtin tested are only found in fragment shaders
1934 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1935 return skip;
1936 }
1937
1938 for (const auto id : accessible_ids) {
1939 auto insn = src->get_def(id);
1940 const decoration_set decorations = src->get_decorations(insn.word(2));
1941
1942 // Built-ins are obtained from OpVariable
1943 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1944 auto type_pointer = src->get_def(insn.word(1));
1945 assert(type_pointer.opcode() == spv::OpTypePointer);
1946
1947 auto type = src->get_def(type_pointer.word(3));
1948 if (type.opcode() == spv::OpTypeArray) {
1949 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1950
1951 switch (decorations.builtin) {
1952 case spv::BuiltInSampleMask:
1953 // Handles both the input and output sampleMask
1954 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1955 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1956 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1957 "maxSampleMaskWords of %u in %s.",
1958 length, phys_dev_props.limits.maxSampleMaskWords,
1959 report_data->FormatHandle(src->vk_shader_module).c_str());
1960 }
1961 break;
1962 }
1963 }
1964 }
1965 }
1966
1967 return skip;
1968}
1969
Chris Forbes47567b72017-06-09 12:09:45 -07001970// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001971bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001972 bool skip = false;
1973
1974 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1975
1976 if (spec) {
1977 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001978 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001979 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1980 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1981 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1982 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1983 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001984
1985 continue;
1986 }
Chris Forbes47567b72017-06-09 12:09:45 -07001987 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001988 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
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->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001993 }
1994 }
1995 }
1996
1997 return skip;
1998}
1999
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002000// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002001static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2002 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002003 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002004 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002005 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002006 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002007
2008 // 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 -05002009 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2010 if (type.opcode() == spv::OpTypeRuntimeArray) {
2011 descriptor_count = 0;
2012 type = module->get_def(type.word(2));
2013 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002014 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002015 type = module->get_def(type.word(2));
2016 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002017 if (type.word(2) == spv::StorageClassStorageBuffer) {
2018 is_storage_buffer = true;
2019 }
Chris Forbes47567b72017-06-09 12:09:45 -07002020 type = module->get_def(type.word(3));
2021 }
2022 }
2023
2024 switch (type.opcode()) {
2025 case spv::OpTypeStruct: {
2026 for (auto insn : *module) {
2027 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
2028 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002029 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002030 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2031 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2032 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002033 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002034 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2035 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2036 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2037 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002038 }
Chris Forbes47567b72017-06-09 12:09:45 -07002039 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002040 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2041 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2042 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002043 }
2044 }
2045 }
2046
2047 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002048 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002049 }
2050
2051 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002052 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2053 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2054 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002055
Chris Forbes73c00bf2018-06-22 16:28:06 -07002056 case spv::OpTypeSampledImage: {
2057 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2058 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2059 auto image_type = module->get_def(type.word(2));
2060 auto dim = image_type.word(3);
2061 auto sampled = image_type.word(7);
2062 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002063 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2064 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002065 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002066 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002067 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2068 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002069
2070 case spv::OpTypeImage: {
2071 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2072 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2073 auto dim = type.word(3);
2074 auto sampled = type.word(7);
2075
2076 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002077 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2078 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002079 } else if (dim == spv::DimBuffer) {
2080 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002081 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2082 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002083 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002084 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2085 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002086 }
2087 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002088 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2089 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2090 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002091 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002092 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2093 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002094 }
2095 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002096 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002097 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2098 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002099 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002100
2101 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2102 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002103 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002104 }
2105}
2106
Jeff Bolze54ae892018-09-08 12:16:29 -05002107static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002108 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002109 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2110 if (ss.tellp()) ss << ", ";
2111 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002112 }
2113 return ss.str();
2114}
2115
sfricke-samsung0065ce02020-12-03 22:46:37 -08002116bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002117 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002118 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 -05002119 return true;
2120 }
2121 }
2122
2123 return false;
2124}
2125
sfricke-samsung0065ce02020-12-03 22:46:37 -08002126bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002127 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002128 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002129 return true;
2130 }
2131 }
2132
2133 return false;
2134}
2135
locke-lunarg63e4daf2020-08-17 17:53:25 -06002136bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2137 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002138 bool skip = false;
2139
locke-lunarg63e4daf2020-08-17 17:53:25 -06002140 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002141 switch (stage) {
2142 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002143 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2144 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2145 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2146 case VK_SHADER_STAGE_MISS_BIT_NV:
2147 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2148 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2149 case VK_SHADER_STAGE_TASK_BIT_NV:
2150 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002151 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002152 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002153 break;
2154 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002155 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2156 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002157 break;
2158 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002159 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2160 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002161 break;
2162 }
2163 }
2164
Chris Forbes47567b72017-06-09 12:09:45 -07002165 return skip;
2166}
2167
Jeff Bolz526f2d52019-09-18 13:18:08 -05002168bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002169 bool skip = false;
2170
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002171 auto const subgroup_props = phys_dev_props_core11;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002172 const VkSubgroupFeatureFlags supported_stages = subgroup_props.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05002173
Jeff Bolz526f2d52019-09-18 13:18:08 -05002174 for (auto inst : *module) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002175 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2176 if (GroupOperation(inst.opcode()) == true) {
2177 // Check the quad operations.
2178 if ((inst.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (inst.opcode() == spv::OpGroupNonUniformQuadSwap)) {
Jeff Bolzee743412019-06-20 22:24:32 -05002179 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002180 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
sfricke-samsung0065ce02020-12-03 22:46:37 -08002181 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2182 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolzee743412019-06-20 22:24:32 -05002183 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002184 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002185
sfricke-samsung0065ce02020-12-03 22:46:37 -08002186 uint32_t scope_type = spv::ScopeMax;
sfricke-samsung95180142020-12-10 20:58:20 -08002187 if (inst.opcode() == spv::OpGroupNonUniformPartitionNV) {
2188 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2189 scope_type = spv::ScopeSubgroup;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002190 } else {
sfricke-samsung95180142020-12-10 20:58:20 -08002191 auto scope_id = module->get_def(inst.word(3));
2192 if ((scope_id.opcode() == spv::OpSpecConstant) || (scope_id.opcode() == spv::OpConstant)) {
2193 scope_type = scope_id.word(3);
2194 } else {
2195 // TODO - Look if this is check by spirv-val
2196 skip |= LogWarning(device, "UNASSIGNED-spirv-group-scopeId",
2197 "Expecting group operation (%u) scope id operand to point to a OpConstant or OpSpecConstant "
2198 "opcode but instead it is pointing to opcode (%u)",
2199 inst.opcode(), scope_id.opcode());
2200 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002201 }
2202
2203 if (scope_type == spv::ScopeSubgroup) {
2204 // "Group operations with subgroup scope" must have stage support
2205 skip |=
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002206 RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002207 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
2208 }
2209
2210 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2211 auto type = module->get_def(inst.word(1));
2212
2213 if (type.opcode() == spv::OpTypeVector) {
2214 // Get the element type
2215 type = module->get_def(type.word(2));
2216 }
2217
2218 if (type.opcode() == spv::OpTypeBool) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05002219 break;
sfricke-samsung0065ce02020-12-03 22:46:37 -08002220 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002221
sfricke-samsung0065ce02020-12-03 22:46:37 -08002222 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2223 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002224
sfricke-samsung0065ce02020-12-03 22:46:37 -08002225 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2226 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2227 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2228 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2229 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002230 }
2231 }
2232 }
Jeff Bolzee743412019-06-20 22:24:32 -05002233 }
2234
2235 return skip;
2236}
2237
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002238bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002239 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002240 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2241 pStage->stage == VK_SHADER_STAGE_ALL) {
2242 return false;
2243 }
2244
2245 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002246 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002247
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002248 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002249 struct Variable {
2250 uint32_t baseTypePtrID;
2251 uint32_t ID;
2252 uint32_t storageClass;
2253 };
2254 std::vector<Variable> variables;
2255
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002256 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002257 bool is_iso_lines = false;
2258 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002259
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002260 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002261
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002262 for (auto insn : *src) {
2263 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002264 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002265 case spv::OpDecorate:
2266 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002267 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002268 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002269 break;
2270 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002271 default:
2272 break;
2273 }
2274 break;
2275 // Find all input and output variables
2276 case spv::OpVariable: {
2277 Variable var = {};
2278 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002279 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2280 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002281 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002282 var.baseTypePtrID = insn.word(1);
2283 var.ID = insn.word(2);
2284 variables.push_back(var);
2285 }
2286 break;
2287 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002288 case spv::OpExecutionMode:
2289 if (insn.word(1) == entrypoint.word(2)) {
2290 switch (insn.word(2)) {
2291 default:
2292 break;
2293 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002294 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002295 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002296 case spv::ExecutionModeIsolines:
2297 is_iso_lines = true;
2298 break;
2299 case spv::ExecutionModePointMode:
2300 is_point_mode = true;
2301 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002302 }
2303 }
2304 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002305 default:
2306 break;
2307 }
2308 }
2309
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002310 bool strip_output_array_level =
2311 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2312 bool strip_input_array_level =
2313 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2314 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2315
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002316 uint32_t num_comp_in = 0, num_comp_out = 0;
2317 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002318
2319 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2320 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2321
2322 // Find max component location used for input variables.
2323 for (auto &var : inputs) {
2324 int location = var.first.first;
2325 int component = var.first.second;
2326 interface_var &iv = var.second;
2327
2328 // Only need to look at the first location, since we use the type's whole size
2329 if (iv.offset != 0) {
2330 continue;
2331 }
2332
2333 if (iv.is_patch) {
2334 continue;
2335 }
2336
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002337 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2338 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002339 }
2340
2341 // Find max component location used for output variables.
2342 for (auto &var : outputs) {
2343 int location = var.first.first;
2344 int component = var.first.second;
2345 interface_var &iv = var.second;
2346
2347 // Only need to look at the first location, since we use the type's whole size
2348 if (iv.offset != 0) {
2349 continue;
2350 }
2351
2352 if (iv.is_patch) {
2353 continue;
2354 }
2355
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002356 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2357 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002358 }
2359
2360 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2361 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002362 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002363 // Check if the variable is a patch. Patches can also be members of blocks,
2364 // but if they are then the top-level arrayness has already been stripped
2365 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002366 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002367
2368 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002369 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002370 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002371 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002372 }
2373 }
2374
2375 switch (pStage->stage) {
2376 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002377 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002378 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2379 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2380 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2381 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002382 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002383 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002384 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002385 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2386 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2387 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2388 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002389 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002390 break;
2391
2392 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002393 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002394 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2395 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2396 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2397 "components by %u components",
2398 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002399 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002400 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002401 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002402 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002403 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2404 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2405 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2406 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002407 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002408 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002409 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2410 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2411 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2412 "components by %u components",
2413 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002414 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002415 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002416 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002417 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002418 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2419 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2420 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2421 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002422 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002423 break;
2424
2425 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002426 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002427 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2428 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2429 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2430 "components by %u components",
2431 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002432 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002433 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002435 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002436 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2437 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2438 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2439 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002440 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002441 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002442 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2443 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2444 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2445 "components by %u components",
2446 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002447 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002448 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002449 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002450 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002451 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2452 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2453 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2454 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002455 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002456 // Portability validation
2457 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2458 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2459 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2460 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2461 " is using abstract patch type IsoLines, but this is not supported on this platform");
2462 }
2463 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2464 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2465 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2466 " is using abstract patch type PointMode, but this is not supported on this platform");
2467 }
2468 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002469 break;
2470
2471 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002472 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002473 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2474 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2475 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2476 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002477 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002478 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002479 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002480 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2481 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2482 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2483 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002484 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002485 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002486 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2487 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2488 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2489 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002490 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002491 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002493 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2494 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2495 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2496 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002497 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002498 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002499 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2500 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2501 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2502 "components by %u components",
2503 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002504 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002505 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002506 break;
2507
2508 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002509 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002510 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2511 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2512 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2513 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002514 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002515 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002516 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002517 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2518 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2519 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2520 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002521 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002522 break;
2523
Jeff Bolz148d94e2018-12-13 21:25:56 -06002524 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2525 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2526 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2527 case VK_SHADER_STAGE_MISS_BIT_NV:
2528 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2529 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2530 case VK_SHADER_STAGE_TASK_BIT_NV:
2531 case VK_SHADER_STAGE_MESH_BIT_NV:
2532 break;
2533
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002534 default:
2535 assert(false); // This should never happen
2536 }
2537 return skip;
2538}
2539
sfricke-samsungdc96f302020-03-18 20:42:10 -07002540bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2541 bool skip = false;
2542 uint32_t total_resources = 0;
2543
2544 // Only currently testing for graphics and compute pipelines
2545 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2546 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2547 return false;
2548 }
2549
2550 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2551 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2552 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2553 }
2554
2555 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2556 // input from CreatePipeline and CreatePipelineLayout level
2557 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2558 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2559 continue;
2560 }
2561
2562 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2563 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2564 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2565 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2566 // Check only descriptor types listed in maxPerStageResources description in spec
2567 switch (binding->descriptorType) {
2568 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2569 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2570 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2571 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2572 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2573 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2574 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2575 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2576 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2577 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2578 total_resources += binding->descriptorCount;
2579 break;
2580 default:
2581 break;
2582 }
2583 }
2584 }
2585 }
2586
2587 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2588 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2589 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2590 skip |= LogError(pipeline->pipeline, vuid,
2591 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2592 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2593 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2594 }
2595
2596 return skip;
2597}
2598
Jeff Bolze4356752019-03-07 11:23:46 -06002599// copy the specialization constant value into buf, if it is present
2600void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2601 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2602
2603 if (spec && spec_id < spec->mapEntryCount) {
2604 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2605 }
2606}
2607
2608// Fill in value with the constant or specialization constant value, if available.
2609// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002610static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002611 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2612 auto type_id = src->get_def(insn.word(1));
2613 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2614 return false;
2615 }
2616 switch (insn.opcode()) {
2617 case spv::OpSpecConstant:
2618 *value = insn.word(3);
2619 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2620 return true;
2621 case spv::OpConstant:
2622 *value = insn.word(3);
2623 return true;
2624 default:
2625 return false;
2626 }
2627}
2628
2629// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002630VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002631 switch (insn.opcode()) {
2632 case spv::OpTypeInt:
2633 switch (insn.word(2)) {
2634 case 8:
2635 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2636 case 16:
2637 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2638 case 32:
2639 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2640 case 64:
2641 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2642 default:
2643 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2644 }
2645 case spv::OpTypeFloat:
2646 switch (insn.word(2)) {
2647 case 16:
2648 return VK_COMPONENT_TYPE_FLOAT16_NV;
2649 case 32:
2650 return VK_COMPONENT_TYPE_FLOAT32_NV;
2651 case 64:
2652 return VK_COMPONENT_TYPE_FLOAT64_NV;
2653 default:
2654 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2655 }
2656 default:
2657 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2658 }
2659}
2660
2661// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2662// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002663bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002664 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002665 bool skip = false;
2666
2667 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2668 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2669 // Map SPIR-V result ID to the ID of its type.
2670 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2671
2672 struct CoopMatType {
2673 uint32_t scope, rows, cols;
2674 VkComponentTypeNV component_type;
2675 bool all_constant;
2676
2677 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2678
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002679 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002680 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2681 spirv_inst_iter insn = src->get_def(id);
2682 uint32_t component_type_id = insn.word(2);
2683 uint32_t scope_id = insn.word(3);
2684 uint32_t rows_id = insn.word(4);
2685 uint32_t cols_id = insn.word(5);
2686 auto component_type_iter = src->get_def(component_type_id);
2687 auto scope_iter = src->get_def(scope_id);
2688 auto rows_iter = src->get_def(rows_id);
2689 auto cols_iter = src->get_def(cols_id);
2690
2691 all_constant = true;
2692 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2693 all_constant = false;
2694 }
2695 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2696 all_constant = false;
2697 }
2698 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2699 all_constant = false;
2700 }
2701 component_type = GetComponentType(component_type_iter, src);
2702 }
2703 };
2704
2705 bool seen_coopmat_capability = false;
2706
2707 for (auto insn : *src) {
2708 // Whitelist instructions whose result can be a cooperative matrix type, and
2709 // keep track of their types. It would be nice if SPIRV-Headers generated code
2710 // to identify which instructions have a result type and result id. Lacking that,
2711 // this whitelist is based on the set of instructions that
2712 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2713 switch (insn.opcode()) {
2714 case spv::OpLoad:
2715 case spv::OpCooperativeMatrixLoadNV:
2716 case spv::OpCooperativeMatrixMulAddNV:
2717 case spv::OpSNegate:
2718 case spv::OpFNegate:
2719 case spv::OpIAdd:
2720 case spv::OpFAdd:
2721 case spv::OpISub:
2722 case spv::OpFSub:
2723 case spv::OpFDiv:
2724 case spv::OpSDiv:
2725 case spv::OpUDiv:
2726 case spv::OpMatrixTimesScalar:
2727 case spv::OpConstantComposite:
2728 case spv::OpCompositeConstruct:
2729 case spv::OpConvertFToU:
2730 case spv::OpConvertFToS:
2731 case spv::OpConvertSToF:
2732 case spv::OpConvertUToF:
2733 case spv::OpUConvert:
2734 case spv::OpSConvert:
2735 case spv::OpFConvert:
2736 id_to_type_id[insn.word(2)] = insn.word(1);
2737 break;
2738 default:
2739 break;
2740 }
2741
2742 switch (insn.opcode()) {
2743 case spv::OpDecorate:
2744 if (insn.word(2) == spv::DecorationSpecId) {
2745 id_to_spec_id[insn.word(1)] = insn.word(3);
2746 }
2747 break;
2748 case spv::OpCapability:
2749 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2750 seen_coopmat_capability = true;
2751
2752 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002753 skip |= LogError(
2754 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2755 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2756 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002757 }
2758 }
2759 break;
2760 case spv::OpMemoryModel:
2761 // If the capability isn't enabled, don't bother with the rest of this function.
2762 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2763 if (!seen_coopmat_capability) {
2764 return skip;
2765 }
2766 break;
2767 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002768 CoopMatType m;
2769 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002770
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002771 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002772 // Validate that the type parameters are all supported for one of the
2773 // operands of a cooperative matrix property.
2774 bool valid = false;
2775 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002776 if (cooperative_matrix_properties[i].AType == m.component_type &&
2777 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2778 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002779 valid = true;
2780 break;
2781 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002782 if (cooperative_matrix_properties[i].BType == m.component_type &&
2783 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2784 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002785 valid = true;
2786 break;
2787 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002788 if (cooperative_matrix_properties[i].CType == m.component_type &&
2789 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2790 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002791 valid = true;
2792 break;
2793 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002794 if (cooperative_matrix_properties[i].DType == m.component_type &&
2795 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2796 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002797 valid = true;
2798 break;
2799 }
2800 }
2801 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002802 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2803 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2804 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002805 }
2806 }
2807 break;
2808 }
2809 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002810 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002811 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2812 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2813 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2814 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002815 // Couldn't find type of matrix
2816 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002817 break;
2818 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002819 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2820 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2821 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2822 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002823
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002824 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002825 // Validate that the type parameters are all supported for the same
2826 // cooperative matrix property.
2827 bool valid = false;
2828 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002829 if (cooperative_matrix_properties[i].AType == a.component_type &&
2830 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2831 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002832
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002833 cooperative_matrix_properties[i].BType == b.component_type &&
2834 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2835 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002836
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002837 cooperative_matrix_properties[i].CType == c.component_type &&
2838 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2839 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002840
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002841 cooperative_matrix_properties[i].DType == d.component_type &&
2842 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2843 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002844 valid = true;
2845 break;
2846 }
2847 }
2848 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002849 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2850 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2851 "VkCooperativeMatrixPropertiesNV",
2852 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002853 }
2854 }
2855 break;
2856 }
2857 default:
2858 break;
2859 }
2860 }
2861
2862 return skip;
2863}
2864
John Zulaufac4c6e12019-07-01 16:05:58 -06002865bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002866 auto entrypoint_id = entrypoint.word(2);
2867
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002868 // The first denorm execution mode encountered, along with its bit width.
2869 // Used to check if SeparateDenormSettings is respected.
2870 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002871
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002872 // The first rounding mode encountered, along with its bit width.
2873 // Used to check if SeparateRoundingModeSettings is respected.
2874 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002875
2876 bool skip = false;
2877
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002878 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002879 uint32_t invocations = 0;
2880
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002881 for (auto insn : *src) {
2882 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2883 auto mode = insn.word(2);
2884 switch (mode) {
2885 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2886 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002887 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2888 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2889 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002890 skip |= LogError(
2891 device, kVUID_Core_Shader_FeatureNotEnabled,
2892 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2893 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002894 }
2895 break;
2896 }
2897
2898 case spv::ExecutionModeDenormPreserve: {
2899 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002900 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2901 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2902 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002903 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2904 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2905 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002906 }
2907
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002908 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2909 // Register the first denorm execution mode found
2910 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002911 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002912 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002913 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002914 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002915 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2916 "Shader uses different denorm execution modes for 16 and 64-bit but "
2917 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002918 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002919 }
2920 break;
2921
Mike Schuchardt2df08912020-12-15 16:28:09 -08002922 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002923 break;
2924
Mike Schuchardt2df08912020-12-15 16:28:09 -08002925 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002926 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2927 "Shader uses different denorm execution modes for different bit widths but "
2928 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002929 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002930 break;
2931
2932 default:
2933 break;
2934 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002935 }
2936 break;
2937 }
2938
2939 case spv::ExecutionModeDenormFlushToZero: {
2940 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002941 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2942 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2943 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002944 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2945 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2946 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002947 }
2948
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002949 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2950 // Register the first denorm execution mode found
2951 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002952 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002953 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002954 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002955 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002956 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2957 "Shader uses different denorm execution modes for 16 and 64-bit but "
2958 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002959 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002960 }
2961 break;
2962
Mike Schuchardt2df08912020-12-15 16:28:09 -08002963 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002964 break;
2965
Mike Schuchardt2df08912020-12-15 16:28:09 -08002966 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002967 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2968 "Shader uses different denorm execution modes for different bit widths but "
2969 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002970 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002971 break;
2972
2973 default:
2974 break;
2975 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002976 }
2977 break;
2978 }
2979
2980 case spv::ExecutionModeRoundingModeRTE: {
2981 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002982 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2983 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2984 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002985 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2986 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2987 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002988 }
2989
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002990 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2991 // Register the first rounding mode found
2992 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002993 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002994 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002995 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002996 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002997 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2998 "Shader uses different rounding modes for 16 and 64-bit but "
2999 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003000 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003001 }
3002 break;
3003
Mike Schuchardt2df08912020-12-15 16:28:09 -08003004 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003005 break;
3006
Mike Schuchardt2df08912020-12-15 16:28:09 -08003007 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003008 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3009 "Shader uses different rounding modes for different bit widths but "
3010 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003011 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003012 break;
3013
3014 default:
3015 break;
3016 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003017 }
3018 break;
3019 }
3020
3021 case spv::ExecutionModeRoundingModeRTZ: {
3022 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003023 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3024 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3025 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003026 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3027 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3028 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003029 }
3030
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003031 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3032 // Register the first rounding mode found
3033 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003034 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003035 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003036 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003037 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003038 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3039 "Shader uses different rounding modes for 16 and 64-bit but "
3040 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003041 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003042 }
3043 break;
3044
Mike Schuchardt2df08912020-12-15 16:28:09 -08003045 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003046 break;
3047
Mike Schuchardt2df08912020-12-15 16:28:09 -08003048 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003049 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3050 "Shader uses different rounding modes for different bit widths but "
3051 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003052 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003053 break;
3054
3055 default:
3056 break;
3057 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003058 }
3059 break;
3060 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003061
3062 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003063 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003064 break;
3065 }
3066
3067 case spv::ExecutionModeInvocations: {
3068 invocations = insn.word(3);
3069 break;
3070 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003071 }
3072 }
3073 }
3074
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003075 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003076 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003077 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3078 "Geometry shader entry point must have an OpExecutionMode instruction that "
3079 "specifies a maximum output vertex count that is greater than 0 and less "
3080 "than or equal to maxGeometryOutputVertices. "
3081 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003082 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003083 }
3084
3085 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003086 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3087 "Geometry shader entry point must have an OpExecutionMode instruction that "
3088 "specifies an invocation count that is greater than 0 and less "
3089 "than or equal to maxGeometryShaderInvocations. "
3090 "Invocations=%d, maxGeometryShaderInvocations=%d",
3091 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003092 }
3093 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003094 return skip;
3095}
3096
locke-lunargd9a069d2019-09-17 01:50:19 -06003097uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003098 auto type = module->get_def(type_id);
3099
3100 while (true) {
3101 switch (type.opcode()) {
3102 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003103 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003104 case spv::OpTypeSampledImage:
3105 type = module->get_def(type.word(2));
3106 break;
3107 case spv::OpTypePointer:
3108 type = module->get_def(type.word(3));
3109 break;
3110 case spv::OpTypeImage: {
3111 auto dim = type.word(3);
3112 auto arrayed = type.word(5);
3113 auto msaa = type.word(6);
3114
Chris Forbes74ba2232018-08-27 15:19:27 -07003115 uint32_t bits = 0;
3116 switch (GetFundamentalType(module, type.word(2))) {
3117 case FORMAT_TYPE_FLOAT:
3118 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3119 break;
3120 case FORMAT_TYPE_UINT:
3121 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3122 break;
3123 case FORMAT_TYPE_SINT:
3124 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3125 break;
3126 default:
3127 break;
3128 }
3129
Chris Forbes47567b72017-06-09 12:09:45 -07003130 switch (dim) {
3131 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003132 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3133 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003134 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003135 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3136 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3137 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003138 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003139 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3140 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003141 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003142 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3143 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003144 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003145 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3146 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003147 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003148 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003149 }
3150 }
3151 default:
3152 return 0;
3153 }
3154 }
3155}
3156
3157// For given pipelineLayout verify that the set_layout_node at slot.first
3158// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003159static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003160 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003161 if (!pipelineLayout) return nullptr;
3162
3163 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3164
3165 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3166}
3167
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003168int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3169 if (module == nullptr) return -1;
3170
3171 auto type = module->get_def(resource.type_id);
3172 while (true) {
3173 switch (type.opcode()) {
3174 case spv::OpTypeSampledImage:
3175 type = module->get_def(type.word(2));
3176 break;
3177 case spv::OpTypePointer:
3178 type = module->get_def(type.word(3));
3179 break;
3180 case spv::OpTypeImage:
3181 return type.word(3);
3182 default:
3183 return -1;
3184 }
3185 }
3186}
3187
3188bool 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 -06003189 for (auto insn : *src) {
3190 if (insn.opcode() == spv::OpEntryPoint) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003191 auto execution_model = insn.word(1);
3192 auto entrypoint_stage_bits = ExecutionModelToShaderStageFlagBits(execution_model);
3193 if (entrypoint_stage_bits == VK_SHADER_STAGE_COMPUTE_BIT) {
Locke1ec6d952019-04-02 11:57:21 -06003194 auto entrypoint_id = insn.word(2);
3195 for (auto insn1 : *src) {
3196 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3197 insn1.word(2) == spv::ExecutionModeLocalSize) {
3198 local_size_x = insn1.word(3);
3199 local_size_y = insn1.word(4);
3200 local_size_z = insn1.word(5);
3201 return true;
3202 }
3203 }
3204 }
3205 }
3206 }
3207 return false;
3208}
3209
locke-lunargd9a069d2019-09-17 01:50:19 -06003210void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003211 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003212 bool is_point_mode = false;
3213
3214 for (auto insn : *src) {
3215 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3216 switch (insn.word(2)) {
3217 case spv::ExecutionModePointMode:
3218 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3219 is_point_mode = true;
3220 break;
3221
3222 case spv::ExecutionModeOutputPoints:
3223 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3224 break;
3225
3226 case spv::ExecutionModeIsolines:
3227 case spv::ExecutionModeOutputLineStrip:
3228 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3229 break;
3230
3231 case spv::ExecutionModeTriangles:
3232 case spv::ExecutionModeQuads:
3233 case spv::ExecutionModeOutputTriangleStrip:
3234 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3235 break;
3236 }
3237 }
3238 }
3239
3240 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3241}
3242
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003243// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3244// o If there is only a vertex shader : gl_PointSize must be written when using points
3245// o If there is a geometry or tessellation shader:
3246// - If shaderTessellationAndGeometryPointSize feature is enabled:
3247// * gl_PointSize must be written in the final geometry stage
3248// - If shaderTessellationAndGeometryPointSize feature is disabled:
3249// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003250bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003251 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003252 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3253 return false;
3254 }
3255
3256 bool pointsize_written = false;
3257 bool skip = false;
3258
3259 // Search for PointSize built-in decorations
3260 std::vector<uint32_t> pointsize_builtin_offsets;
3261 spirv_inst_iter insn = entrypoint;
3262 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3263 if (insn.opcode() == spv::OpMemberDecorate) {
3264 if (insn.word(3) == spv::DecorationBuiltIn) {
3265 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003266 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003267 }
3268 }
3269 } else if (insn.opcode() == spv::OpDecorate) {
3270 if (insn.word(2) == spv::DecorationBuiltIn) {
3271 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003272 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003273 }
3274 }
3275 }
3276
3277 insn++;
3278 }
3279
3280 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003281 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003282 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003283 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3284 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3285 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003286 }
3287 } else if (!pointsize_written) {
3288 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003289 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3290 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3291 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003292 }
3293 return skip;
3294}
John Zulauf14c355b2019-06-27 16:09:37 -06003295
Tobias Hector6663c9b2020-11-05 10:18:02 +00003296bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3297 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3298 bool primitiverate_written = false;
3299 bool viewportindex_written = false;
3300 bool viewportmask_written = false;
3301 bool skip = false;
3302
3303 // Check if the primitive shading rate is written
3304 spirv_inst_iter insn = entrypoint;
3305 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3306 if (insn.opcode() == spv::OpMemberDecorate) {
3307 if (insn.word(3) == spv::DecorationBuiltIn) {
3308 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3309 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3310 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3311 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3312 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3313 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3314 }
3315 }
3316 } else if (insn.opcode() == spv::OpDecorate) {
3317 if (insn.word(2) == spv::DecorationBuiltIn) {
3318 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3319 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3320 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3321 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3322 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3323 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3324 }
3325 }
3326 }
3327
3328 insn++;
3329 }
3330
3331 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports) {
3332 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3333 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
3334 skip |= LogError(
3335 pipeline->pipeline, "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3336 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but multiple viewports "
3337 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3338 string_VkShaderStageFlagBits(stage));
3339 }
3340
3341 if (primitiverate_written && viewportindex_written) {
3342 skip |= LogError(pipeline->pipeline,
3343 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3344 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3345 "ViewportIndex built-ins,"
3346 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3347 string_VkShaderStageFlagBits(stage));
3348 }
3349
3350 if (primitiverate_written && viewportmask_written) {
3351 skip |= LogError(pipeline->pipeline,
3352 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3353 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3354 "ViewportMaskNV built-ins,"
3355 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3356 string_VkShaderStageFlagBits(stage));
3357 }
3358 }
3359 return skip;
3360}
3361
John Zulauf14c355b2019-06-27 16:09:37 -06003362bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3363 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003364 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003365 bool skip = false;
3366
3367 // Check the module
3368 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003369 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3370 "%s does not contain valid spirv for stage %s.",
3371 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003372 }
3373
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003374 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3375 // specializations should be applied and validated.
3376 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3377 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3378 // Gather the specialization-constant values.
3379 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003380 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003381 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3382 id_value_map.reserve(specialization_info->mapEntryCount);
3383 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3384 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003385
Jeremy Hayes521221d2020-01-15 16:48:49 -07003386 // Expect only scalar types.
3387 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3388 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3389 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003390 }
3391
3392 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003393 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003394 spvtools::Optimizer optimizer(spirv_environment);
3395 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3396 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003397 skip |= LogError(
3398 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003399 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3400 };
3401 optimizer.SetMessageConsumer(consumer);
3402 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3403 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3404 std::vector<uint32_t> specialized_spirv;
3405 auto const optimized =
3406 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3407 assert(optimized == true);
3408
3409 if (optimized) {
3410 spv_context ctx = spvContextCreate(spirv_environment);
3411 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3412 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003413 spvtools::ValidatorOptions options;
3414 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003415 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3416 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003417 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003418 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3419 report_data->FormatHandle(module->vk_shader_module).c_str(),
3420 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003421 }
3422
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003423 spvDiagnosticDestroy(diag);
3424 spvContextDestroy(ctx);
3425 }
3426 }
3427
John Zulauf14c355b2019-06-27 16:09:37 -06003428 // Check the entrypoint
3429 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003430 skip |=
3431 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3432 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003433 }
3434 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3435
3436 // Mark accessible ids
3437 auto &accessible_ids = stage_state.accessible_ids;
3438
Chris Forbes47567b72017-06-09 12:09:45 -07003439 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003440 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3441 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003442
Chris Forbes349b3132018-03-07 11:38:08 -08003443 // Validate shader capabilities against enabled device features
sfricke-samsung0065ce02020-12-03 22:46:37 -08003444 skip |= ValidateShaderCapabilitiesAndExtensions(module);
locke-lunarg63e4daf2020-08-17 17:53:25 -06003445 skip |=
3446 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003447 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003448 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05003449 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003450 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003451 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003452 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003453 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003454 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003455 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003456 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003457 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003458 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3459 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3460 }
Chris Forbes47567b72017-06-09 12:09:45 -07003461
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003462 std::string vuid_layout_mismatch;
3463 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3464 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3465 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3466 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3467 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3468 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3469 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3470 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3471 }
3472
Chris Forbes47567b72017-06-09 12:09:45 -07003473 // Validate descriptor use
3474 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003475 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003476 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003477 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003478 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3479 std::set<uint32_t> descriptor_types =
3480 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003481
3482 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003483 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003484 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3485 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003486 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003487 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003488 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3489 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003490 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003491 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003492 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3493 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3494 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003495 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003496 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003497 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3498 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003499 }
3500 }
3501
3502 // Validate use of input attachments against subpass structure
3503 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003504 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003505
Petr Krause91f7a12017-12-14 20:57:36 +01003506 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003507 auto subpass = pipeline->graphicsPipelineCI.subpass;
3508
3509 for (auto use : input_attachment_uses) {
3510 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3511 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003512 ? input_attachments[use.first].attachment
3513 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003514
3515 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003516 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3517 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003518 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003519 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003520 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3521 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3522 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003523 }
3524 }
3525 }
Lockeaa8fdc02019-04-02 11:59:20 -06003526 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3527 skip |= ValidateComputeWorkGroupSizes(module);
3528 }
Chris Forbes47567b72017-06-09 12:09:45 -07003529 return skip;
3530}
3531
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003532bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3533 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3534 spirv_inst_iter consumer_entrypoint,
3535 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003536 bool skip = false;
3537
3538 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003539 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3540 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003541
3542 auto a_it = outputs.begin();
3543 auto b_it = inputs.begin();
3544
3545 // Maps sorted by key (location); walk them together to find mismatches
3546 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3547 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3548 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3549 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3550 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3551
3552 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003553 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3554 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3555 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003556 a_it++;
3557 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003558 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3559 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3560 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003561 b_it++;
3562 } else {
3563 // subtleties of arrayed interfaces:
3564 // - if is_patch, then the member is not arrayed, even though the interface may be.
3565 // - if is_block_member, then the extra array level of an arrayed interface is not
3566 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003567 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3568 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3569 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003570 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3571 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3572 DescribeType(producer, a_it->second.type_id).c_str(),
3573 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003574 }
3575 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003576 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3577 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3578 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3579 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003580 }
3581 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003582 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3583 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3584 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003585 }
3586 a_it++;
3587 b_it++;
3588 }
3589 }
3590
Ari Suonpaa696b3432019-03-11 14:02:57 +02003591 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3592 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3593 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3594
3595 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3596 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003597 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3598 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003599 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3600 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003601 } else {
3602 auto it_producer = builtins_producer.begin();
3603 auto it_consumer = builtins_consumer.begin();
3604 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3605 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003606 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3607 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3608 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003609 break;
3610 }
3611 it_producer++;
3612 it_consumer++;
3613 }
3614 }
3615 }
3616 }
3617
Chris Forbes47567b72017-06-09 12:09:45 -07003618 return skip;
3619}
3620
John Zulauf14c355b2019-06-27 16:09:37 -06003621static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003622 uint32_t stage_mask = 0;
3623 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3624 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3625 stage_mask |= pCreateInfo->pStages[i].stage;
3626 }
3627 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003628 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3629 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3630 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003631 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3632 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3633 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3634 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3635 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003636 }
3637 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003638 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003639}
3640
Chris Forbes47567b72017-06-09 12:09:45 -07003641// Validate that the shaders used by the given pipeline and store the active_slots
3642// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003643bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003644 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003645 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3646 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003647
John Zulauf14c355b2019-06-27 16:09:37 -06003648 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003649 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003650 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003651 bool skip = false;
3652
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003653 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003654
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003655 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3656 auto stage = &create_info->pStages[i];
3657 auto stage_id = GetShaderStageId(stage->stage);
3658 shaders[stage_id] = GetShaderModuleState(stage->module);
3659 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3660 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3661 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003662 }
3663
3664 // if the shader stages are no good individually, cross-stage validation is pointless.
3665 if (skip) return true;
3666
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003667 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003668
3669 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003670 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003671 }
3672
3673 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003674 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003675 }
3676
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003677 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3678 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003679
3680 while (!shaders[producer] && producer != fragment_stage) {
3681 producer++;
3682 consumer++;
3683 }
3684
3685 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3686 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003687 if (shaders[consumer]) {
3688 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003689 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3690 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003691 }
Chris Forbes47567b72017-06-09 12:09:45 -07003692
3693 producer = consumer;
3694 }
3695 }
3696
3697 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003698 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003699 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003700 }
3701
3702 return skip;
3703}
3704
Tobias Hector6663c9b2020-11-05 10:18:02 +00003705bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3706 const char *caller, const DrawDispatchVuid &vuid) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003707 auto create_info = pipeline->graphicsPipelineCI.ptr();
Tobias Hector6663c9b2020-11-05 10:18:02 +00003708
3709 const SHADER_MODULE_STATE *shaders[32];
3710 memset(shaders, 0, sizeof(shaders));
3711 spirv_inst_iter entrypoints[32];
3712 memset(entrypoints, 0, sizeof(entrypoints));
3713 bool skip = false;
3714
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003715 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3716 auto stage = &create_info->pStages[i];
3717 auto stage_id = GetShaderStageId(stage->stage);
3718 shaders[stage_id] = GetShaderModuleState(stage->module);
3719 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003720
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003721 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3722 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003723 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3724 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3725 spirv_inst_iter insn = entrypoints[stage_id];
3726 bool primitiverate_written = false;
3727
3728 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3729 if (insn.opcode() == spv::OpMemberDecorate) {
3730 if (insn.word(3) == spv::DecorationBuiltIn) {
3731 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3732 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3733 }
3734 }
3735 } else if (insn.opcode() == spv::OpDecorate) {
3736 if (insn.word(2) == spv::DecorationBuiltIn) {
3737 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3738 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3739 }
3740 }
3741 }
3742
3743 insn++;
3744 }
3745
3746 if (primitiverate_written) {
3747 skip |=
3748 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3749 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3750 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3751 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003752 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003753 }
3754 }
3755 }
3756 }
3757
3758 return skip;
3759}
3760
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003761bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003762 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003763
John Zulauf14c355b2019-06-27 16:09:37 -06003764 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3765 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003766
John Zulauf14c355b2019-06-27 16:09:37 -06003767 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003768}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003769
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003770uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3771 uint32_t total = 0;
3772
3773 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3774 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3775 if (stages[stage_index].stage == stageBit) {
3776 total++;
3777 }
3778 }
3779
3780 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3781 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3782 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3783 total += CalcShaderStageCount(library_pipeline, stageBit);
3784 }
3785 }
3786
3787 return total;
3788}
3789
sourav parmarcd5fb182020-07-17 12:58:44 -07003790bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003791 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003792
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003793 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003794 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3795 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3796 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3797 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3798 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3799 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3800 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003801 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003802 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3803 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003804 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003805 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003806 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003807 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3808 skip |= LogError(
3809 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3810 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3811 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003812 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003813 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3814 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003815 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3816 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003817 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003818 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003819 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3820 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3821 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3822 "member must have been created with values of the maxPipelineRayPayloadSize and "
3823 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3824 }
3825 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003826 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003827 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3828 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3829 "vkCreateRayTracingPipelinesKHR: If flags includes "
3830 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3831 "the pLibraries member of libraries must have been created with the "
3832 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3833 }
sourav parmar83c31b12020-05-06 12:30:54 -07003834 }
3835 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003836 } else {
3837 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003838 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3839 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3840 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003841 pipeline->raytracingPipelineCI.maxRecursionDepth,
3842 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3843 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003844 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003845 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3846 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3847
John Zulaufe4474e72019-07-01 17:28:27 -06003848 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003849 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003850
John Zulaufe4474e72019-07-01 17:28:27 -06003851 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3852 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003853
John Zulaufe4474e72019-07-01 17:28:27 -06003854 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003855 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003856
3857 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3858 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3859 if (raygen_stages_count == 0) {
3860 skip |= LogError(
3861 device,
3862 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3863 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3864 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003865 }
3866
3867 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3868 const auto &group = groups[group_index];
3869
3870 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3871 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3872 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3873 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3874 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003875 skip |= LogError(device,
3876 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3877 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3878 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003879 }
3880 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3881 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003882 skip |= LogError(device,
3883 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3884 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3885 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003886 }
3887 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3888 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3889 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003890 skip |= LogError(device,
3891 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3892 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3893 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003894 }
3895 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3896 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003897 skip |= LogError(device,
3898 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3899 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3900 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003901 }
3902 }
3903
3904 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3905 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3906 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3907 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003908 skip |= LogError(device,
3909 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3910 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3911 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003912 }
3913 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3914 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3915 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003916 skip |= LogError(device,
3917 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3918 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3919 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003920 }
3921 }
John Zulaufe4474e72019-07-01 17:28:27 -06003922 }
3923 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003924}
3925
Dave Houltona9df0ce2018-02-07 10:51:23 -07003926uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003927
Dave Houltona9df0ce2018-02-07 10:51:23 -07003928static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003929 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3930 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003931 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003932 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003933 return nullptr;
3934}
3935
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003936bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003937 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003938 bool skip = false;
3939 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003940
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003941 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003942 return false;
3943 }
3944
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003945 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003946
3947 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003948 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3949 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3950 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003951 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003952 auto cache = GetValidationCacheInfo(pCreateInfo);
3953 uint32_t hash = 0;
3954 if (cache) {
3955 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003956 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003957 }
3958
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003959 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
3960 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003961 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06003962 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003963 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003964 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003965 spvtools::ValidatorOptions options;
3966 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06003967 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003968 if (spv_valid != SPV_SUCCESS) {
3969 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003970 if (spv_valid == SPV_WARNING) {
3971 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3972 diag && diag->error ? diag->error : "(no error text)");
3973 } else {
3974 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3975 diag && diag->error ? diag->error : "(no error text)");
3976 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003977 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003978 } else {
3979 if (cache) {
3980 cache->Insert(hash);
3981 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003982 }
3983
3984 spvDiagnosticDestroy(diag);
3985 spvContextDestroy(ctx);
3986 }
3987
Chris Forbes4ae55b32017-06-09 14:42:56 -07003988 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003989}
3990
John Zulaufac4c6e12019-07-01 16:05:58 -06003991bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003992 bool skip = false;
3993 uint32_t local_size_x = 0;
3994 uint32_t local_size_y = 0;
3995 uint32_t local_size_z = 0;
3996 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3997 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003998 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3999 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4000 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4001 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004002 }
4003 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004004 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4005 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4006 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4007 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004008 }
4009 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004010 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4011 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4012 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4013 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004014 }
4015
4016 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4017 uint64_t invocations = local_size_x * local_size_y;
4018 // Prevent overflow.
4019 bool fail = false;
4020 if (invocations > UINT32_MAX || invocations > limit) {
4021 fail = true;
4022 }
4023 if (!fail) {
4024 invocations *= local_size_z;
4025 if (invocations > UINT32_MAX || invocations > limit) {
4026 fail = true;
4027 }
4028 }
4029 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004030 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4031 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4032 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4033 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4034 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004035 }
4036 }
4037 return skip;
4038}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004039
4040spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4041 if (api_version >= VK_API_VERSION_1_2) {
4042 return SPV_ENV_VULKAN_1_2;
4043 } else if (api_version >= VK_API_VERSION_1_1) {
4044 if (spirv_1_4) {
4045 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4046 } else {
4047 return SPV_ENV_VULKAN_1_1;
4048 }
4049 }
4050 return SPV_ENV_VULKAN_1_0;
4051}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004052
4053void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4054 spvtools::ValidatorOptions &options) {
4055 if (device_extensions.vk_khr_relaxed_block_layout) {
4056 options.SetRelaxBlockLayout(true);
4057 }
4058 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4059 options.SetUniformBufferStandardLayout(true);
4060 }
4061 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4062 options.SetScalarBlockLayout(true);
4063 }
4064}