blob: bd5a5d2be0d0d9c08aa2de794b077d3028e9ae80 [file] [log] [blame]
sfricke-samsung691299b2021-01-01 20:48:48 -08001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
Tobias Hector6663c9b2020-11-05 10:18:02 +00005 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Chris Forbes47567b72017-06-09 12:09:45 -07006 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060020 * Author: Dave Houlton <daveh@lunarg.com>
Tobias Hector6663c9b2020-11-05 10:18:02 +000021 * Author: Tobias Hector <tobias.hector@amd.com>
Chris Forbes47567b72017-06-09 12:09:45 -070022 */
23
Petr Kraus25810d02019-08-27 17:41:15 +020024#include "shader_validation.h"
25
Chris Forbes47567b72017-06-09 12:09:45 -070026#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020027#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060029#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070031#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <string>
33#include <unordered_map>
34#include <vector>
35
Mark Lobodzinski102687e2020-04-28 11:03:28 -060036#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_loader_platform.h"
38#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039#include "vk_layer_data.h"
40#include "vk_layer_extension_utils.h"
41#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070042#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070043#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020044
Chris Forbes4ae55b32017-06-09 14:42:56 -070045#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070046#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070047
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080048void decoration_set::add(uint32_t decoration, uint32_t value) {
49 switch (decoration) {
50 case spv::DecorationLocation:
51 flags |= location_bit;
52 location = value;
53 break;
54 case spv::DecorationPatch:
55 flags |= patch_bit;
56 break;
57 case spv::DecorationRelaxedPrecision:
58 flags |= relaxed_precision_bit;
59 break;
60 case spv::DecorationBlock:
61 flags |= block_bit;
62 break;
63 case spv::DecorationBufferBlock:
64 flags |= buffer_block_bit;
65 break;
66 case spv::DecorationComponent:
67 flags |= component_bit;
68 component = value;
69 break;
70 case spv::DecorationInputAttachmentIndex:
71 flags |= input_attachment_index_bit;
72 input_attachment_index = value;
73 break;
74 case spv::DecorationDescriptorSet:
75 flags |= descriptor_set_bit;
76 descriptor_set = value;
77 break;
78 case spv::DecorationBinding:
79 flags |= binding_bit;
80 binding = value;
81 break;
82 case spv::DecorationNonWritable:
83 flags |= nonwritable_bit;
84 break;
85 case spv::DecorationBuiltIn:
86 flags |= builtin_bit;
87 builtin = value;
88 break;
89 }
90}
91
Chris Forbes47567b72017-06-09 12:09:45 -070092enum FORMAT_TYPE {
93 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
94 FORMAT_TYPE_SINT = 2,
95 FORMAT_TYPE_UINT = 4,
96};
97
98typedef std::pair<unsigned, unsigned> location_t;
99
Chris Forbes47567b72017-06-09 12:09:45 -0700100static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
102 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
103 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
104 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
105 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700106};
107
John Zulauf14c355b2019-06-27 16:09:37 -0600108unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
109
Chris Forbes47567b72017-06-09 12:09:45 -0700110// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600111void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600112 function_set func_set = {};
113 EntryPoint *entry_point = nullptr;
114
Chris Forbes47567b72017-06-09 12:09:45 -0700115 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600116 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 if (func_set.offset) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600118 func_set.op_lists.insert({insn.opcode(), insn.offset()});
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700119 } else if (entry_point) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600120 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
121 }
122
Chris Forbes47567b72017-06-09 12:09:45 -0700123 switch (insn.opcode()) {
124 // Types
125 case spv::OpTypeVoid:
126 case spv::OpTypeBool:
127 case spv::OpTypeInt:
128 case spv::OpTypeFloat:
129 case spv::OpTypeVector:
130 case spv::OpTypeMatrix:
131 case spv::OpTypeImage:
132 case spv::OpTypeSampler:
133 case spv::OpTypeSampledImage:
134 case spv::OpTypeArray:
135 case spv::OpTypeRuntimeArray:
136 case spv::OpTypeStruct:
137 case spv::OpTypeOpaque:
138 case spv::OpTypePointer:
139 case spv::OpTypeFunction:
140 case spv::OpTypeEvent:
141 case spv::OpTypeDeviceEvent:
142 case spv::OpTypeReserveId:
143 case spv::OpTypeQueue:
144 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600145 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600146 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700147 def_index[insn.word(1)] = insn.offset();
148 break;
149
150 // Fixed constants
151 case spv::OpConstantTrue:
152 case spv::OpConstantFalse:
153 case spv::OpConstant:
154 case spv::OpConstantComposite:
155 case spv::OpConstantSampler:
156 case spv::OpConstantNull:
157 def_index[insn.word(2)] = insn.offset();
158 break;
159
160 // Specialization constants
161 case spv::OpSpecConstantTrue:
162 case spv::OpSpecConstantFalse:
163 case spv::OpSpecConstant:
164 case spv::OpSpecConstantComposite:
165 case spv::OpSpecConstantOp:
166 def_index[insn.word(2)] = insn.offset();
167 break;
168
169 // Variables
170 case spv::OpVariable:
171 def_index[insn.word(2)] = insn.offset();
172 break;
173
174 // Functions
175 case spv::OpFunction:
176 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600177 func_set.id = insn.word(2);
178 func_set.offset = insn.offset();
179 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700180 break;
181
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800182 // Decorations
183 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700184 auto target_id = insn.word(1);
185 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
sfricke-samsung94d71a52021-02-26 05:25:43 -0800186 decoration_inst.push_back(insn);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800187 } break;
188 case spv::OpGroupDecorate: {
189 auto const &src = decorations[insn.word(1)];
190 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
191 } break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800192 case spv::OpMemberDecorate: {
193 member_decoration_inst.push_back(insn);
194 } break;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800195
John Zulauf14c355b2019-06-27 16:09:37 -0600196 // Entry points ... add to the entrypoint table
197 case spv::OpEntryPoint: {
198 // 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 -0700199 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600200 auto execution_model = insn.word(1);
201 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600202 entry_points.emplace(entrypoint_name,
203 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
204
205 auto range = entry_points.equal_range(entrypoint_name);
206 for (auto it = range.first; it != range.second; ++it) {
207 if (it->second.offset == insn.offset()) {
208 entry_point = &(it->second);
209 break;
210 }
211 }
212 assert(entry_point != nullptr);
213 break;
214 }
215 case spv::OpFunctionEnd: {
216 assert(entry_point != nullptr);
217 func_set.length = insn.offset() - func_set.offset;
218 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600219 break;
220 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800221
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700222 // Copy operations
223 case spv::OpCopyLogical:
224 case spv::OpCopyObject: {
225 def_index[insn.word(2)] = insn.offset();
226 break;
227 }
228
Chris Forbes47567b72017-06-09 12:09:45 -0700229 default:
230 // We don't care about any other defs for now.
231 break;
232 }
233 }
234}
235
Jeff Bolz105d6492018-09-29 15:46:44 -0500236unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
237 switch (mode) {
238 case spv::ExecutionModelVertex:
239 return VK_SHADER_STAGE_VERTEX_BIT;
240 case spv::ExecutionModelTessellationControl:
241 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
242 case spv::ExecutionModelTessellationEvaluation:
243 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
244 case spv::ExecutionModelGeometry:
245 return VK_SHADER_STAGE_GEOMETRY_BIT;
246 case spv::ExecutionModelFragment:
247 return VK_SHADER_STAGE_FRAGMENT_BIT;
248 case spv::ExecutionModelGLCompute:
249 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600250 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700251 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600252 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700253 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600254 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700255 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600256 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700257 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600258 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700259 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600260 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700261 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500262 case spv::ExecutionModelTaskNV:
263 return VK_SHADER_STAGE_TASK_BIT_NV;
264 case spv::ExecutionModelMeshNV:
265 return VK_SHADER_STAGE_MESH_BIT_NV;
266 default:
267 return 0;
268 }
269}
270
locke-lunargde3f0fa2020-09-10 11:55:31 -0600271const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
272 VkShaderStageFlagBits stageBits) {
273 auto range = src->entry_points.equal_range(name);
274 for (auto it = range.first; it != range.second; ++it) {
275 if (it->second.stage == stageBits) {
276 return &(it->second);
277 }
278 }
279 return nullptr;
280}
281
locke-lunargd9a069d2019-09-17 01:50:19 -0600282spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600283 auto range = src->entry_points.equal_range(name);
284 for (auto it = range.first; it != range.second; ++it) {
285 if (it->second.stage == stageBits) {
286 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700287 }
288 }
Chris Forbes47567b72017-06-09 12:09:45 -0700289 return src->end();
290}
291
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600292static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700293 switch (sc) {
294 case spv::StorageClassInput:
295 return "input";
296 case spv::StorageClassOutput:
297 return "output";
298 case spv::StorageClassUniformConstant:
299 return "const uniform";
300 case spv::StorageClassUniform:
301 return "uniform";
302 case spv::StorageClassWorkgroup:
303 return "workgroup local";
304 case spv::StorageClassCrossWorkgroup:
305 return "workgroup global";
306 case spv::StorageClassPrivate:
307 return "private global";
308 case spv::StorageClassFunction:
309 return "function";
310 case spv::StorageClassGeneric:
311 return "generic";
312 case spv::StorageClassAtomicCounter:
313 return "atomic counter";
314 case spv::StorageClassImage:
315 return "image";
316 case spv::StorageClassPushConstant:
317 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800318 case spv::StorageClassStorageBuffer:
319 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700320 default:
321 return "unknown";
322 }
323}
324
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700325// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
326// Otherwise, returns src->end().
327spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700328 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700329
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700330 // If id is a copy, see where it was copied from
331 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
332 id = value.word(3);
333 value = src->get_def(id);
334 }
335
336 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
337 return value;
338 }
339 return src->end();
340}
341
342// Assumes itr points to an OpConstant instruction
343uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
344
345// Either returns the constant value described by the instruction at id, or 1
346uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
347 auto value = GetConstantDef(src, id);
348
349 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700350 // TODO: Either ensure that the specialization transform is already performed on a module we're
351 // considering here, OR -- specialize on the fly now.
352 return 1;
353 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700354 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700355}
356
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600357static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 auto insn = src->get_def(type);
359 assert(insn != src->end());
360
361 switch (insn.opcode()) {
362 case spv::OpTypeBool:
363 ss << "bool";
364 break;
365 case spv::OpTypeInt:
366 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
367 break;
368 case spv::OpTypeFloat:
369 ss << "float" << insn.word(2);
370 break;
371 case spv::OpTypeVector:
372 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600373 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700374 break;
375 case spv::OpTypeMatrix:
376 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600377 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700378 break;
379 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600380 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
381 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700382 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700383 case spv::OpTypeRuntimeArray:
384 ss << "runtime arr[] of ";
385 DescribeTypeInner(ss, src, insn.word(2));
386 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700387 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600388 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
389 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700390 break;
391 case spv::OpTypeStruct: {
392 ss << "struct of (";
393 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600394 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700395 if (i == insn.len() - 1) {
396 ss << ")";
397 } else {
398 ss << ", ";
399 }
400 }
401 break;
402 }
403 case spv::OpTypeSampler:
404 ss << "sampler";
405 break;
406 case spv::OpTypeSampledImage:
407 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600408 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700409 break;
410 case spv::OpTypeImage:
411 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
412 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600413 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500414 ss << "accelerationStruture";
415 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700416 default:
417 ss << "oddtype";
418 break;
419 }
420}
421
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600422static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700423 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600424 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700425 return ss.str();
426}
427
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600428static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700429 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
430 return type.word(2) < 64;
431}
432
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600433static 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 -0600434 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700435 // Walk two type trees together, and complain about differences
436 auto a_insn = a->get_def(a_type);
437 auto b_insn = b->get_def(b_type);
438 assert(a_insn != a->end());
439 assert(b_insn != b->end());
440
Chris Forbes062f1222018-08-21 15:34:15 -0700441 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
442
Chris Forbes47567b72017-06-09 12:09:45 -0700443 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600444 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700445 }
446
447 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
448 // 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 -0600449 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700450 }
451
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600452 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
453 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700454 }
455
456 if (a_insn.opcode() != b_insn.opcode()) {
457 return false;
458 }
459
460 if (a_insn.opcode() == spv::OpTypePointer) {
461 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600462 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700463 }
464
465 if (a_arrayed || b_arrayed) {
466 // If we havent resolved array-of-verts by here, we're not going to.
467 return false;
468 }
469
470 switch (a_insn.opcode()) {
471 case spv::OpTypeBool:
472 return true;
473 case spv::OpTypeInt:
474 // Match on width, signedness
475 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
476 case spv::OpTypeFloat:
477 // Match on width
478 return a_insn.word(2) == b_insn.word(2);
479 case spv::OpTypeVector:
480 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600481 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
482 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700483 return a_insn.word(3) >= b_insn.word(3);
484 } else {
485 return a_insn.word(3) == b_insn.word(3);
486 }
487 case spv::OpTypeMatrix:
488 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600489 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700490 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700491 case spv::OpTypeArray:
492 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
493 // 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 -0600494 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
495 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700496 case spv::OpTypeStruct:
497 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700498 {
499 if (a_insn.len() != b_insn.len()) {
500 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700501 }
Chris Forbes47567b72017-06-09 12:09:45 -0700502
Dave Houltona9df0ce2018-02-07 10:51:23 -0700503 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600504 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700505 return false;
506 }
507 }
508
509 return true;
510 }
Chris Forbes47567b72017-06-09 12:09:45 -0700511 default:
512 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
513 return false;
514 }
515}
516
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600517static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700518 auto insn = src->get_def(type);
519 assert(insn != src->end());
520
521 switch (insn.opcode()) {
522 case spv::OpTypePointer:
523 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
524 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600525 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700526 case spv::OpTypeArray:
527 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600528 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700529 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600530 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700531 }
532 case spv::OpTypeMatrix:
533 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600534 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700535 case spv::OpTypeVector: {
536 auto scalar_type = src->get_def(insn.word(2));
537 auto bit_width =
538 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
539
540 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
541 return (bit_width * insn.word(3) + 127) / 128;
542 }
543 default:
544 // Everything else is just 1.
545 return 1;
546
547 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
548 }
549}
550
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600551static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200552 auto insn = src->get_def(type);
553 assert(insn != src->end());
554
555 switch (insn.opcode()) {
556 case spv::OpTypePointer:
557 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
558 // pointers around.
559 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
560 case spv::OpTypeStruct: {
561 uint32_t sum = 0;
562 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
563 sum += GetComponentsConsumedByType(src, insn.word(i), false);
564 }
565 return sum;
566 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500567 case spv::OpTypeArray:
568 if (strip_array_level) {
569 return GetComponentsConsumedByType(src, insn.word(2), false);
570 } else {
571 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200572 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200573 case spv::OpTypeMatrix:
574 // Num locations is the dimension * element size
575 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
576 case spv::OpTypeVector: {
577 auto scalar_type = src->get_def(insn.word(2));
578 auto bit_width =
579 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
580 // One component is 32-bit
581 return (bit_width * insn.word(3) + 31) / 32;
582 }
583 case spv::OpTypeFloat: {
584 auto bit_width = insn.word(2);
585 return (bit_width + 31) / 32;
586 }
587 case spv::OpTypeInt: {
588 auto bit_width = insn.word(2);
589 return (bit_width + 31) / 32;
590 }
591 case spv::OpConstant:
592 return GetComponentsConsumedByType(src, insn.word(1), false);
593 default:
594 return 0;
595 }
596}
597
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600598static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700599 switch (format) {
600 case VK_FORMAT_R64G64B64A64_SFLOAT:
601 case VK_FORMAT_R64G64B64A64_SINT:
602 case VK_FORMAT_R64G64B64A64_UINT:
603 case VK_FORMAT_R64G64B64_SFLOAT:
604 case VK_FORMAT_R64G64B64_SINT:
605 case VK_FORMAT_R64G64B64_UINT:
606 return 2;
607 default:
608 return 1;
609 }
610}
611
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600612static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700613 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
614 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
615 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
616 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700617 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
618 return FORMAT_TYPE_FLOAT;
619}
620
621// 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 -0700622// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600623static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700624 auto insn = src->get_def(type);
625 assert(insn != src->end());
626
627 switch (insn.opcode()) {
628 case spv::OpTypeInt:
629 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
630 case spv::OpTypeFloat:
631 return FORMAT_TYPE_FLOAT;
632 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700633 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700634 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700635 case spv::OpTypeRuntimeArray:
636 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600637 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700638 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600639 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700640
641 default:
642 return 0;
643 }
644}
645
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600646static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700647 uint32_t bit_pos = uint32_t(u_ffs(stage));
648 return bit_pos - 1;
649}
650
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600651static 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 -0700652 while (true) {
653 if (def.opcode() == spv::OpTypePointer) {
654 def = src->get_def(def.word(3));
655 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
656 def = src->get_def(def.word(2));
657 is_array_of_verts = false;
658 } else if (def.opcode() == spv::OpTypeStruct) {
659 return def;
660 } else {
661 return src->end();
662 }
663 }
664}
665
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600666static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800667 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
668 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700669 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600670 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800671 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700672 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700673 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700674 }
675
676 std::unordered_map<unsigned, unsigned> member_components;
677 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700678 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700679
680 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800681 for (auto insn : src->member_decoration_inst) {
682 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700683 unsigned member_index = insn.word(2);
684
685 if (insn.word(3) == spv::DecorationComponent) {
686 unsigned component = insn.word(4);
687 member_components[member_index] = component;
688 }
689
690 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
691 member_relaxed_precision[member_index] = 1;
692 }
Chris Forbesa313d772017-06-13 13:59:41 -0700693
694 if (insn.word(3) == spv::DecorationPatch) {
695 member_patch[member_index] = 1;
696 }
Chris Forbes47567b72017-06-09 12:09:45 -0700697 }
698 }
699
Chris Forbesa313d772017-06-13 13:59:41 -0700700 // TODO: correctly handle location assignment from outside
701
Chris Forbes47567b72017-06-09 12:09:45 -0700702 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800703 for (auto insn : src->member_decoration_inst) {
704 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700705 unsigned member_index = insn.word(2);
706 unsigned member_type_id = type.word(2 + member_index);
707
708 if (insn.word(3) == spv::DecorationLocation) {
709 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600710 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700711 auto component_it = member_components.find(member_index);
712 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
713 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700714 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700715
716 for (unsigned int offset = 0; offset < num_locations; offset++) {
717 interface_var v = {};
718 v.id = id;
719 // TODO: member index in interface_var too?
720 v.type_id = member_type_id;
721 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700722 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700723 v.is_block_member = true;
724 v.is_relaxed_precision = is_relaxed_precision;
725 (*out)[std::make_pair(location + offset, component)] = v;
726 }
727 }
728 }
729 }
Chris Forbesa313d772017-06-13 13:59:41 -0700730
731 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700732}
733
Ari Suonpaa696b3432019-03-11 14:02:57 +0200734static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800735 assert(entrypoint.opcode() == spv::OpEntryPoint);
736
Ari Suonpaa696b3432019-03-11 14:02:57 +0200737 std::vector<uint32_t> interfaces;
738 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
739 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
740 uint32_t word = 3;
741 while (entrypoint.word(word) & 0xff000000u) {
742 ++word;
743 }
744 ++word;
745
746 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
747
748 return interfaces;
749}
750
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600751static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600752 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700753 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
754
Chris Forbes47567b72017-06-09 12:09:45 -0700755 std::map<location_t, interface_var> out;
756
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800757 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
758 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700759 assert(insn != src->end());
760 assert(insn.opcode() == spv::OpVariable);
761
762 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800763 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700764 unsigned id = insn.word(2);
765 unsigned type = insn.word(1);
766
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800767 int location = d.location;
768 int builtin = d.builtin;
769 unsigned component = d.component;
770 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
771 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700772
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700773 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700774 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700775 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700776 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
777 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600778 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700779 for (unsigned int offset = 0; offset < num_locations; offset++) {
780 interface_var v = {};
781 v.id = id;
782 v.type_id = type;
783 v.offset = offset;
784 v.is_patch = is_patch;
785 v.is_relaxed_precision = is_relaxed_precision;
786 out[std::make_pair(location + offset, component)] = v;
787 }
Chris Forbes47567b72017-06-09 12:09:45 -0700788 }
789 }
790 }
791
792 return out;
793}
794
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600795static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200796 uint32_t storageClass) {
797 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700798 std::vector<uint32_t> builtin_struct_members;
799 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200800
sfricke-samsung94d71a52021-02-26 05:25:43 -0800801 for (auto insn : src->member_decoration_inst) {
802 if (insn.word(3) == spv::DecorationBuiltIn) {
803 builtin_struct_members.push_back(insn.word(1));
804 }
805 }
806 for (auto insn : src->decoration_inst) {
807 switch (insn.word(2)) {
808 case spv::DecorationBlock: {
809 uint32_t block_id = insn.word(1);
810 for (auto built_in_block_id : builtin_struct_members) {
811 // Check if one of the members of the block are built-in -> the block is built-in
812 if (block_id == built_in_block_id) {
813 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200814 break;
815 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200816 }
817 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800818 }
819 case spv::DecorationBuiltIn:
820 builtin_decorations.push_back(insn.word(1));
821 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200822 default:
823 break;
824 }
825 }
826
827 // Find all interface variables belonging to the entrypoint and matching the storage class
828 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
829 auto def = src->get_def(id);
830 assert(def != src->end());
831 assert(def.opcode() == spv::OpVariable);
832
833 if (def.word(3) == storageClass) variables.push_back(def.word(1));
834 }
835
836 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700837 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200838 for (auto &var : variables) {
839 auto def = src->get_def(src->get_def(var).word(3));
840
841 // It could be an array of IO blocks. The element type should be the struct defining the block contents
842 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
843
844 // Now find all members belonging to the struct defining the IO block
845 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700846 for (auto built_in_id : builtin_decorations) {
847 if (built_in_id == def.word(1)) {
848 for (int i = 2; i < static_cast<int>(def.len()); i++) {
849 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
850 }
851 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800852 for (auto insn : src->member_decoration_inst) {
853 if (insn.word(1) == built_in_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700854 auto struct_index = insn.word(2);
855 assert(struct_index < builtin_block_members.size());
856 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200857 }
858 }
859 }
860 }
861 }
862 }
863
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700864 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200865}
866
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600867static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600868 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700869 std::vector<std::pair<uint32_t, interface_var>> out;
870
sfricke-samsung94d71a52021-02-26 05:25:43 -0800871 for (auto insn : src->decoration_inst) {
872 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
873 auto attachment_index = insn.word(3);
874 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700875
sfricke-samsung94d71a52021-02-26 05:25:43 -0800876 if (accessible_ids.count(id)) {
877 auto def = src->get_def(id);
878 assert(def != src->end());
879 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
880 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
881 for (unsigned int offset = 0; offset < num_locations; offset++) {
882 interface_var v = {};
883 v.id = id;
884 v.type_id = def.word(1);
885 v.offset = offset;
886 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700887 }
888 }
889 }
890 }
891 }
892
893 return out;
894}
895
locke-lunarg25b6c352020-08-06 17:44:18 -0600896static bool AtomicOperation(uint32_t opcode) {
897 switch (opcode) {
898 case spv::OpAtomicLoad:
899 case spv::OpAtomicStore:
900 case spv::OpAtomicExchange:
901 case spv::OpAtomicCompareExchange:
902 case spv::OpAtomicCompareExchangeWeak:
903 case spv::OpAtomicIIncrement:
904 case spv::OpAtomicIDecrement:
905 case spv::OpAtomicIAdd:
906 case spv::OpAtomicISub:
907 case spv::OpAtomicSMin:
908 case spv::OpAtomicUMin:
909 case spv::OpAtomicSMax:
910 case spv::OpAtomicUMax:
911 case spv::OpAtomicAnd:
912 case spv::OpAtomicOr:
913 case spv::OpAtomicXor:
914 case spv::OpAtomicFAddEXT:
915 return true;
916 default:
917 return false;
918 }
919 return false;
920}
921
sfricke-samsung0065ce02020-12-03 22:46:37 -0800922// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
923// covered with VUID 01090
924static bool GroupOperation(uint32_t opcode) {
925 switch (opcode) {
926 case spv::OpGroupNonUniformElect:
927 case spv::OpGroupNonUniformAll:
928 case spv::OpGroupNonUniformAny:
929 case spv::OpGroupNonUniformAllEqual:
930 case spv::OpGroupNonUniformBroadcast:
931 case spv::OpGroupNonUniformBroadcastFirst:
932 case spv::OpGroupNonUniformBallot:
933 case spv::OpGroupNonUniformInverseBallot:
934 case spv::OpGroupNonUniformBallotBitExtract:
935 case spv::OpGroupNonUniformBallotBitCount:
936 case spv::OpGroupNonUniformBallotFindLSB:
937 case spv::OpGroupNonUniformBallotFindMSB:
938 case spv::OpGroupNonUniformShuffle:
939 case spv::OpGroupNonUniformShuffleXor:
940 case spv::OpGroupNonUniformShuffleUp:
941 case spv::OpGroupNonUniformShuffleDown:
942 case spv::OpGroupNonUniformIAdd:
943 case spv::OpGroupNonUniformFAdd:
944 case spv::OpGroupNonUniformIMul:
945 case spv::OpGroupNonUniformFMul:
946 case spv::OpGroupNonUniformSMin:
947 case spv::OpGroupNonUniformUMin:
948 case spv::OpGroupNonUniformFMin:
949 case spv::OpGroupNonUniformSMax:
950 case spv::OpGroupNonUniformUMax:
951 case spv::OpGroupNonUniformFMax:
952 case spv::OpGroupNonUniformBitwiseAnd:
953 case spv::OpGroupNonUniformBitwiseOr:
954 case spv::OpGroupNonUniformBitwiseXor:
955 case spv::OpGroupNonUniformLogicalAnd:
956 case spv::OpGroupNonUniformLogicalOr:
957 case spv::OpGroupNonUniformLogicalXor:
958 case spv::OpGroupNonUniformQuadBroadcast:
959 case spv::OpGroupNonUniformQuadSwap:
960 case spv::OpGroupNonUniformPartitionNV:
961 return true;
962 default:
963 return false;
964 }
965 return false;
966}
967
locke-lunarg12d20992020-09-21 12:46:49 -0600968bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
969 const std::unordered_map<unsigned, unsigned> &load_members,
970 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
971 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600972 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600973 auto load_it = load_members.find(load_id);
974 if (load_it == load_members.end()) {
975 continue;
976 }
977 if (load_it->second == object_id) {
978 return true;
979 }
980
981 auto accesschain_it = accesschain_members.find(load_it->second);
982 if (accesschain_it == accesschain_members.end()) {
983 continue;
984 }
985 if (accesschain_it->second.first == object_id) {
986 return true;
987 }
988 }
989 return false;
990}
991
locke-lunargae2a43c2020-09-22 17:21:57 -0600992bool CheckImageOperandsBiasOffset(uint32_t type) {
993 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
994 spv::ImageOperandsConstOffsetsMask)
995 ? true
996 : false;
997}
998
locke-lunargd3da0422020-09-23 01:02:11 -0600999struct shader_module_used_operators {
1000 bool updated;
1001 std::vector<unsigned> imagwrite_members;
1002 std::vector<unsigned> atomic_members;
1003 std::vector<unsigned> store_members;
1004 std::vector<unsigned> atomic_store_members;
1005 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1006 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001007 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
locke-lunargd3da0422020-09-23 01:02:11 -06001008 std::unordered_map<unsigned, unsigned> load_members;
1009 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1010 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
1011
1012 shader_module_used_operators() : updated(false) {}
1013
1014 void update(SHADER_MODULE_STATE const *module) {
1015 if (updated) return;
1016 updated = true;
1017
1018 for (auto insn : *module) {
1019 switch (insn.opcode()) {
1020 case spv::OpImageSampleImplicitLod:
1021 case spv::OpImageSampleProjImplicitLod:
1022 case spv::OpImageSampleProjExplicitLod:
1023 case spv::OpImageSparseSampleImplicitLod:
1024 case spv::OpImageSparseSampleProjImplicitLod:
1025 case spv::OpImageSparseSampleProjExplicitLod: {
1026 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1027 // ImageOperands in index: 5
1028 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1029 sampler_bias_offset_members.emplace_back(insn.word(3));
1030 }
1031 break;
1032 }
1033 case spv::OpImageSampleDrefImplicitLod:
1034 case spv::OpImageSampleDrefExplicitLod:
1035 case spv::OpImageSampleProjDrefImplicitLod:
1036 case spv::OpImageSampleProjDrefExplicitLod:
1037 case spv::OpImageSparseSampleDrefImplicitLod:
1038 case spv::OpImageSparseSampleDrefExplicitLod:
1039 case spv::OpImageSparseSampleProjDrefImplicitLod:
1040 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1041 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1042 // ImageOperands in index: 6
1043 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1044 sampler_bias_offset_members.emplace_back(insn.word(3));
1045 }
1046 break;
1047 }
1048 case spv::OpImageSampleExplicitLod:
1049 case spv::OpImageSparseSampleExplicitLod: {
1050 // ImageOperands in index: 5
1051 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1052 sampler_bias_offset_members.emplace_back(insn.word(3));
1053 }
1054 break;
1055 }
1056 case spv::OpStore: {
1057 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1058 break;
1059 }
1060 case spv::OpImageWrite: {
1061 imagwrite_members.emplace_back(insn.word(1)); // Load id
1062 break;
1063 }
1064 case spv::OpSampledImage: {
1065 // 3: image load id, 4: sampler load id
1066 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1067 break;
1068 }
1069 case spv::OpLoad: {
1070 // 2: Load id, 3: object id or AccessChain id
1071 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1072 break;
1073 }
1074 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001075 if (insn.len() == 4) {
1076 // If it is for struct, the length is only 4.
1077 // 2: AccessChain id, 3: object id
1078 accesschain_members.insert(std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0)));
1079 } else {
1080 // 2: AccessChain id, 3: object id, 4: object id of array index
1081 accesschain_members.insert(
1082 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1083 }
locke-lunargd3da0422020-09-23 01:02:11 -06001084 break;
1085 }
1086 case spv::OpImageTexelPointer: {
1087 // 2: ImageTexelPointer id, 3: object id
1088 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1089 break;
1090 }
1091 default: {
1092 if (AtomicOperation(insn.opcode())) {
1093 if (insn.opcode() == spv::OpAtomicStore) {
1094 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1095 } else {
1096 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1097 }
1098 }
1099 break;
1100 }
1101 }
1102 }
1103 }
1104};
1105
sfricke-samsung691299b2021-01-01 20:48:48 -08001106// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1107// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001108static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001109 bool is_check_writable, interface_var &out_interface_var,
1110 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001111 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001112 unsigned int id = id_it.word(2);
1113
Chris Forbes8af24522018-03-07 11:37:45 -08001114 auto type = module->get_def(type_id);
1115
1116 // 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 -06001117 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1118 type.opcode() == spv::OpTypeSampledImage) {
1119 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1120 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001121 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001122 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001123 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001124 }
1125 }
Chris Forbes8af24522018-03-07 11:37:45 -08001126 switch (type.opcode()) {
1127 case spv::OpTypeImage: {
1128 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001129 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001130 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001131
locke-lunargd3da0422020-09-23 01:02:11 -06001132 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1133 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001134 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001135 }
1136 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1137 used_operators.accesschain_members)) {
1138 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001139 }
locke-lunargd3da0422020-09-23 01:02:11 -06001140 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1141 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001142 out_interface_var.is_sampler_bias_offset = true;
1143 }
locke-lunargd3da0422020-09-23 01:02:11 -06001144 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1145 used_operators.accesschain_members) ||
1146 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1147 used_operators.accesschain_members)) {
1148 out_interface_var.is_atomic_operation = true;
1149 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001150
locke-lunargd3da0422020-09-23 01:02:11 -06001151 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001152 // Find if image id match.
1153 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001154 auto load_it = used_operators.load_members.find(itp_id.first);
1155 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001156 continue;
1157 } else {
1158 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001159 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1160 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001161 continue;
1162 } else {
1163 if (accesschain_it->second.first != id) {
1164 continue;
1165 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001166
1167 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1168 if (const_itr == module->end()) {
1169 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001170 break;
1171 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001172 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001173 }
1174 }
1175 }
1176 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001177 load_it = used_operators.load_members.find(itp_id.second);
1178 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001179 continue;
1180 } else {
1181 uint32_t sampler_id = load_it->second;
1182 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001183 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001184
locke-lunargd3da0422020-09-23 01:02:11 -06001185 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001186 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1187 if (const_itr == module->end()) {
1188 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001189 break;
1190 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001191 sampler_id = const_itr.offset();
1192 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001193 }
1194 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001195 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1196 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1197 }
1198 out_interface_var.samplers_used_by_image[image_index].emplace(
1199 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001200 }
1201 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001202 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001203 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001204 }
1205
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001206 case spv::OpTypeStruct: {
1207 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001208 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001209 for (auto insn : module->member_decoration_inst) {
1210 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001211 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001212 }
1213 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001214
1215 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1216 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001217 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001218 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001219
locke-lunargd3da0422020-09-23 01:02:11 -06001220 for (auto oid : used_operators.store_members) {
1221 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001222 out_interface_var.is_writable = true;
1223 return;
1224 }
locke-lunargd3da0422020-09-23 01:02:11 -06001225 auto accesschain_it = used_operators.accesschain_members.find(oid);
1226 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001227 continue;
1228 }
locke-lunargd3da0422020-09-23 01:02:11 -06001229 if (accesschain_it->second.first == id) {
1230 out_interface_var.is_writable = true;
1231 return;
1232 }
1233 }
1234 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1235 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001236 out_interface_var.is_writable = true;
1237 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001238 }
1239 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001240 }
Chris Forbes8af24522018-03-07 11:37:45 -08001241 }
Chris Forbes8af24522018-03-07 11:37:45 -08001242}
1243
locke-lunargd9a069d2019-09-17 01:50:19 -06001244std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001245 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1246 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001247 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001248 shader_module_used_operators operators;
1249
Chris Forbes47567b72017-06-09 12:09:45 -07001250 for (auto id : accessible_ids) {
1251 auto insn = src->get_def(id);
1252 assert(insn != src->end());
1253
1254 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001255 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1256 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001257 auto d = src->get_decorations(insn.word(2));
1258 unsigned set = d.descriptor_set;
1259 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001260
1261 interface_var v = {};
1262 v.id = insn.word(2);
1263 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001264
locke-lunarg25b6c352020-08-06 17:44:18 -06001265 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001266 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001267 if (v.is_writable) *has_writable_descriptor = true;
1268 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001269 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001270 }
1271 }
1272
1273 return out;
1274}
1275
locke-lunargde3f0fa2020-09-10 11:55:31 -06001276void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1277 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1278 const auto struct_it = GetStructType(&src, it, false);
1279 assert(struct_it != src.end());
1280 data.size = 0;
1281
1282 shader_struct_member data1;
1283 uint32_t i = 2;
1284 uint32_t local_offset = 0;
1285 std::vector<uint32_t> offsets;
1286 offsets.resize(struct_it.len() - i);
1287
1288 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1289 for (const auto offset : memberDecorate_offsets) {
1290 const auto member_decorate = src.at(offset);
1291 if (member_decorate.word(1) != struct_it.word(1)) {
1292 continue;
1293 }
1294
1295 offsets[member_decorate.word(2)] = member_decorate.word(4);
1296 }
1297
1298 for (const auto offset : offsets) {
1299 local_offset = offset;
1300 data1 = {};
1301 data1.root = data.root;
1302 data1.offset = local_offset;
1303 auto def_member = src.get_def(struct_it.word(i));
1304
1305 // Array could be multi-dimensional
1306 while (def_member.opcode() == spv::OpTypeArray) {
1307 const auto len_id = def_member.word(3);
1308 const auto def_len = src.get_def(len_id);
1309 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1310 def_member = src.get_def(def_member.word(2));
1311 }
1312
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001313 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001314 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001315 } else if (def_member.opcode() == spv::OpTypePointer) {
1316 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1317 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1318 // that "points to something."
1319 data1.size = 8;
1320 } else {
1321 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1322 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1323 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001324 } else {
1325 if (def_member.opcode() == spv::OpTypeMatrix) {
1326 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1327 def_member = src.get_def(def_member.word(2));
1328 }
1329
1330 if (def_member.opcode() == spv::OpTypeVector) {
1331 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1332 def_member = src.get_def(def_member.word(2));
1333 }
1334
1335 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1336 data1.size = (def_member.word(2) / 8);
1337 }
1338 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1339 if (array_length_hierarchy_szie > 0) {
1340 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1341
1342 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1343 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1344 }
1345 }
1346 data.struct_members.emplace_back(data1);
1347 ++i;
1348 }
1349 uint32_t total_array_length = 1;
1350 for (const auto length : data1.array_length_hierarchy) {
1351 total_array_length *= length;
1352 }
1353 data.size = local_offset + data1.size * total_array_length;
1354}
1355
1356uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1357 int array_indices_size = static_cast<int>(array_indices.size());
1358 if (array_indices_size) {
1359 uint32_t array_index = 0;
1360 uint32_t i = 0;
1361 for (const auto index : array_indices) {
1362 array_index += (data.array_block_size[i] * index);
1363 ++i;
1364 }
1365 offset += (array_index * data.size);
1366 }
1367 return offset;
1368}
1369
1370void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1371 int array_indices_size = static_cast<int>(array_indices.size());
1372 uint32_t block_memory_size = data.size;
1373 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1374 block_memory_size *= data.array_length_hierarchy[i];
1375 }
1376
1377 offset = UpdateOffset(offset, array_indices, data);
1378
1379 uint32_t end = offset + block_memory_size;
1380 auto used_bytes = data.GetUsedbytes();
1381 if (used_bytes->size() < end) {
1382 used_bytes->resize(end, 0);
1383 }
1384 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1385}
1386
1387void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1388 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1389 if (access_chain_word_index < access_chain_it.len()) {
1390 if (data.array_length_hierarchy.size() > array_indices.size()) {
1391 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1392 ++access_chain_word_index;
1393
1394 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1395 array_indices.emplace_back(def_it.word(3));
1396 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1397 } else {
1398 // If it is a variable, set the all array is used.
1399 if (access_chain_word_index < access_chain_it.len()) {
1400 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1401 for (uint32_t i = 0; i < array_length; ++i) {
1402 auto array_indices2 = array_indices;
1403 array_indices2.emplace_back(i);
1404 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1405 }
1406 } else {
1407 SetUsedBytes(offset, array_indices, data);
1408 }
1409 }
1410 } else {
1411 offset = UpdateOffset(offset, array_indices, data);
1412 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1413 }
1414 } else {
1415 SetUsedBytes(offset, array_indices, data);
1416 }
1417}
1418
1419void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1420 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1421 std::vector<uint32_t> array_indices_emptry;
1422
1423 if (access_chain_word_index < access_chain_it.len()) {
1424 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1425 ++access_chain_word_index;
1426
1427 auto data1 = data.struct_members[strcut_member_index];
1428 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1429 }
1430}
1431
1432void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1433 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1434 for (const auto &func_set : function_set_list) {
1435 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1436 for (auto it = range.first; it != range.second; ++it) {
1437 auto access_chain = src.at(it->second);
1438 if (access_chain.word(3) == variable_id) {
1439 RunUsedStruct(src, 0, 4, access_chain, data);
1440 }
1441 }
1442 }
1443}
1444
1445void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1446 for (auto &entrypoint : src.entry_points) {
1447 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1448 for (auto it = range.first; it != range.second; ++it) {
1449 const auto def_insn = src.at(it->second);
1450
1451 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1452 spirv_inst_iter type = src.get_def(def_insn.word(1));
1453 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1454 std::vector<uint32_t> offsets;
1455
1456 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1457 auto member_decorate = src.at(it2->second);
1458 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1459 offsets.emplace_back(member_decorate.offset());
1460 }
1461 }
1462 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1463 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1464 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1465 entrypoint.second.push_constant_used_in_shader);
1466 }
1467 }
1468 }
1469}
1470
locke-lunarg96dc9632020-06-10 17:22:18 -06001471std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1472 const VkPipelineShaderStageCreateInfo &stage_info) {
1473 std::unordered_set<uint32_t> location_list;
1474 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1475 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1476 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1477 std::unordered_set<unsigned> store_members;
1478 std::unordered_map<unsigned, unsigned> accesschain_members;
1479
1480 for (auto insn : module) {
1481 switch (insn.opcode()) {
1482 case spv::OpStore:
1483 case spv::OpAtomicStore: {
1484 store_members.insert(insn.word(1)); // object id or AccessChain id
1485 break;
1486 }
1487 case spv::OpAccessChain: {
1488 // 2: AccessChain id, 3: object id
1489 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1490 break;
1491 }
1492 default:
1493 break;
1494 }
1495 }
1496 if (store_members.empty()) {
1497 return location_list;
1498 }
1499 for (auto output : outputs) {
1500 auto store_it = store_members.find(output.second.id);
1501 if (store_it != store_members.end()) {
1502 location_list.insert(output.first.first);
1503 store_members.erase(store_it);
1504 continue;
1505 }
1506 store_it = store_members.begin();
1507 while (store_it != store_members.end()) {
1508 auto accesschain_it = accesschain_members.find(*store_it);
1509 if (accesschain_it == accesschain_members.end()) {
1510 ++store_it;
1511 continue;
1512 }
1513 if (accesschain_it->second == output.second.id) {
1514 location_list.insert(output.first.first);
1515 store_members.erase(store_it);
1516 accesschain_members.erase(accesschain_it);
1517 break;
1518 }
1519 ++store_it;
1520 }
1521 }
1522 return location_list;
1523}
1524
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001525bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001526 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1527 // be specified only once.
1528 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1529 bool skip = false;
1530
1531 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1532 auto desc = &vi->pVertexBindingDescriptions[i];
1533 auto &binding = bindings[desc->binding];
1534 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001535 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001536 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1537 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001538 } else {
1539 binding = desc;
1540 }
1541 }
1542
1543 return skip;
1544}
1545
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001546bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1547 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001548 bool skip = false;
1549
Petr Kraus25810d02019-08-27 17:41:15 +02001550 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001551
1552 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001553 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001554 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001555 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1556 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1557 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001558 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1559 }
1560 }
1561 }
1562
Petr Kraus25810d02019-08-27 17:41:15 +02001563 struct AttribInputPair {
1564 const VkVertexInputAttributeDescription *attrib = nullptr;
1565 const interface_var *input = nullptr;
1566 };
1567 std::map<uint32_t, AttribInputPair> location_map;
1568 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1569 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001570
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001571 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001572 const auto location = location_it.first;
1573 const auto attrib = location_it.second.attrib;
1574 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001575
Petr Kraus25810d02019-08-27 17:41:15 +02001576 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001577 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1578 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001579 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001580 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1581 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001582 } else if (attrib && input) {
1583 const auto attrib_type = GetFormatType(attrib->format);
1584 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001585
1586 // Type checking
1587 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001588 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1589 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1590 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001591 }
Petr Kraus25810d02019-08-27 17:41:15 +02001592 } else { // !attrib && !input
1593 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001594 }
1595 }
1596
1597 return skip;
1598}
1599
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001600bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1601 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001602 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001603
Petr Kraus25810d02019-08-27 17:41:15 +02001604 const auto rpci = pipeline->rp_state->createInfo.ptr();
1605
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001606 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001607 const VkAttachmentReference2 *reference = nullptr;
1608 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001609 const interface_var *output = nullptr;
1610 };
1611 std::map<uint32_t, Attachment> location_map;
1612
Petr Kraus25810d02019-08-27 17:41:15 +02001613 const auto subpass = rpci->pSubpasses[subpass_index];
1614 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001615 auto const &reference = subpass.pColorAttachments[i];
1616 location_map[i].reference = &reference;
1617 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1618 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1619 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001620 }
1621 }
1622
Chris Forbes47567b72017-06-09 12:09:45 -07001623 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1624
Petr Kraus25810d02019-08-27 17:41:15 +02001625 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001626 for (const auto &output_it : outputs) {
1627 auto const location = output_it.first.first;
1628 location_map[location].output = &output_it.second;
1629 }
Chris Forbes47567b72017-06-09 12:09:45 -07001630
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001631 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1632 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001633
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001634 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001635 const auto reference = location_it.second.reference;
1636 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1637 continue;
1638 }
1639
Petr Kraus25810d02019-08-27 17:41:15 +02001640 const auto location = location_it.first;
1641 const auto attachment = location_it.second.attachment;
1642 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001643 if (attachment && !output) {
1644 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001645 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1646 "Attachment %" PRIu32
1647 " not written by fragment shader; undefined values will be written to attachment",
1648 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001649 }
1650 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001651 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001652 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1653 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001654 }
Petr Kraus25810d02019-08-27 17:41:15 +02001655 } else if (attachment && output) {
1656 const auto attachment_type = GetFormatType(attachment->format);
1657 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001658
1659 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001660 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001661 skip |=
1662 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1663 "Attachment %" PRIu32
1664 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1665 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001666 }
Petr Kraus25810d02019-08-27 17:41:15 +02001667 } else { // !attachment && !output
1668 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001669 }
1670 }
1671
Petr Kraus25810d02019-08-27 17:41:15 +02001672 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001673 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1674 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1675 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001676 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1677 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001678 }
1679
Chris Forbes47567b72017-06-09 12:09:45 -07001680 return skip;
1681}
1682
Tobias Hector6663c9b2020-11-05 10:18:02 +00001683// 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 -06001684// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001685static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001686 auto type = builtin_instr.opcode();
1687 uint32_t target_id = builtin_instr.word(1);
1688 bool init_complete = false;
1689
1690 if (type == spv::OpMemberDecorate) {
1691 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1692 auto insn = entrypoint;
1693 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1694 switch (insn.opcode()) {
1695 case spv::OpTypePointer:
1696 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1697 target_id = insn.word(1);
1698 }
1699 break;
1700 case spv::OpVariable:
1701 if (insn.word(1) == target_id) {
1702 target_id = insn.word(2);
1703 init_complete = true;
1704 }
1705 break;
1706 }
1707 insn++;
1708 }
1709 }
1710
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001711 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1712
1713 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001714 std::unordered_set<uint32_t> worklist;
1715 worklist.insert(entrypoint.word(2));
1716
1717 // Follow instructions in call graph looking for writes to target
1718 while (!worklist.empty() && !found_write) {
1719 auto id_iter = worklist.begin();
1720 auto id = *id_iter;
1721 worklist.erase(id_iter);
1722
1723 auto insn = src->get_def(id);
1724 if (insn == src->end()) {
1725 continue;
1726 }
1727
1728 if (insn.opcode() == spv::OpFunction) {
1729 // Scan body of function looking for other function calls or items in our ID chain
1730 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1731 switch (insn.opcode()) {
1732 case spv::OpAccessChain:
1733 if (insn.word(3) == target_id) {
1734 if (type == spv::OpMemberDecorate) {
1735 auto value = GetConstantValue(src, insn.word(4));
1736 if (value == builtin_instr.word(2)) {
1737 target_id = insn.word(2);
1738 }
1739 } else {
1740 target_id = insn.word(2);
1741 }
1742 }
1743 break;
1744 case spv::OpStore:
1745 if (insn.word(1) == target_id) {
1746 found_write = true;
1747 }
1748 break;
1749 case spv::OpFunctionCall:
1750 worklist.insert(insn.word(3));
1751 break;
1752 }
1753 }
1754 }
1755 }
1756 return found_write;
1757}
1758
Chris Forbes47567b72017-06-09 12:09:45 -07001759// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1760// important for identifying the set of shader resources actually used by an entrypoint, for example.
1761// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1762// - NOT the shader input/output interfaces.
1763//
1764// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1765// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001766std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001767 std::unordered_set<uint32_t> ids;
1768 std::unordered_set<uint32_t> worklist;
1769 worklist.insert(entrypoint.word(2));
1770
1771 while (!worklist.empty()) {
1772 auto id_iter = worklist.begin();
1773 auto id = *id_iter;
1774 worklist.erase(id_iter);
1775
1776 auto insn = src->get_def(id);
1777 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001778 // 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 -07001779 // that we may not care about.
1780 continue;
1781 }
1782
1783 // Try to add to the output set
1784 if (!ids.insert(id).second) {
1785 continue; // If we already saw this id, we don't want to walk it again.
1786 }
1787
1788 switch (insn.opcode()) {
1789 case spv::OpFunction:
1790 // Scan whole body of the function, enlisting anything interesting
1791 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1792 switch (insn.opcode()) {
1793 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001794 worklist.insert(insn.word(3)); // ptr
1795 break;
1796 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001797 worklist.insert(insn.word(1)); // ptr
1798 break;
1799 case spv::OpAccessChain:
1800 case spv::OpInBoundsAccessChain:
1801 worklist.insert(insn.word(3)); // base ptr
1802 break;
1803 case spv::OpSampledImage:
1804 case spv::OpImageSampleImplicitLod:
1805 case spv::OpImageSampleExplicitLod:
1806 case spv::OpImageSampleDrefImplicitLod:
1807 case spv::OpImageSampleDrefExplicitLod:
1808 case spv::OpImageSampleProjImplicitLod:
1809 case spv::OpImageSampleProjExplicitLod:
1810 case spv::OpImageSampleProjDrefImplicitLod:
1811 case spv::OpImageSampleProjDrefExplicitLod:
1812 case spv::OpImageFetch:
1813 case spv::OpImageGather:
1814 case spv::OpImageDrefGather:
1815 case spv::OpImageRead:
1816 case spv::OpImage:
1817 case spv::OpImageQueryFormat:
1818 case spv::OpImageQueryOrder:
1819 case spv::OpImageQuerySizeLod:
1820 case spv::OpImageQuerySize:
1821 case spv::OpImageQueryLod:
1822 case spv::OpImageQueryLevels:
1823 case spv::OpImageQuerySamples:
1824 case spv::OpImageSparseSampleImplicitLod:
1825 case spv::OpImageSparseSampleExplicitLod:
1826 case spv::OpImageSparseSampleDrefImplicitLod:
1827 case spv::OpImageSparseSampleDrefExplicitLod:
1828 case spv::OpImageSparseSampleProjImplicitLod:
1829 case spv::OpImageSparseSampleProjExplicitLod:
1830 case spv::OpImageSparseSampleProjDrefImplicitLod:
1831 case spv::OpImageSparseSampleProjDrefExplicitLod:
1832 case spv::OpImageSparseFetch:
1833 case spv::OpImageSparseGather:
1834 case spv::OpImageSparseDrefGather:
1835 case spv::OpImageTexelPointer:
1836 worklist.insert(insn.word(3)); // Image or sampled image
1837 break;
1838 case spv::OpImageWrite:
1839 worklist.insert(insn.word(1)); // Image -- different operand order to above
1840 break;
1841 case spv::OpFunctionCall:
1842 for (uint32_t i = 3; i < insn.len(); i++) {
1843 worklist.insert(insn.word(i)); // fn itself, and all args
1844 }
1845 break;
1846
1847 case spv::OpExtInst:
1848 for (uint32_t i = 5; i < insn.len(); i++) {
1849 worklist.insert(insn.word(i)); // Operands to ext inst
1850 }
1851 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001852
1853 default: {
1854 if (AtomicOperation(insn.opcode())) {
1855 if (insn.opcode() == spv::OpAtomicStore) {
1856 worklist.insert(insn.word(1)); // ptr
1857 } else {
1858 worklist.insert(insn.word(3)); // ptr
1859 }
1860 }
1861 break;
1862 }
Chris Forbes47567b72017-06-09 12:09:45 -07001863 }
1864 }
1865 break;
1866 }
1867 }
1868
1869 return ids;
1870}
1871
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001872PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1873 const shader_struct_member &push_constant_used_in_shader,
1874 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001875 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001876 const auto used_bytes_size = used_bytes->size();
1877 if (used_bytes_size == 0) return PC_Byte_Updated;
1878
1879 const auto push_constant_data_update_size = push_constant_data_update.size();
1880 const auto *data = push_constant_data_update.data();
1881 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1882 if (used_bytes_size <= push_constant_data_update_size) {
1883 return PC_Byte_Updated;
1884 }
1885 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1886
1887 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1888 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1889 return PC_Byte_Updated;
1890 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001891 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001892
locke-lunargde3f0fa2020-09-10 11:55:31 -06001893 uint32_t i = 0;
1894 for (const auto used : *used_bytes) {
1895 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001896 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001897 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001898 return PC_Byte_Not_Set;
1899 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001900 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001901 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001902 }
1903 }
1904 ++i;
1905 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001906 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001907}
1908
1909bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1910 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001911 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001912 // 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 -06001913 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1914 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1915 return skip;
1916 }
1917 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001918
locke-lunargde3f0fa2020-09-10 11:55:31 -06001919 bool found_stage = false;
1920 for (auto const &range : *push_constant_ranges) {
1921 if (range.stageFlags & pStage->stage) {
1922 found_stage = true;
1923 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001924 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001925 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001926 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001927 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001928 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001929 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001930 const auto ret =
1931 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001932
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001933 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001934 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1935 LogObjectList objlist(src->vk_shader_module);
1936 objlist.add(pipeline.pipeline_layout->layout);
1937 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1938 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1939 string_VkShaderStageFlags(pStage->stage).c_str(),
1940 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1941 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001942 }
1943 }
1944 }
1945
locke-lunargde3f0fa2020-09-10 11:55:31 -06001946 if (!found_stage) {
1947 LogObjectList objlist(src->vk_shader_module);
1948 objlist.add(pipeline.pipeline_layout->layout);
1949 skip |= LogError(
1950 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1951 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1952 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001953 }
Chris Forbes47567b72017-06-09 12:09:45 -07001954 return skip;
1955}
1956
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001957bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1958 VkShaderStageFlagBits stage) const {
1959 bool skip = false;
1960
1961 // Currently all builtin tested are only found in fragment shaders
1962 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1963 return skip;
1964 }
1965
1966 for (const auto id : accessible_ids) {
1967 auto insn = src->get_def(id);
1968 const decoration_set decorations = src->get_decorations(insn.word(2));
1969
1970 // Built-ins are obtained from OpVariable
1971 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1972 auto type_pointer = src->get_def(insn.word(1));
1973 assert(type_pointer.opcode() == spv::OpTypePointer);
1974
1975 auto type = src->get_def(type_pointer.word(3));
1976 if (type.opcode() == spv::OpTypeArray) {
1977 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1978
1979 switch (decorations.builtin) {
1980 case spv::BuiltInSampleMask:
1981 // Handles both the input and output sampleMask
1982 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1983 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1984 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1985 "maxSampleMaskWords of %u in %s.",
1986 length, phys_dev_props.limits.maxSampleMaskWords,
1987 report_data->FormatHandle(src->vk_shader_module).c_str());
1988 }
1989 break;
1990 }
1991 }
1992 }
1993 }
1994
1995 return skip;
1996}
1997
Chris Forbes47567b72017-06-09 12:09:45 -07001998// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001999bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002000 bool skip = false;
2001
2002 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2003
2004 if (spec) {
2005 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002006 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002007 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2008 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2009 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2010 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2011 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002012
2013 continue;
2014 }
Chris Forbes47567b72017-06-09 12:09:45 -07002015 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002016 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2017 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2018 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2019 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2020 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002021 }
2022 }
2023 }
2024
2025 return skip;
2026}
2027
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002028// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002029static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2030 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002031 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002032 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002033 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002034 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002035
2036 // 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 -05002037 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2038 if (type.opcode() == spv::OpTypeRuntimeArray) {
2039 descriptor_count = 0;
2040 type = module->get_def(type.word(2));
2041 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002042 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002043 type = module->get_def(type.word(2));
2044 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002045 if (type.word(2) == spv::StorageClassStorageBuffer) {
2046 is_storage_buffer = true;
2047 }
Chris Forbes47567b72017-06-09 12:09:45 -07002048 type = module->get_def(type.word(3));
2049 }
2050 }
2051
2052 switch (type.opcode()) {
2053 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002054 for (auto insn : module->decoration_inst) {
2055 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002056 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002057 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002058 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2059 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2060 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002061 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002062 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2063 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2064 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2065 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002066 }
Chris Forbes47567b72017-06-09 12:09:45 -07002067 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002068 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2069 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2070 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002071 }
2072 }
2073 }
2074
2075 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002076 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002077 }
2078
2079 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002080 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2081 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2082 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002083
Chris Forbes73c00bf2018-06-22 16:28:06 -07002084 case spv::OpTypeSampledImage: {
2085 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2086 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2087 auto image_type = module->get_def(type.word(2));
2088 auto dim = image_type.word(3);
2089 auto sampled = image_type.word(7);
2090 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002091 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2092 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002093 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002094 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002095 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2096 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002097
2098 case spv::OpTypeImage: {
2099 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2100 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2101 auto dim = type.word(3);
2102 auto sampled = type.word(7);
2103
2104 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002105 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2106 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002107 } else if (dim == spv::DimBuffer) {
2108 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002109 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2110 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002111 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002112 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2113 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002114 }
2115 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002116 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2117 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2118 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002119 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002120 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2121 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002122 }
2123 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002124 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002125 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2126 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002127 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002128
2129 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2130 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002131 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002132 }
2133}
2134
Jeff Bolze54ae892018-09-08 12:16:29 -05002135static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002136 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002137 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2138 if (ss.tellp()) ss << ", ";
2139 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002140 }
2141 return ss.str();
2142}
2143
sfricke-samsung0065ce02020-12-03 22:46:37 -08002144bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002145 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002146 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 -05002147 return true;
2148 }
2149 }
2150
2151 return false;
2152}
2153
sfricke-samsung0065ce02020-12-03 22:46:37 -08002154bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002155 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002156 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002157 return true;
2158 }
2159 }
2160
2161 return false;
2162}
2163
locke-lunarg63e4daf2020-08-17 17:53:25 -06002164bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2165 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002166 bool skip = false;
2167
locke-lunarg63e4daf2020-08-17 17:53:25 -06002168 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002169 switch (stage) {
2170 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002171 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2172 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2173 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2174 case VK_SHADER_STAGE_MISS_BIT_NV:
2175 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2176 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2177 case VK_SHADER_STAGE_TASK_BIT_NV:
2178 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002179 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002180 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002181 break;
2182 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002183 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2184 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002185 break;
2186 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002187 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2188 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002189 break;
2190 }
2191 }
2192
Chris Forbes47567b72017-06-09 12:09:45 -07002193 return skip;
2194}
2195
sfricke-samsung94167ca2021-02-26 04:14:59 -08002196bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2197 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002198 bool skip = false;
2199
sfricke-samsung94167ca2021-02-26 04:14:59 -08002200 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2201 if (GroupOperation(insn.opcode()) == true) {
2202 // Check the quad operations.
2203 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2204 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2205 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2206 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2207 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002208 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002209 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002210
sfricke-samsung94167ca2021-02-26 04:14:59 -08002211 uint32_t scope_type = spv::ScopeMax;
2212 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2213 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2214 scope_type = spv::ScopeSubgroup;
2215 } else {
2216 // "All <id> used for Scope <id> must be of an OpConstant"
2217 auto scope_id = module->get_def(insn.word(3));
2218 scope_type = scope_id.word(3);
2219 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002220
sfricke-samsung94167ca2021-02-26 04:14:59 -08002221 if (scope_type == spv::ScopeSubgroup) {
2222 // "Group operations with subgroup scope" must have stage support
2223 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2224 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002225 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002226 }
2227
2228 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2229 auto type = module->get_def(insn.word(1));
2230
2231 if (type.opcode() == spv::OpTypeVector) {
2232 // Get the element type
2233 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002234 }
2235
sfricke-samsung94167ca2021-02-26 04:14:59 -08002236 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002237 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2238 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002239
sfricke-samsung0065ce02020-12-03 22:46:37 -08002240 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2241 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2242 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2243 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2244 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002245 }
2246 }
2247 }
Jeff Bolzee743412019-06-20 22:24:32 -05002248 }
2249
2250 return skip;
2251}
2252
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002253bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002254 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002255 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2256 pStage->stage == VK_SHADER_STAGE_ALL) {
2257 return false;
2258 }
2259
2260 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002261 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002262
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002263 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002264 struct Variable {
2265 uint32_t baseTypePtrID;
2266 uint32_t ID;
2267 uint32_t storageClass;
2268 };
2269 std::vector<Variable> variables;
2270
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002271 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002272 bool is_iso_lines = false;
2273 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002274
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002275 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002276
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002277 for (auto insn : *src) {
2278 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002279 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002280 case spv::OpDecorate:
2281 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002282 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002283 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002284 break;
2285 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002286 default:
2287 break;
2288 }
2289 break;
2290 // Find all input and output variables
2291 case spv::OpVariable: {
2292 Variable var = {};
2293 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002294 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2295 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002296 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002297 var.baseTypePtrID = insn.word(1);
2298 var.ID = insn.word(2);
2299 variables.push_back(var);
2300 }
2301 break;
2302 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002303 case spv::OpExecutionMode:
2304 if (insn.word(1) == entrypoint.word(2)) {
2305 switch (insn.word(2)) {
2306 default:
2307 break;
2308 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002309 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002310 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002311 case spv::ExecutionModeIsolines:
2312 is_iso_lines = true;
2313 break;
2314 case spv::ExecutionModePointMode:
2315 is_point_mode = true;
2316 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002317 }
2318 }
2319 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002320 default:
2321 break;
2322 }
2323 }
2324
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002325 bool strip_output_array_level =
2326 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2327 bool strip_input_array_level =
2328 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2329 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2330
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002331 uint32_t num_comp_in = 0, num_comp_out = 0;
2332 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002333
2334 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2335 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2336
2337 // Find max component location used for input variables.
2338 for (auto &var : inputs) {
2339 int location = var.first.first;
2340 int component = var.first.second;
2341 interface_var &iv = var.second;
2342
2343 // Only need to look at the first location, since we use the type's whole size
2344 if (iv.offset != 0) {
2345 continue;
2346 }
2347
2348 if (iv.is_patch) {
2349 continue;
2350 }
2351
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002352 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2353 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002354 }
2355
2356 // Find max component location used for output variables.
2357 for (auto &var : outputs) {
2358 int location = var.first.first;
2359 int component = var.first.second;
2360 interface_var &iv = var.second;
2361
2362 // Only need to look at the first location, since we use the type's whole size
2363 if (iv.offset != 0) {
2364 continue;
2365 }
2366
2367 if (iv.is_patch) {
2368 continue;
2369 }
2370
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002371 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2372 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002373 }
2374
2375 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2376 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002377 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002378 // Check if the variable is a patch. Patches can also be members of blocks,
2379 // but if they are then the top-level arrayness has already been stripped
2380 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002381 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002382
2383 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002384 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002385 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002386 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002387 }
2388 }
2389
2390 switch (pStage->stage) {
2391 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002392 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002393 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2394 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2395 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2396 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002397 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002398 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002399 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002400 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2401 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2402 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2403 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002404 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002405 break;
2406
2407 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002408 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
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::maxTessellationControlPerVertexInputComponents of %u "
2412 "components by %u components",
2413 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002414 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002415 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002416 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
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 input variable uses location that "
2420 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2421 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002422 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002423 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002424 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2425 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2426 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2427 "components by %u components",
2428 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002429 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002430 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002431 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002432 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002433 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2434 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2435 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2436 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002437 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002438 break;
2439
2440 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002441 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
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::maxTessellationEvaluationInputComponents of %u "
2445 "components by %u components",
2446 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002447 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002448 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002449 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
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 input variable uses location that "
2453 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2454 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002455 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002456 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002457 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2458 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2459 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2460 "components by %u components",
2461 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002462 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002463 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002464 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002465 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002466 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2467 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2468 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2469 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002470 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002471 // Portability validation
2472 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2473 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2474 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2475 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2476 " is using abstract patch type IsoLines, but this is not supported on this platform");
2477 }
2478 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2479 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2480 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2481 " is using abstract patch type PointMode, but this is not supported on this platform");
2482 }
2483 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002484 break;
2485
2486 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002487 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002488 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2489 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2490 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2491 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002493 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002494 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002495 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2496 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2497 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2498 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002499 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002500 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002501 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2502 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2503 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2504 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002505 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002506 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002507 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002508 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2509 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2510 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2511 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002512 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002513 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002514 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2515 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2516 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2517 "components by %u components",
2518 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002519 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002520 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002521 break;
2522
2523 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002524 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002525 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2526 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2527 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2528 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002529 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002530 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002531 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002532 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2533 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2534 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2535 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002536 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002537 break;
2538
Jeff Bolz148d94e2018-12-13 21:25:56 -06002539 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2540 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2541 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2542 case VK_SHADER_STAGE_MISS_BIT_NV:
2543 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2544 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2545 case VK_SHADER_STAGE_TASK_BIT_NV:
2546 case VK_SHADER_STAGE_MESH_BIT_NV:
2547 break;
2548
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002549 default:
2550 assert(false); // This should never happen
2551 }
2552 return skip;
2553}
2554
sfricke-samsungdc96f302020-03-18 20:42:10 -07002555bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2556 bool skip = false;
2557 uint32_t total_resources = 0;
2558
2559 // Only currently testing for graphics and compute pipelines
2560 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2561 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2562 return false;
2563 }
2564
2565 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2566 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2567 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2568 }
2569
2570 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2571 // input from CreatePipeline and CreatePipelineLayout level
2572 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2573 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2574 continue;
2575 }
2576
2577 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2578 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2579 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2580 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2581 // Check only descriptor types listed in maxPerStageResources description in spec
2582 switch (binding->descriptorType) {
2583 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2584 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2585 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2586 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2587 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2588 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2589 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2590 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2591 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2592 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2593 total_resources += binding->descriptorCount;
2594 break;
2595 default:
2596 break;
2597 }
2598 }
2599 }
2600 }
2601
2602 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2603 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2604 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2605 skip |= LogError(pipeline->pipeline, vuid,
2606 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2607 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2608 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2609 }
2610
2611 return skip;
2612}
2613
Jeff Bolze4356752019-03-07 11:23:46 -06002614// copy the specialization constant value into buf, if it is present
2615void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2616 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2617
2618 if (spec && spec_id < spec->mapEntryCount) {
2619 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2620 }
2621}
2622
2623// Fill in value with the constant or specialization constant value, if available.
2624// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002625static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002626 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2627 auto type_id = src->get_def(insn.word(1));
2628 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2629 return false;
2630 }
2631 switch (insn.opcode()) {
2632 case spv::OpSpecConstant:
2633 *value = insn.word(3);
2634 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2635 return true;
2636 case spv::OpConstant:
2637 *value = insn.word(3);
2638 return true;
2639 default:
2640 return false;
2641 }
2642}
2643
2644// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002645VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002646 switch (insn.opcode()) {
2647 case spv::OpTypeInt:
2648 switch (insn.word(2)) {
2649 case 8:
2650 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2651 case 16:
2652 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2653 case 32:
2654 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2655 case 64:
2656 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2657 default:
2658 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2659 }
2660 case spv::OpTypeFloat:
2661 switch (insn.word(2)) {
2662 case 16:
2663 return VK_COMPONENT_TYPE_FLOAT16_NV;
2664 case 32:
2665 return VK_COMPONENT_TYPE_FLOAT32_NV;
2666 case 64:
2667 return VK_COMPONENT_TYPE_FLOAT64_NV;
2668 default:
2669 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2670 }
2671 default:
2672 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2673 }
2674}
2675
2676// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2677// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002678bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002679 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002680 bool skip = false;
2681
2682 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2683 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2684 // Map SPIR-V result ID to the ID of its type.
2685 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2686
2687 struct CoopMatType {
2688 uint32_t scope, rows, cols;
2689 VkComponentTypeNV component_type;
2690 bool all_constant;
2691
2692 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2693
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002694 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002695 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2696 spirv_inst_iter insn = src->get_def(id);
2697 uint32_t component_type_id = insn.word(2);
2698 uint32_t scope_id = insn.word(3);
2699 uint32_t rows_id = insn.word(4);
2700 uint32_t cols_id = insn.word(5);
2701 auto component_type_iter = src->get_def(component_type_id);
2702 auto scope_iter = src->get_def(scope_id);
2703 auto rows_iter = src->get_def(rows_id);
2704 auto cols_iter = src->get_def(cols_id);
2705
2706 all_constant = true;
2707 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2708 all_constant = false;
2709 }
2710 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2711 all_constant = false;
2712 }
2713 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2714 all_constant = false;
2715 }
2716 component_type = GetComponentType(component_type_iter, src);
2717 }
2718 };
2719
2720 bool seen_coopmat_capability = false;
2721
2722 for (auto insn : *src) {
2723 // Whitelist instructions whose result can be a cooperative matrix type, and
2724 // keep track of their types. It would be nice if SPIRV-Headers generated code
2725 // to identify which instructions have a result type and result id. Lacking that,
2726 // this whitelist is based on the set of instructions that
2727 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2728 switch (insn.opcode()) {
2729 case spv::OpLoad:
2730 case spv::OpCooperativeMatrixLoadNV:
2731 case spv::OpCooperativeMatrixMulAddNV:
2732 case spv::OpSNegate:
2733 case spv::OpFNegate:
2734 case spv::OpIAdd:
2735 case spv::OpFAdd:
2736 case spv::OpISub:
2737 case spv::OpFSub:
2738 case spv::OpFDiv:
2739 case spv::OpSDiv:
2740 case spv::OpUDiv:
2741 case spv::OpMatrixTimesScalar:
2742 case spv::OpConstantComposite:
2743 case spv::OpCompositeConstruct:
2744 case spv::OpConvertFToU:
2745 case spv::OpConvertFToS:
2746 case spv::OpConvertSToF:
2747 case spv::OpConvertUToF:
2748 case spv::OpUConvert:
2749 case spv::OpSConvert:
2750 case spv::OpFConvert:
2751 id_to_type_id[insn.word(2)] = insn.word(1);
2752 break;
2753 default:
2754 break;
2755 }
2756
2757 switch (insn.opcode()) {
2758 case spv::OpDecorate:
2759 if (insn.word(2) == spv::DecorationSpecId) {
2760 id_to_spec_id[insn.word(1)] = insn.word(3);
2761 }
2762 break;
2763 case spv::OpCapability:
2764 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2765 seen_coopmat_capability = true;
2766
2767 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002768 skip |= LogError(
2769 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2770 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2771 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002772 }
2773 }
2774 break;
2775 case spv::OpMemoryModel:
2776 // If the capability isn't enabled, don't bother with the rest of this function.
2777 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2778 if (!seen_coopmat_capability) {
2779 return skip;
2780 }
2781 break;
2782 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002783 CoopMatType m;
2784 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002785
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002786 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002787 // Validate that the type parameters are all supported for one of the
2788 // operands of a cooperative matrix property.
2789 bool valid = false;
2790 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002791 if (cooperative_matrix_properties[i].AType == m.component_type &&
2792 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2793 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002794 valid = true;
2795 break;
2796 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002797 if (cooperative_matrix_properties[i].BType == m.component_type &&
2798 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2799 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002800 valid = true;
2801 break;
2802 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002803 if (cooperative_matrix_properties[i].CType == m.component_type &&
2804 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2805 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002806 valid = true;
2807 break;
2808 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002809 if (cooperative_matrix_properties[i].DType == m.component_type &&
2810 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2811 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002812 valid = true;
2813 break;
2814 }
2815 }
2816 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002817 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2818 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2819 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002820 }
2821 }
2822 break;
2823 }
2824 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002825 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002826 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2827 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2828 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2829 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002830 // Couldn't find type of matrix
2831 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002832 break;
2833 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002834 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2835 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2836 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2837 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002838
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002839 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002840 // Validate that the type parameters are all supported for the same
2841 // cooperative matrix property.
2842 bool valid = false;
2843 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002844 if (cooperative_matrix_properties[i].AType == a.component_type &&
2845 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2846 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002847
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002848 cooperative_matrix_properties[i].BType == b.component_type &&
2849 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2850 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002851
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002852 cooperative_matrix_properties[i].CType == c.component_type &&
2853 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2854 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002855
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002856 cooperative_matrix_properties[i].DType == d.component_type &&
2857 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2858 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002859 valid = true;
2860 break;
2861 }
2862 }
2863 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002864 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2865 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2866 "VkCooperativeMatrixPropertiesNV",
2867 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002868 }
2869 }
2870 break;
2871 }
2872 default:
2873 break;
2874 }
2875 }
2876
2877 return skip;
2878}
2879
John Zulaufac4c6e12019-07-01 16:05:58 -06002880bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002881 auto entrypoint_id = entrypoint.word(2);
2882
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002883 // The first denorm execution mode encountered, along with its bit width.
2884 // Used to check if SeparateDenormSettings is respected.
2885 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002886
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002887 // The first rounding mode encountered, along with its bit width.
2888 // Used to check if SeparateRoundingModeSettings is respected.
2889 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002890
2891 bool skip = false;
2892
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002893 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002894 uint32_t invocations = 0;
2895
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002896 for (auto insn : *src) {
2897 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2898 auto mode = insn.word(2);
2899 switch (mode) {
2900 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2901 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002902 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2903 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2904 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002905 skip |= LogError(
2906 device, kVUID_Core_Shader_FeatureNotEnabled,
2907 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2908 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002909 }
2910 break;
2911 }
2912
2913 case spv::ExecutionModeDenormPreserve: {
2914 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002915 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2916 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2917 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002918 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2919 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2920 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002921 }
2922
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002923 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2924 // Register the first denorm execution mode found
2925 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002926 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002927 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002928 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002929 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002930 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2931 "Shader uses different denorm execution modes for 16 and 64-bit but "
2932 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002933 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002934 }
2935 break;
2936
Mike Schuchardt2df08912020-12-15 16:28:09 -08002937 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002938 break;
2939
Mike Schuchardt2df08912020-12-15 16:28:09 -08002940 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002941 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2942 "Shader uses different denorm execution modes for different bit widths but "
2943 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002944 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002945 break;
2946
2947 default:
2948 break;
2949 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002950 }
2951 break;
2952 }
2953
2954 case spv::ExecutionModeDenormFlushToZero: {
2955 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002956 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2957 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2958 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002959 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2960 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2961 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002962 }
2963
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002964 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2965 // Register the first denorm execution mode found
2966 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002967 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002968 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002969 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002970 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002971 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2972 "Shader uses different denorm execution modes for 16 and 64-bit but "
2973 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002974 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002975 }
2976 break;
2977
Mike Schuchardt2df08912020-12-15 16:28:09 -08002978 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002979 break;
2980
Mike Schuchardt2df08912020-12-15 16:28:09 -08002981 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002982 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2983 "Shader uses different denorm execution modes for different bit widths but "
2984 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002985 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002986 break;
2987
2988 default:
2989 break;
2990 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002991 }
2992 break;
2993 }
2994
2995 case spv::ExecutionModeRoundingModeRTE: {
2996 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002997 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2998 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2999 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003000 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3001 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3002 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003003 }
3004
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003005 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3006 // Register the first rounding mode found
3007 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003008 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003009 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003010 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003011 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003012 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3013 "Shader uses different rounding modes for 16 and 64-bit but "
3014 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003015 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003016 }
3017 break;
3018
Mike Schuchardt2df08912020-12-15 16:28:09 -08003019 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003020 break;
3021
Mike Schuchardt2df08912020-12-15 16:28:09 -08003022 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003023 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3024 "Shader uses different rounding modes for different bit widths but "
3025 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003026 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003027 break;
3028
3029 default:
3030 break;
3031 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003032 }
3033 break;
3034 }
3035
3036 case spv::ExecutionModeRoundingModeRTZ: {
3037 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003038 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3039 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3040 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003041 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3042 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3043 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003044 }
3045
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003046 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3047 // Register the first rounding mode found
3048 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003049 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003050 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003051 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003052 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003053 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3054 "Shader uses different rounding modes for 16 and 64-bit but "
3055 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003056 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003057 }
3058 break;
3059
Mike Schuchardt2df08912020-12-15 16:28:09 -08003060 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003061 break;
3062
Mike Schuchardt2df08912020-12-15 16:28:09 -08003063 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003064 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3065 "Shader uses different rounding modes for different bit widths but "
3066 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003067 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003068 break;
3069
3070 default:
3071 break;
3072 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003073 }
3074 break;
3075 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003076
3077 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003078 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003079 break;
3080 }
3081
3082 case spv::ExecutionModeInvocations: {
3083 invocations = insn.word(3);
3084 break;
3085 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003086 }
3087 }
3088 }
3089
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003090 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003091 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003092 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3093 "Geometry shader entry point must have an OpExecutionMode instruction that "
3094 "specifies a maximum output vertex count that is greater than 0 and less "
3095 "than or equal to maxGeometryOutputVertices. "
3096 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003097 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003098 }
3099
3100 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003101 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3102 "Geometry shader entry point must have an OpExecutionMode instruction that "
3103 "specifies an invocation count that is greater than 0 and less "
3104 "than or equal to maxGeometryShaderInvocations. "
3105 "Invocations=%d, maxGeometryShaderInvocations=%d",
3106 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003107 }
3108 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003109 return skip;
3110}
3111
locke-lunargd9a069d2019-09-17 01:50:19 -06003112uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003113 auto type = module->get_def(type_id);
3114
3115 while (true) {
3116 switch (type.opcode()) {
3117 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003118 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003119 case spv::OpTypeSampledImage:
3120 type = module->get_def(type.word(2));
3121 break;
3122 case spv::OpTypePointer:
3123 type = module->get_def(type.word(3));
3124 break;
3125 case spv::OpTypeImage: {
3126 auto dim = type.word(3);
3127 auto arrayed = type.word(5);
3128 auto msaa = type.word(6);
3129
Chris Forbes74ba2232018-08-27 15:19:27 -07003130 uint32_t bits = 0;
3131 switch (GetFundamentalType(module, type.word(2))) {
3132 case FORMAT_TYPE_FLOAT:
3133 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3134 break;
3135 case FORMAT_TYPE_UINT:
3136 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3137 break;
3138 case FORMAT_TYPE_SINT:
3139 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3140 break;
3141 default:
3142 break;
3143 }
3144
Chris Forbes47567b72017-06-09 12:09:45 -07003145 switch (dim) {
3146 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003147 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3148 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003149 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003150 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3151 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3152 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003153 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003154 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3155 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003156 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003157 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3158 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003159 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003160 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3161 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003162 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003163 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003164 }
3165 }
3166 default:
3167 return 0;
3168 }
3169 }
3170}
3171
3172// For given pipelineLayout verify that the set_layout_node at slot.first
3173// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003174static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003175 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003176 if (!pipelineLayout) return nullptr;
3177
3178 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3179
3180 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3181}
3182
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003183int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3184 if (module == nullptr) return -1;
3185
3186 auto type = module->get_def(resource.type_id);
3187 while (true) {
3188 switch (type.opcode()) {
3189 case spv::OpTypeSampledImage:
3190 type = module->get_def(type.word(2));
3191 break;
3192 case spv::OpTypePointer:
3193 type = module->get_def(type.word(3));
3194 break;
3195 case spv::OpTypeImage:
3196 return type.word(3);
3197 default:
3198 return -1;
3199 }
3200 }
3201}
3202
3203bool 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 -06003204 for (auto insn : *src) {
3205 if (insn.opcode() == spv::OpEntryPoint) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003206 auto execution_model = insn.word(1);
3207 auto entrypoint_stage_bits = ExecutionModelToShaderStageFlagBits(execution_model);
3208 if (entrypoint_stage_bits == VK_SHADER_STAGE_COMPUTE_BIT) {
Locke1ec6d952019-04-02 11:57:21 -06003209 auto entrypoint_id = insn.word(2);
3210 for (auto insn1 : *src) {
3211 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3212 insn1.word(2) == spv::ExecutionModeLocalSize) {
3213 local_size_x = insn1.word(3);
3214 local_size_y = insn1.word(4);
3215 local_size_z = insn1.word(5);
3216 return true;
3217 }
3218 }
3219 }
3220 }
3221 }
3222 return false;
3223}
3224
locke-lunargd9a069d2019-09-17 01:50:19 -06003225void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003226 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003227 bool is_point_mode = false;
3228
3229 for (auto insn : *src) {
3230 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3231 switch (insn.word(2)) {
3232 case spv::ExecutionModePointMode:
3233 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3234 is_point_mode = true;
3235 break;
3236
3237 case spv::ExecutionModeOutputPoints:
3238 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3239 break;
3240
3241 case spv::ExecutionModeIsolines:
3242 case spv::ExecutionModeOutputLineStrip:
3243 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3244 break;
3245
3246 case spv::ExecutionModeTriangles:
3247 case spv::ExecutionModeQuads:
3248 case spv::ExecutionModeOutputTriangleStrip:
3249 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3250 break;
3251 }
3252 }
3253 }
3254
3255 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3256}
3257
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003258// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3259// o If there is only a vertex shader : gl_PointSize must be written when using points
3260// o If there is a geometry or tessellation shader:
3261// - If shaderTessellationAndGeometryPointSize feature is enabled:
3262// * gl_PointSize must be written in the final geometry stage
3263// - If shaderTessellationAndGeometryPointSize feature is disabled:
3264// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003265bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003266 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003267 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3268 return false;
3269 }
3270
3271 bool pointsize_written = false;
3272 bool skip = false;
3273
3274 // Search for PointSize built-in decorations
3275 std::vector<uint32_t> pointsize_builtin_offsets;
3276 spirv_inst_iter insn = entrypoint;
3277 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3278 if (insn.opcode() == spv::OpMemberDecorate) {
3279 if (insn.word(3) == spv::DecorationBuiltIn) {
3280 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003281 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003282 }
3283 }
3284 } else if (insn.opcode() == spv::OpDecorate) {
3285 if (insn.word(2) == spv::DecorationBuiltIn) {
3286 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003287 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003288 }
3289 }
3290 }
3291
3292 insn++;
3293 }
3294
3295 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003296 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003297 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003298 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3299 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3300 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003301 }
3302 } else if (!pointsize_written) {
3303 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003304 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3305 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3306 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003307 }
3308 return skip;
3309}
John Zulauf14c355b2019-06-27 16:09:37 -06003310
Tobias Hector6663c9b2020-11-05 10:18:02 +00003311bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3312 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3313 bool primitiverate_written = false;
3314 bool viewportindex_written = false;
3315 bool viewportmask_written = false;
3316 bool skip = false;
3317
3318 // Check if the primitive shading rate is written
3319 spirv_inst_iter insn = entrypoint;
3320 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3321 if (insn.opcode() == spv::OpMemberDecorate) {
3322 if (insn.word(3) == spv::DecorationBuiltIn) {
3323 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3324 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3325 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3326 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3327 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3328 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3329 }
3330 }
3331 } else if (insn.opcode() == spv::OpDecorate) {
3332 if (insn.word(2) == spv::DecorationBuiltIn) {
3333 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3334 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3335 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3336 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3337 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3338 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3339 }
3340 }
3341 }
3342
3343 insn++;
3344 }
3345
Tony-LunarGd44844c2021-01-22 13:24:37 -07003346 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3347 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003348 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3349 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003350 skip |= LogError(pipeline->pipeline,
3351 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3352 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3353 "multiple viewports "
3354 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3355 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003356 }
3357
3358 if (primitiverate_written && viewportindex_written) {
3359 skip |= LogError(pipeline->pipeline,
3360 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3361 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3362 "ViewportIndex built-ins,"
3363 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3364 string_VkShaderStageFlagBits(stage));
3365 }
3366
3367 if (primitiverate_written && viewportmask_written) {
3368 skip |= LogError(pipeline->pipeline,
3369 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3370 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3371 "ViewportMaskNV built-ins,"
3372 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3373 string_VkShaderStageFlagBits(stage));
3374 }
3375 }
3376 return skip;
3377}
3378
sfricke-samsung486a51e2021-01-02 00:10:15 -08003379// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003380bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003381 bool skip = false;
3382
sfricke-samsung94167ca2021-02-26 04:14:59 -08003383 switch (insn.opcode()) {
3384 case spv::OpReadClockKHR: {
3385 auto scope_id = module->get_def(insn.word(3));
3386 auto scope_type = scope_id.word(3);
3387 // if scope isn't Subgroup or Device, spirv-val will catch
3388 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3389 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3390 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3391 report_data->FormatHandle(module->vk_shader_module).c_str());
3392 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3393 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3394 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3395 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003396 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003397 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003398 }
3399 }
3400 return skip;
3401}
3402
John Zulauf14c355b2019-06-27 16:09:37 -06003403bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3404 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003405 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003406 bool skip = false;
3407
3408 // Check the module
3409 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003410 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3411 "%s does not contain valid spirv for stage %s.",
3412 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003413 }
3414
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003415 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3416 // specializations should be applied and validated.
3417 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3418 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3419 // Gather the specialization-constant values.
3420 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003421 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003422 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3423 id_value_map.reserve(specialization_info->mapEntryCount);
3424 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3425 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003426
Jeremy Hayes521221d2020-01-15 16:48:49 -07003427 // Expect only scalar types.
3428 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3429 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3430 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003431 }
3432
3433 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003434 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003435 spvtools::Optimizer optimizer(spirv_environment);
3436 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3437 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003438 skip |= LogError(
3439 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003440 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3441 };
3442 optimizer.SetMessageConsumer(consumer);
3443 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3444 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3445 std::vector<uint32_t> specialized_spirv;
3446 auto const optimized =
3447 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3448 assert(optimized == true);
3449
3450 if (optimized) {
3451 spv_context ctx = spvContextCreate(spirv_environment);
3452 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3453 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003454 spvtools::ValidatorOptions options;
3455 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003456 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3457 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003458 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003459 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3460 report_data->FormatHandle(module->vk_shader_module).c_str(),
3461 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003462 }
3463
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003464 spvDiagnosticDestroy(diag);
3465 spvContextDestroy(ctx);
3466 }
3467 }
3468
John Zulauf14c355b2019-06-27 16:09:37 -06003469 // Check the entrypoint
3470 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003471 skip |=
3472 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3473 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003474 }
3475 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3476
3477 // Mark accessible ids
3478 auto &accessible_ids = stage_state.accessible_ids;
3479
Chris Forbes47567b72017-06-09 12:09:45 -07003480 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003481 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3482 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003483
sfricke-samsung94167ca2021-02-26 04:14:59 -08003484 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3485 // and mainly only checking the instruction in detail for a single operation
3486 for (auto insn : *module) {
3487 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3488 skip |= ValidatePropertiesAndFeatures(module, insn);
3489 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3490 }
3491
locke-lunarg63e4daf2020-08-17 17:53:25 -06003492 skip |=
3493 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003494 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003495 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003496 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003497 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003498 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003499 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003500 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003501 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003502 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003503 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003504 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3505 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3506 }
Chris Forbes47567b72017-06-09 12:09:45 -07003507
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003508 std::string vuid_layout_mismatch;
3509 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3510 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3511 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3512 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3513 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3514 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3515 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3516 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3517 }
3518
Chris Forbes47567b72017-06-09 12:09:45 -07003519 // Validate descriptor use
3520 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003521 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003522 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003523 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003524 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3525 std::set<uint32_t> descriptor_types =
3526 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003527
3528 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003529 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003530 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3531 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003532 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003533 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003534 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3535 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003536 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003537 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003538 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3539 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3540 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003541 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003542 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003543 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3544 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003545 }
3546 }
3547
3548 // Validate use of input attachments against subpass structure
3549 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003550 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003551
Petr Krause91f7a12017-12-14 20:57:36 +01003552 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003553 auto subpass = pipeline->graphicsPipelineCI.subpass;
3554
3555 for (auto use : input_attachment_uses) {
3556 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3557 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003558 ? input_attachments[use.first].attachment
3559 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003560
3561 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003562 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3563 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003564 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003565 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003566 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3567 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3568 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003569 }
3570 }
3571 }
Lockeaa8fdc02019-04-02 11:59:20 -06003572 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3573 skip |= ValidateComputeWorkGroupSizes(module);
3574 }
Chris Forbes47567b72017-06-09 12:09:45 -07003575 return skip;
3576}
3577
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003578bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3579 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3580 spirv_inst_iter consumer_entrypoint,
3581 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003582 bool skip = false;
3583
3584 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003585 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3586 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003587
3588 auto a_it = outputs.begin();
3589 auto b_it = inputs.begin();
3590
3591 // Maps sorted by key (location); walk them together to find mismatches
3592 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3593 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3594 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3595 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3596 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3597
3598 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003599 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3600 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3601 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003602 a_it++;
3603 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003604 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3605 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3606 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003607 b_it++;
3608 } else {
3609 // subtleties of arrayed interfaces:
3610 // - if is_patch, then the member is not arrayed, even though the interface may be.
3611 // - if is_block_member, then the extra array level of an arrayed interface is not
3612 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003613 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3614 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3615 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003616 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3617 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3618 DescribeType(producer, a_it->second.type_id).c_str(),
3619 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003620 }
3621 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003622 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3623 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3624 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3625 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003626 }
3627 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003628 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3629 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3630 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003631 }
3632 a_it++;
3633 b_it++;
3634 }
3635 }
3636
Ari Suonpaa696b3432019-03-11 14:02:57 +02003637 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3638 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3639 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3640
3641 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3642 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003643 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3644 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003645 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3646 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003647 } else {
3648 auto it_producer = builtins_producer.begin();
3649 auto it_consumer = builtins_consumer.begin();
3650 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3651 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003652 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3653 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3654 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003655 break;
3656 }
3657 it_producer++;
3658 it_consumer++;
3659 }
3660 }
3661 }
3662 }
3663
Chris Forbes47567b72017-06-09 12:09:45 -07003664 return skip;
3665}
3666
John Zulauf14c355b2019-06-27 16:09:37 -06003667static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003668 uint32_t stage_mask = 0;
3669 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3670 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3671 stage_mask |= pCreateInfo->pStages[i].stage;
3672 }
3673 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003674 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3675 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3676 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003677 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3678 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3679 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3680 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3681 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003682 }
3683 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003684 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003685}
3686
Chris Forbes47567b72017-06-09 12:09:45 -07003687// Validate that the shaders used by the given pipeline and store the active_slots
3688// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003689bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003690 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003691 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3692 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003693
John Zulauf14c355b2019-06-27 16:09:37 -06003694 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003695 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003696 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003697 bool skip = false;
3698
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003699 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003700
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003701 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3702 auto stage = &create_info->pStages[i];
3703 auto stage_id = GetShaderStageId(stage->stage);
3704 shaders[stage_id] = GetShaderModuleState(stage->module);
3705 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3706 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3707 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003708 }
3709
3710 // if the shader stages are no good individually, cross-stage validation is pointless.
3711 if (skip) return true;
3712
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003713 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003714
3715 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003716 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003717 }
3718
3719 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003720 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003721 }
3722
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003723 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3724 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003725
3726 while (!shaders[producer] && producer != fragment_stage) {
3727 producer++;
3728 consumer++;
3729 }
3730
3731 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3732 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003733 if (shaders[consumer]) {
3734 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003735 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3736 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003737 }
Chris Forbes47567b72017-06-09 12:09:45 -07003738
3739 producer = consumer;
3740 }
3741 }
3742
3743 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003744 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003745 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003746 }
3747
3748 return skip;
3749}
3750
Tony-LunarGb2ded512021-02-02 16:03:30 -07003751void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3752 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3753
3754 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3755 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3756 return;
3757 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003758
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003759 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3760 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003761 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003762
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003763 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3764 auto stage = &create_info->pStages[i];
3765 auto stage_id = GetShaderStageId(stage->stage);
3766 shaders[stage_id] = GetShaderModuleState(stage->module);
3767 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003768
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003769 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3770 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003771 spirv_inst_iter insn = entrypoints[stage_id];
3772 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003773
Tony-LunarGb2ded512021-02-02 16:03:30 -07003774 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3775 if (insn.opcode() == spv::OpMemberDecorate) {
3776 if (insn.word(3) == spv::DecorationBuiltIn) {
3777 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3778 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003779 }
3780 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003781 } else if (insn.opcode() == spv::OpDecorate) {
3782 if (insn.word(2) == spv::DecorationBuiltIn) {
3783 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3784 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3785 }
3786 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003787 }
3788
Tony-LunarGb2ded512021-02-02 16:03:30 -07003789 insn++;
3790 }
3791 if (primitiverate_written) {
3792 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3793 }
3794 }
3795 }
3796}
3797
3798bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3799 const char *caller, const DrawDispatchVuid &vuid) const {
3800 auto create_info = pipeline->graphicsPipelineCI.ptr();
3801 bool skip = false;
3802
3803 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3804 auto stage = &create_info->pStages[i];
3805 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3806 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3807 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3808 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3809 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003810 skip |=
3811 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3812 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3813 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3814 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003815 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003816 }
3817 }
3818 }
3819 }
3820
3821 return skip;
3822}
3823
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003824bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003825 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003826
John Zulauf14c355b2019-06-27 16:09:37 -06003827 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3828 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003829
John Zulauf14c355b2019-06-27 16:09:37 -06003830 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003831}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003832
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003833uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3834 uint32_t total = 0;
3835
3836 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3837 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3838 if (stages[stage_index].stage == stageBit) {
3839 total++;
3840 }
3841 }
3842
3843 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3844 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3845 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3846 total += CalcShaderStageCount(library_pipeline, stageBit);
3847 }
3848 }
3849
3850 return total;
3851}
3852
sourav parmarcd5fb182020-07-17 12:58:44 -07003853bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003854 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003855
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003856 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003857 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3858 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3859 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3860 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3861 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3862 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3863 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003864 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003865 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3866 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003867 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003868 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003869 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003870 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3871 skip |= LogError(
3872 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3873 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3874 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3877 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003878 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3879 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003880 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003881 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003882 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3883 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3884 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3885 "member must have been created with values of the maxPipelineRayPayloadSize and "
3886 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3887 }
3888 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003889 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003890 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3891 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3892 "vkCreateRayTracingPipelinesKHR: If flags includes "
3893 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3894 "the pLibraries member of libraries must have been created with the "
3895 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3896 }
sourav parmar83c31b12020-05-06 12:30:54 -07003897 }
3898 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003899 } else {
3900 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003901 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3902 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3903 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003904 pipeline->raytracingPipelineCI.maxRecursionDepth,
3905 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3906 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003907 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003908 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3909 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3910
John Zulaufe4474e72019-07-01 17:28:27 -06003911 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003912 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003913
John Zulaufe4474e72019-07-01 17:28:27 -06003914 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3915 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003916
John Zulaufe4474e72019-07-01 17:28:27 -06003917 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003918 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003919
3920 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3921 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3922 if (raygen_stages_count == 0) {
3923 skip |= LogError(
3924 device,
3925 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3926 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3927 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003928 }
3929
3930 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3931 const auto &group = groups[group_index];
3932
3933 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3934 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3935 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3936 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3937 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003938 skip |= LogError(device,
3939 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3940 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3941 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003942 }
3943 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3944 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003945 skip |= LogError(device,
3946 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3947 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3948 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003949 }
3950 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3951 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3952 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003953 skip |= LogError(device,
3954 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3955 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3956 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003957 }
3958 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3959 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003960 skip |= LogError(device,
3961 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3962 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3963 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003964 }
3965 }
3966
3967 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3968 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3969 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3970 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003971 skip |= LogError(device,
3972 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3973 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3974 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003975 }
3976 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3977 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3978 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003979 skip |= LogError(device,
3980 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3981 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3982 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003983 }
3984 }
John Zulaufe4474e72019-07-01 17:28:27 -06003985 }
3986 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003987}
3988
Dave Houltona9df0ce2018-02-07 10:51:23 -07003989uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003990
Dave Houltona9df0ce2018-02-07 10:51:23 -07003991static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003992 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003993 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003994 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003995 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003996 return nullptr;
3997}
3998
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003999bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004000 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004001 bool skip = false;
4002 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004003
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06004004 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004005 return false;
4006 }
4007
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06004008 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004009
4010 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004011 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
4012 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
4013 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004014 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004015 auto cache = GetValidationCacheInfo(pCreateInfo);
4016 uint32_t hash = 0;
4017 if (cache) {
4018 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004019 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004020 }
4021
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004022 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4023 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004024 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004025 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004026 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004027 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004028 spvtools::ValidatorOptions options;
4029 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004030 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004031 if (spv_valid != SPV_SUCCESS) {
4032 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004033 if (spv_valid == SPV_WARNING) {
4034 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4035 diag && diag->error ? diag->error : "(no error text)");
4036 } else {
4037 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4038 diag && diag->error ? diag->error : "(no error text)");
4039 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004040 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004041 } else {
4042 if (cache) {
4043 cache->Insert(hash);
4044 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004045 }
4046
4047 spvDiagnosticDestroy(diag);
4048 spvContextDestroy(ctx);
4049 }
4050
Chris Forbes4ae55b32017-06-09 14:42:56 -07004051 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004052}
4053
John Zulaufac4c6e12019-07-01 16:05:58 -06004054bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004055 bool skip = false;
4056 uint32_t local_size_x = 0;
4057 uint32_t local_size_y = 0;
4058 uint32_t local_size_z = 0;
4059 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
4060 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004061 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4062 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4063 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4064 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004065 }
4066 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004067 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4068 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4069 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4070 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004071 }
4072 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004073 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4074 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4075 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4076 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004077 }
4078
4079 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4080 uint64_t invocations = local_size_x * local_size_y;
4081 // Prevent overflow.
4082 bool fail = false;
4083 if (invocations > UINT32_MAX || invocations > limit) {
4084 fail = true;
4085 }
4086 if (!fail) {
4087 invocations *= local_size_z;
4088 if (invocations > UINT32_MAX || invocations > limit) {
4089 fail = true;
4090 }
4091 }
4092 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004093 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4094 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4095 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4096 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4097 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004098 }
4099 }
4100 return skip;
4101}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004102
4103spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4104 if (api_version >= VK_API_VERSION_1_2) {
4105 return SPV_ENV_VULKAN_1_2;
4106 } else if (api_version >= VK_API_VERSION_1_1) {
4107 if (spirv_1_4) {
4108 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4109 } else {
4110 return SPV_ENV_VULKAN_1_1;
4111 }
4112 }
4113 return SPV_ENV_VULKAN_1_0;
4114}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004115
4116void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4117 spvtools::ValidatorOptions &options) {
4118 if (device_extensions.vk_khr_relaxed_block_layout) {
4119 options.SetRelaxBlockLayout(true);
4120 }
4121 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4122 options.SetUniformBufferStandardLayout(true);
4123 }
4124 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4125 options.SetScalarBlockLayout(true);
4126 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004127 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4128 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4129 options.SetWorkgroupScalarBlockLayout(true);
4130 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004131}