blob: e6847cb14b7be23a3bcb386ad1789c9d68655008 [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
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800229 // Execution Mode
230 case spv::OpExecutionMode: {
231 execution_mode_inst[insn.word(1)].push_back(insn);
232 } break;
233
Chris Forbes47567b72017-06-09 12:09:45 -0700234 default:
235 // We don't care about any other defs for now.
236 break;
237 }
238 }
239}
240
Jeff Bolz105d6492018-09-29 15:46:44 -0500241unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
242 switch (mode) {
243 case spv::ExecutionModelVertex:
244 return VK_SHADER_STAGE_VERTEX_BIT;
245 case spv::ExecutionModelTessellationControl:
246 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
247 case spv::ExecutionModelTessellationEvaluation:
248 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
249 case spv::ExecutionModelGeometry:
250 return VK_SHADER_STAGE_GEOMETRY_BIT;
251 case spv::ExecutionModelFragment:
252 return VK_SHADER_STAGE_FRAGMENT_BIT;
253 case spv::ExecutionModelGLCompute:
254 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600255 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700256 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600257 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700258 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600259 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700260 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600261 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700262 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600263 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700264 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600265 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700266 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500267 case spv::ExecutionModelTaskNV:
268 return VK_SHADER_STAGE_TASK_BIT_NV;
269 case spv::ExecutionModelMeshNV:
270 return VK_SHADER_STAGE_MESH_BIT_NV;
271 default:
272 return 0;
273 }
274}
275
locke-lunargde3f0fa2020-09-10 11:55:31 -0600276const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
277 VkShaderStageFlagBits stageBits) {
278 auto range = src->entry_points.equal_range(name);
279 for (auto it = range.first; it != range.second; ++it) {
280 if (it->second.stage == stageBits) {
281 return &(it->second);
282 }
283 }
284 return nullptr;
285}
286
locke-lunargd9a069d2019-09-17 01:50:19 -0600287spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600288 auto range = src->entry_points.equal_range(name);
289 for (auto it = range.first; it != range.second; ++it) {
290 if (it->second.stage == stageBits) {
291 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700292 }
293 }
Chris Forbes47567b72017-06-09 12:09:45 -0700294 return src->end();
295}
296
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600297static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700298 switch (sc) {
299 case spv::StorageClassInput:
300 return "input";
301 case spv::StorageClassOutput:
302 return "output";
303 case spv::StorageClassUniformConstant:
304 return "const uniform";
305 case spv::StorageClassUniform:
306 return "uniform";
307 case spv::StorageClassWorkgroup:
308 return "workgroup local";
309 case spv::StorageClassCrossWorkgroup:
310 return "workgroup global";
311 case spv::StorageClassPrivate:
312 return "private global";
313 case spv::StorageClassFunction:
314 return "function";
315 case spv::StorageClassGeneric:
316 return "generic";
317 case spv::StorageClassAtomicCounter:
318 return "atomic counter";
319 case spv::StorageClassImage:
320 return "image";
321 case spv::StorageClassPushConstant:
322 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800323 case spv::StorageClassStorageBuffer:
324 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700325 default:
326 return "unknown";
327 }
328}
329
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700330// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
331// Otherwise, returns src->end().
332spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700333 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700334
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700335 // If id is a copy, see where it was copied from
336 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
337 id = value.word(3);
338 value = src->get_def(id);
339 }
340
341 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
342 return value;
343 }
344 return src->end();
345}
346
347// Assumes itr points to an OpConstant instruction
348uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
349
350// Either returns the constant value described by the instruction at id, or 1
351uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
352 auto value = GetConstantDef(src, id);
353
354 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700355 // TODO: Either ensure that the specialization transform is already performed on a module we're
356 // considering here, OR -- specialize on the fly now.
357 return 1;
358 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700359 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700360}
361
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600362static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700363 auto insn = src->get_def(type);
364 assert(insn != src->end());
365
366 switch (insn.opcode()) {
367 case spv::OpTypeBool:
368 ss << "bool";
369 break;
370 case spv::OpTypeInt:
371 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
372 break;
373 case spv::OpTypeFloat:
374 ss << "float" << insn.word(2);
375 break;
376 case spv::OpTypeVector:
377 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600378 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700379 break;
380 case spv::OpTypeMatrix:
381 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600382 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700383 break;
384 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600385 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
386 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700387 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700388 case spv::OpTypeRuntimeArray:
389 ss << "runtime arr[] of ";
390 DescribeTypeInner(ss, src, insn.word(2));
391 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700392 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600393 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
394 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700395 break;
396 case spv::OpTypeStruct: {
397 ss << "struct of (";
398 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600399 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700400 if (i == insn.len() - 1) {
401 ss << ")";
402 } else {
403 ss << ", ";
404 }
405 }
406 break;
407 }
408 case spv::OpTypeSampler:
409 ss << "sampler";
410 break;
411 case spv::OpTypeSampledImage:
412 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700414 break;
415 case spv::OpTypeImage:
416 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
417 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600418 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500419 ss << "accelerationStruture";
420 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700421 default:
422 ss << "oddtype";
423 break;
424 }
425}
426
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600427static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700428 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600429 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700430 return ss.str();
431}
432
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600433static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700434 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
435 return type.word(2) < 64;
436}
437
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600438static 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 -0600439 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700440 // Walk two type trees together, and complain about differences
441 auto a_insn = a->get_def(a_type);
442 auto b_insn = b->get_def(b_type);
443 assert(a_insn != a->end());
444 assert(b_insn != b->end());
445
Chris Forbes062f1222018-08-21 15:34:15 -0700446 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
447
Chris Forbes47567b72017-06-09 12:09:45 -0700448 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600449 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700450 }
451
452 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
453 // 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 -0600454 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700455 }
456
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600457 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
458 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700459 }
460
461 if (a_insn.opcode() != b_insn.opcode()) {
462 return false;
463 }
464
465 if (a_insn.opcode() == spv::OpTypePointer) {
466 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600467 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700468 }
469
470 if (a_arrayed || b_arrayed) {
471 // If we havent resolved array-of-verts by here, we're not going to.
472 return false;
473 }
474
475 switch (a_insn.opcode()) {
476 case spv::OpTypeBool:
477 return true;
478 case spv::OpTypeInt:
479 // Match on width, signedness
480 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
481 case spv::OpTypeFloat:
482 // Match on width
483 return a_insn.word(2) == b_insn.word(2);
484 case spv::OpTypeVector:
485 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600486 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
487 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700488 return a_insn.word(3) >= b_insn.word(3);
489 } else {
490 return a_insn.word(3) == b_insn.word(3);
491 }
492 case spv::OpTypeMatrix:
493 // Match on element type, count.
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) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700495 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700496 case spv::OpTypeArray:
497 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
498 // 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 -0600499 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
500 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700501 case spv::OpTypeStruct:
502 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700503 {
504 if (a_insn.len() != b_insn.len()) {
505 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700506 }
Chris Forbes47567b72017-06-09 12:09:45 -0700507
Dave Houltona9df0ce2018-02-07 10:51:23 -0700508 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600509 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700510 return false;
511 }
512 }
513
514 return true;
515 }
Chris Forbes47567b72017-06-09 12:09:45 -0700516 default:
517 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
518 return false;
519 }
520}
521
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600522static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700523 auto insn = src->get_def(type);
524 assert(insn != src->end());
525
526 switch (insn.opcode()) {
527 case spv::OpTypePointer:
528 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
529 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600530 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700531 case spv::OpTypeArray:
532 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600533 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700534 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600535 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700536 }
537 case spv::OpTypeMatrix:
538 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600539 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700540 case spv::OpTypeVector: {
541 auto scalar_type = src->get_def(insn.word(2));
542 auto bit_width =
543 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
544
545 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
546 return (bit_width * insn.word(3) + 127) / 128;
547 }
548 default:
549 // Everything else is just 1.
550 return 1;
551
552 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
553 }
554}
555
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600556static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200557 auto insn = src->get_def(type);
558 assert(insn != src->end());
559
560 switch (insn.opcode()) {
561 case spv::OpTypePointer:
562 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
563 // pointers around.
564 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
565 case spv::OpTypeStruct: {
566 uint32_t sum = 0;
567 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
568 sum += GetComponentsConsumedByType(src, insn.word(i), false);
569 }
570 return sum;
571 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500572 case spv::OpTypeArray:
573 if (strip_array_level) {
574 return GetComponentsConsumedByType(src, insn.word(2), false);
575 } else {
576 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200577 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200578 case spv::OpTypeMatrix:
579 // Num locations is the dimension * element size
580 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
581 case spv::OpTypeVector: {
582 auto scalar_type = src->get_def(insn.word(2));
583 auto bit_width =
584 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
585 // One component is 32-bit
586 return (bit_width * insn.word(3) + 31) / 32;
587 }
588 case spv::OpTypeFloat: {
589 auto bit_width = insn.word(2);
590 return (bit_width + 31) / 32;
591 }
592 case spv::OpTypeInt: {
593 auto bit_width = insn.word(2);
594 return (bit_width + 31) / 32;
595 }
596 case spv::OpConstant:
597 return GetComponentsConsumedByType(src, insn.word(1), false);
598 default:
599 return 0;
600 }
601}
602
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600603static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700604 switch (format) {
605 case VK_FORMAT_R64G64B64A64_SFLOAT:
606 case VK_FORMAT_R64G64B64A64_SINT:
607 case VK_FORMAT_R64G64B64A64_UINT:
608 case VK_FORMAT_R64G64B64_SFLOAT:
609 case VK_FORMAT_R64G64B64_SINT:
610 case VK_FORMAT_R64G64B64_UINT:
611 return 2;
612 default:
613 return 1;
614 }
615}
616
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600617static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700618 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
619 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
620 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
621 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700622 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
623 return FORMAT_TYPE_FLOAT;
624}
625
626// 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 -0700627// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600628static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700629 auto insn = src->get_def(type);
630 assert(insn != src->end());
631
632 switch (insn.opcode()) {
633 case spv::OpTypeInt:
634 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
635 case spv::OpTypeFloat:
636 return FORMAT_TYPE_FLOAT;
637 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700638 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700639 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700640 case spv::OpTypeRuntimeArray:
641 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600642 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700643 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600644 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700645
646 default:
647 return 0;
648 }
649}
650
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600651static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700652 uint32_t bit_pos = uint32_t(u_ffs(stage));
653 return bit_pos - 1;
654}
655
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600656static 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 -0700657 while (true) {
658 if (def.opcode() == spv::OpTypePointer) {
659 def = src->get_def(def.word(3));
660 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
661 def = src->get_def(def.word(2));
662 is_array_of_verts = false;
663 } else if (def.opcode() == spv::OpTypeStruct) {
664 return def;
665 } else {
666 return src->end();
667 }
668 }
669}
670
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600671static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800672 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
673 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700674 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600675 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800676 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700677 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700678 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700679 }
680
681 std::unordered_map<unsigned, unsigned> member_components;
682 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700683 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700684
685 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800686 for (auto insn : src->member_decoration_inst) {
687 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700688 unsigned member_index = insn.word(2);
689
690 if (insn.word(3) == spv::DecorationComponent) {
691 unsigned component = insn.word(4);
692 member_components[member_index] = component;
693 }
694
695 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
696 member_relaxed_precision[member_index] = 1;
697 }
Chris Forbesa313d772017-06-13 13:59:41 -0700698
699 if (insn.word(3) == spv::DecorationPatch) {
700 member_patch[member_index] = 1;
701 }
Chris Forbes47567b72017-06-09 12:09:45 -0700702 }
703 }
704
Chris Forbesa313d772017-06-13 13:59:41 -0700705 // TODO: correctly handle location assignment from outside
706
Chris Forbes47567b72017-06-09 12:09:45 -0700707 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800708 for (auto insn : src->member_decoration_inst) {
709 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700710 unsigned member_index = insn.word(2);
711 unsigned member_type_id = type.word(2 + member_index);
712
713 if (insn.word(3) == spv::DecorationLocation) {
714 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600715 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700716 auto component_it = member_components.find(member_index);
717 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
718 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700719 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700720
721 for (unsigned int offset = 0; offset < num_locations; offset++) {
722 interface_var v = {};
723 v.id = id;
724 // TODO: member index in interface_var too?
725 v.type_id = member_type_id;
726 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700727 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700728 v.is_block_member = true;
729 v.is_relaxed_precision = is_relaxed_precision;
730 (*out)[std::make_pair(location + offset, component)] = v;
731 }
732 }
733 }
734 }
Chris Forbesa313d772017-06-13 13:59:41 -0700735
736 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700737}
738
Ari Suonpaa696b3432019-03-11 14:02:57 +0200739static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800740 assert(entrypoint.opcode() == spv::OpEntryPoint);
741
Ari Suonpaa696b3432019-03-11 14:02:57 +0200742 std::vector<uint32_t> interfaces;
743 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
744 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
745 uint32_t word = 3;
746 while (entrypoint.word(word) & 0xff000000u) {
747 ++word;
748 }
749 ++word;
750
751 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
752
753 return interfaces;
754}
755
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600756static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600757 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700758 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
759
Chris Forbes47567b72017-06-09 12:09:45 -0700760 std::map<location_t, interface_var> out;
761
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800762 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
763 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700764 assert(insn != src->end());
765 assert(insn.opcode() == spv::OpVariable);
766
767 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800768 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700769 unsigned id = insn.word(2);
770 unsigned type = insn.word(1);
771
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800772 int location = d.location;
773 int builtin = d.builtin;
774 unsigned component = d.component;
775 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
776 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700777
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700778 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700779 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700780 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700781 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
782 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600783 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700784 for (unsigned int offset = 0; offset < num_locations; offset++) {
785 interface_var v = {};
786 v.id = id;
787 v.type_id = type;
788 v.offset = offset;
789 v.is_patch = is_patch;
790 v.is_relaxed_precision = is_relaxed_precision;
791 out[std::make_pair(location + offset, component)] = v;
792 }
Chris Forbes47567b72017-06-09 12:09:45 -0700793 }
794 }
795 }
796
797 return out;
798}
799
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600800static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200801 uint32_t storageClass) {
802 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700803 std::vector<uint32_t> builtin_struct_members;
804 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200805
sfricke-samsung94d71a52021-02-26 05:25:43 -0800806 for (auto insn : src->member_decoration_inst) {
807 if (insn.word(3) == spv::DecorationBuiltIn) {
808 builtin_struct_members.push_back(insn.word(1));
809 }
810 }
811 for (auto insn : src->decoration_inst) {
812 switch (insn.word(2)) {
813 case spv::DecorationBlock: {
814 uint32_t block_id = insn.word(1);
815 for (auto built_in_block_id : builtin_struct_members) {
816 // Check if one of the members of the block are built-in -> the block is built-in
817 if (block_id == built_in_block_id) {
818 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200819 break;
820 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200821 }
822 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800823 }
824 case spv::DecorationBuiltIn:
825 builtin_decorations.push_back(insn.word(1));
826 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200827 default:
828 break;
829 }
830 }
831
832 // Find all interface variables belonging to the entrypoint and matching the storage class
833 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
834 auto def = src->get_def(id);
835 assert(def != src->end());
836 assert(def.opcode() == spv::OpVariable);
837
838 if (def.word(3) == storageClass) variables.push_back(def.word(1));
839 }
840
841 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700842 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200843 for (auto &var : variables) {
844 auto def = src->get_def(src->get_def(var).word(3));
845
846 // It could be an array of IO blocks. The element type should be the struct defining the block contents
847 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
848
849 // Now find all members belonging to the struct defining the IO block
850 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700851 for (auto built_in_id : builtin_decorations) {
852 if (built_in_id == def.word(1)) {
853 for (int i = 2; i < static_cast<int>(def.len()); i++) {
854 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
855 }
856 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800857 for (auto insn : src->member_decoration_inst) {
858 if (insn.word(1) == built_in_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700859 auto struct_index = insn.word(2);
860 assert(struct_index < builtin_block_members.size());
861 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200862 }
863 }
864 }
865 }
866 }
867 }
868
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700869 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200870}
871
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600872static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600873 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700874 std::vector<std::pair<uint32_t, interface_var>> out;
875
sfricke-samsung94d71a52021-02-26 05:25:43 -0800876 for (auto insn : src->decoration_inst) {
877 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
878 auto attachment_index = insn.word(3);
879 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700880
sfricke-samsung94d71a52021-02-26 05:25:43 -0800881 if (accessible_ids.count(id)) {
882 auto def = src->get_def(id);
883 assert(def != src->end());
884 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
885 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
886 for (unsigned int offset = 0; offset < num_locations; offset++) {
887 interface_var v = {};
888 v.id = id;
889 v.type_id = def.word(1);
890 v.offset = offset;
891 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700892 }
893 }
894 }
895 }
896 }
897
898 return out;
899}
900
locke-lunarg25b6c352020-08-06 17:44:18 -0600901static bool AtomicOperation(uint32_t opcode) {
902 switch (opcode) {
903 case spv::OpAtomicLoad:
904 case spv::OpAtomicStore:
905 case spv::OpAtomicExchange:
906 case spv::OpAtomicCompareExchange:
907 case spv::OpAtomicCompareExchangeWeak:
908 case spv::OpAtomicIIncrement:
909 case spv::OpAtomicIDecrement:
910 case spv::OpAtomicIAdd:
911 case spv::OpAtomicISub:
912 case spv::OpAtomicSMin:
913 case spv::OpAtomicUMin:
914 case spv::OpAtomicSMax:
915 case spv::OpAtomicUMax:
916 case spv::OpAtomicAnd:
917 case spv::OpAtomicOr:
918 case spv::OpAtomicXor:
919 case spv::OpAtomicFAddEXT:
920 return true;
921 default:
922 return false;
923 }
924 return false;
925}
926
sfricke-samsung0065ce02020-12-03 22:46:37 -0800927// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
928// covered with VUID 01090
929static bool GroupOperation(uint32_t opcode) {
930 switch (opcode) {
931 case spv::OpGroupNonUniformElect:
932 case spv::OpGroupNonUniformAll:
933 case spv::OpGroupNonUniformAny:
934 case spv::OpGroupNonUniformAllEqual:
935 case spv::OpGroupNonUniformBroadcast:
936 case spv::OpGroupNonUniformBroadcastFirst:
937 case spv::OpGroupNonUniformBallot:
938 case spv::OpGroupNonUniformInverseBallot:
939 case spv::OpGroupNonUniformBallotBitExtract:
940 case spv::OpGroupNonUniformBallotBitCount:
941 case spv::OpGroupNonUniformBallotFindLSB:
942 case spv::OpGroupNonUniformBallotFindMSB:
943 case spv::OpGroupNonUniformShuffle:
944 case spv::OpGroupNonUniformShuffleXor:
945 case spv::OpGroupNonUniformShuffleUp:
946 case spv::OpGroupNonUniformShuffleDown:
947 case spv::OpGroupNonUniformIAdd:
948 case spv::OpGroupNonUniformFAdd:
949 case spv::OpGroupNonUniformIMul:
950 case spv::OpGroupNonUniformFMul:
951 case spv::OpGroupNonUniformSMin:
952 case spv::OpGroupNonUniformUMin:
953 case spv::OpGroupNonUniformFMin:
954 case spv::OpGroupNonUniformSMax:
955 case spv::OpGroupNonUniformUMax:
956 case spv::OpGroupNonUniformFMax:
957 case spv::OpGroupNonUniformBitwiseAnd:
958 case spv::OpGroupNonUniformBitwiseOr:
959 case spv::OpGroupNonUniformBitwiseXor:
960 case spv::OpGroupNonUniformLogicalAnd:
961 case spv::OpGroupNonUniformLogicalOr:
962 case spv::OpGroupNonUniformLogicalXor:
963 case spv::OpGroupNonUniformQuadBroadcast:
964 case spv::OpGroupNonUniformQuadSwap:
965 case spv::OpGroupNonUniformPartitionNV:
966 return true;
967 default:
968 return false;
969 }
970 return false;
971}
972
locke-lunarg12d20992020-09-21 12:46:49 -0600973bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
974 const std::unordered_map<unsigned, unsigned> &load_members,
975 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
976 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600977 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600978 auto load_it = load_members.find(load_id);
979 if (load_it == load_members.end()) {
980 continue;
981 }
982 if (load_it->second == object_id) {
983 return true;
984 }
985
986 auto accesschain_it = accesschain_members.find(load_it->second);
987 if (accesschain_it == accesschain_members.end()) {
988 continue;
989 }
990 if (accesschain_it->second.first == object_id) {
991 return true;
992 }
993 }
994 return false;
995}
996
locke-lunargae2a43c2020-09-22 17:21:57 -0600997bool CheckImageOperandsBiasOffset(uint32_t type) {
998 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
999 spv::ImageOperandsConstOffsetsMask)
1000 ? true
1001 : false;
1002}
1003
locke-lunargd3da0422020-09-23 01:02:11 -06001004struct shader_module_used_operators {
1005 bool updated;
1006 std::vector<unsigned> imagwrite_members;
1007 std::vector<unsigned> atomic_members;
1008 std::vector<unsigned> store_members;
1009 std::vector<unsigned> atomic_store_members;
1010 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1011 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001012 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
locke-lunargd3da0422020-09-23 01:02:11 -06001013 std::unordered_map<unsigned, unsigned> load_members;
1014 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1015 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
1016
1017 shader_module_used_operators() : updated(false) {}
1018
1019 void update(SHADER_MODULE_STATE const *module) {
1020 if (updated) return;
1021 updated = true;
1022
1023 for (auto insn : *module) {
1024 switch (insn.opcode()) {
1025 case spv::OpImageSampleImplicitLod:
1026 case spv::OpImageSampleProjImplicitLod:
1027 case spv::OpImageSampleProjExplicitLod:
1028 case spv::OpImageSparseSampleImplicitLod:
1029 case spv::OpImageSparseSampleProjImplicitLod:
1030 case spv::OpImageSparseSampleProjExplicitLod: {
1031 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1032 // ImageOperands in index: 5
1033 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1034 sampler_bias_offset_members.emplace_back(insn.word(3));
1035 }
1036 break;
1037 }
1038 case spv::OpImageSampleDrefImplicitLod:
1039 case spv::OpImageSampleDrefExplicitLod:
1040 case spv::OpImageSampleProjDrefImplicitLod:
1041 case spv::OpImageSampleProjDrefExplicitLod:
1042 case spv::OpImageSparseSampleDrefImplicitLod:
1043 case spv::OpImageSparseSampleDrefExplicitLod:
1044 case spv::OpImageSparseSampleProjDrefImplicitLod:
1045 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1046 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1047 // ImageOperands in index: 6
1048 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1049 sampler_bias_offset_members.emplace_back(insn.word(3));
1050 }
1051 break;
1052 }
1053 case spv::OpImageSampleExplicitLod:
1054 case spv::OpImageSparseSampleExplicitLod: {
1055 // ImageOperands in index: 5
1056 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1057 sampler_bias_offset_members.emplace_back(insn.word(3));
1058 }
1059 break;
1060 }
1061 case spv::OpStore: {
1062 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1063 break;
1064 }
1065 case spv::OpImageWrite: {
1066 imagwrite_members.emplace_back(insn.word(1)); // Load id
1067 break;
1068 }
1069 case spv::OpSampledImage: {
1070 // 3: image load id, 4: sampler load id
1071 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1072 break;
1073 }
1074 case spv::OpLoad: {
1075 // 2: Load id, 3: object id or AccessChain id
1076 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1077 break;
1078 }
1079 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001080 if (insn.len() == 4) {
1081 // If it is for struct, the length is only 4.
1082 // 2: AccessChain id, 3: object id
1083 accesschain_members.insert(std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0)));
1084 } else {
1085 // 2: AccessChain id, 3: object id, 4: object id of array index
1086 accesschain_members.insert(
1087 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1088 }
locke-lunargd3da0422020-09-23 01:02:11 -06001089 break;
1090 }
1091 case spv::OpImageTexelPointer: {
1092 // 2: ImageTexelPointer id, 3: object id
1093 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1094 break;
1095 }
1096 default: {
1097 if (AtomicOperation(insn.opcode())) {
1098 if (insn.opcode() == spv::OpAtomicStore) {
1099 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1100 } else {
1101 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1102 }
1103 }
1104 break;
1105 }
1106 }
1107 }
1108 }
1109};
1110
sfricke-samsung691299b2021-01-01 20:48:48 -08001111// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1112// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001113static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001114 bool is_check_writable, interface_var &out_interface_var,
1115 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001116 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001117 unsigned int id = id_it.word(2);
1118
Chris Forbes8af24522018-03-07 11:37:45 -08001119 auto type = module->get_def(type_id);
1120
1121 // 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 -06001122 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1123 type.opcode() == spv::OpTypeSampledImage) {
1124 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1125 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001126 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001127 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001128 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001129 }
1130 }
Chris Forbes8af24522018-03-07 11:37:45 -08001131 switch (type.opcode()) {
1132 case spv::OpTypeImage: {
1133 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001134 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001135 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001136
locke-lunargd3da0422020-09-23 01:02:11 -06001137 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1138 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001139 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001140 }
1141 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1142 used_operators.accesschain_members)) {
1143 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001144 }
locke-lunargd3da0422020-09-23 01:02:11 -06001145 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1146 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001147 out_interface_var.is_sampler_bias_offset = true;
1148 }
locke-lunargd3da0422020-09-23 01:02:11 -06001149 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1150 used_operators.accesschain_members) ||
1151 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1152 used_operators.accesschain_members)) {
1153 out_interface_var.is_atomic_operation = true;
1154 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001155
locke-lunargd3da0422020-09-23 01:02:11 -06001156 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001157 // Find if image id match.
1158 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001159 auto load_it = used_operators.load_members.find(itp_id.first);
1160 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001161 continue;
1162 } else {
1163 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001164 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1165 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001166 continue;
1167 } else {
1168 if (accesschain_it->second.first != id) {
1169 continue;
1170 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001171
1172 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1173 if (const_itr == module->end()) {
1174 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001175 break;
1176 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001177 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001178 }
1179 }
1180 }
1181 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001182 load_it = used_operators.load_members.find(itp_id.second);
1183 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001184 continue;
1185 } else {
1186 uint32_t sampler_id = load_it->second;
1187 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001188 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001189
locke-lunargd3da0422020-09-23 01:02:11 -06001190 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001191 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1192 if (const_itr == module->end()) {
1193 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001194 break;
1195 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001196 sampler_id = const_itr.offset();
1197 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001198 }
1199 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001200 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1201 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1202 }
1203 out_interface_var.samplers_used_by_image[image_index].emplace(
1204 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001205 }
1206 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001207 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001208 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001209 }
1210
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001211 case spv::OpTypeStruct: {
1212 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001213 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001214 for (auto insn : module->member_decoration_inst) {
1215 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001216 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001217 }
1218 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001219
1220 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1221 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001222 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001223 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001224
locke-lunargd3da0422020-09-23 01:02:11 -06001225 for (auto oid : used_operators.store_members) {
1226 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001227 out_interface_var.is_writable = true;
1228 return;
1229 }
locke-lunargd3da0422020-09-23 01:02:11 -06001230 auto accesschain_it = used_operators.accesschain_members.find(oid);
1231 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001232 continue;
1233 }
locke-lunargd3da0422020-09-23 01:02:11 -06001234 if (accesschain_it->second.first == id) {
1235 out_interface_var.is_writable = true;
1236 return;
1237 }
1238 }
1239 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1240 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001241 out_interface_var.is_writable = true;
1242 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001243 }
1244 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001245 }
Chris Forbes8af24522018-03-07 11:37:45 -08001246 }
Chris Forbes8af24522018-03-07 11:37:45 -08001247}
1248
locke-lunargd9a069d2019-09-17 01:50:19 -06001249std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001250 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1251 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001252 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001253 shader_module_used_operators operators;
1254
Chris Forbes47567b72017-06-09 12:09:45 -07001255 for (auto id : accessible_ids) {
1256 auto insn = src->get_def(id);
1257 assert(insn != src->end());
1258
1259 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001260 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1261 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001262 auto d = src->get_decorations(insn.word(2));
1263 unsigned set = d.descriptor_set;
1264 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001265
1266 interface_var v = {};
1267 v.id = insn.word(2);
1268 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001269
locke-lunarg25b6c352020-08-06 17:44:18 -06001270 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001271 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001272 if (v.is_writable) *has_writable_descriptor = true;
1273 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001274 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001275 }
1276 }
1277
1278 return out;
1279}
1280
locke-lunargde3f0fa2020-09-10 11:55:31 -06001281void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1282 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1283 const auto struct_it = GetStructType(&src, it, false);
1284 assert(struct_it != src.end());
1285 data.size = 0;
1286
1287 shader_struct_member data1;
1288 uint32_t i = 2;
1289 uint32_t local_offset = 0;
1290 std::vector<uint32_t> offsets;
1291 offsets.resize(struct_it.len() - i);
1292
1293 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1294 for (const auto offset : memberDecorate_offsets) {
1295 const auto member_decorate = src.at(offset);
1296 if (member_decorate.word(1) != struct_it.word(1)) {
1297 continue;
1298 }
1299
1300 offsets[member_decorate.word(2)] = member_decorate.word(4);
1301 }
1302
1303 for (const auto offset : offsets) {
1304 local_offset = offset;
1305 data1 = {};
1306 data1.root = data.root;
1307 data1.offset = local_offset;
1308 auto def_member = src.get_def(struct_it.word(i));
1309
1310 // Array could be multi-dimensional
1311 while (def_member.opcode() == spv::OpTypeArray) {
1312 const auto len_id = def_member.word(3);
1313 const auto def_len = src.get_def(len_id);
1314 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1315 def_member = src.get_def(def_member.word(2));
1316 }
1317
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001318 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001319 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001320 } else if (def_member.opcode() == spv::OpTypePointer) {
1321 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1322 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1323 // that "points to something."
1324 data1.size = 8;
1325 } else {
1326 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1327 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1328 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001329 } else {
1330 if (def_member.opcode() == spv::OpTypeMatrix) {
1331 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1332 def_member = src.get_def(def_member.word(2));
1333 }
1334
1335 if (def_member.opcode() == spv::OpTypeVector) {
1336 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1337 def_member = src.get_def(def_member.word(2));
1338 }
1339
1340 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1341 data1.size = (def_member.word(2) / 8);
1342 }
1343 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1344 if (array_length_hierarchy_szie > 0) {
1345 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1346
1347 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1348 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1349 }
1350 }
1351 data.struct_members.emplace_back(data1);
1352 ++i;
1353 }
1354 uint32_t total_array_length = 1;
1355 for (const auto length : data1.array_length_hierarchy) {
1356 total_array_length *= length;
1357 }
1358 data.size = local_offset + data1.size * total_array_length;
1359}
1360
1361uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1362 int array_indices_size = static_cast<int>(array_indices.size());
1363 if (array_indices_size) {
1364 uint32_t array_index = 0;
1365 uint32_t i = 0;
1366 for (const auto index : array_indices) {
1367 array_index += (data.array_block_size[i] * index);
1368 ++i;
1369 }
1370 offset += (array_index * data.size);
1371 }
1372 return offset;
1373}
1374
1375void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1376 int array_indices_size = static_cast<int>(array_indices.size());
1377 uint32_t block_memory_size = data.size;
1378 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1379 block_memory_size *= data.array_length_hierarchy[i];
1380 }
1381
1382 offset = UpdateOffset(offset, array_indices, data);
1383
1384 uint32_t end = offset + block_memory_size;
1385 auto used_bytes = data.GetUsedbytes();
1386 if (used_bytes->size() < end) {
1387 used_bytes->resize(end, 0);
1388 }
1389 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1390}
1391
1392void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1393 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1394 if (access_chain_word_index < access_chain_it.len()) {
1395 if (data.array_length_hierarchy.size() > array_indices.size()) {
1396 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1397 ++access_chain_word_index;
1398
1399 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1400 array_indices.emplace_back(def_it.word(3));
1401 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1402 } else {
1403 // If it is a variable, set the all array is used.
1404 if (access_chain_word_index < access_chain_it.len()) {
1405 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1406 for (uint32_t i = 0; i < array_length; ++i) {
1407 auto array_indices2 = array_indices;
1408 array_indices2.emplace_back(i);
1409 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1410 }
1411 } else {
1412 SetUsedBytes(offset, array_indices, data);
1413 }
1414 }
1415 } else {
1416 offset = UpdateOffset(offset, array_indices, data);
1417 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1418 }
1419 } else {
1420 SetUsedBytes(offset, array_indices, data);
1421 }
1422}
1423
1424void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1425 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1426 std::vector<uint32_t> array_indices_emptry;
1427
1428 if (access_chain_word_index < access_chain_it.len()) {
1429 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1430 ++access_chain_word_index;
1431
1432 auto data1 = data.struct_members[strcut_member_index];
1433 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1434 }
1435}
1436
1437void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1438 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1439 for (const auto &func_set : function_set_list) {
1440 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1441 for (auto it = range.first; it != range.second; ++it) {
1442 auto access_chain = src.at(it->second);
1443 if (access_chain.word(3) == variable_id) {
1444 RunUsedStruct(src, 0, 4, access_chain, data);
1445 }
1446 }
1447 }
1448}
1449
1450void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1451 for (auto &entrypoint : src.entry_points) {
1452 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1453 for (auto it = range.first; it != range.second; ++it) {
1454 const auto def_insn = src.at(it->second);
1455
1456 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1457 spirv_inst_iter type = src.get_def(def_insn.word(1));
1458 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1459 std::vector<uint32_t> offsets;
1460
1461 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1462 auto member_decorate = src.at(it2->second);
1463 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1464 offsets.emplace_back(member_decorate.offset());
1465 }
1466 }
1467 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1468 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1469 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1470 entrypoint.second.push_constant_used_in_shader);
1471 }
1472 }
1473 }
1474}
1475
locke-lunarg96dc9632020-06-10 17:22:18 -06001476std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1477 const VkPipelineShaderStageCreateInfo &stage_info) {
1478 std::unordered_set<uint32_t> location_list;
1479 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1480 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1481 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1482 std::unordered_set<unsigned> store_members;
1483 std::unordered_map<unsigned, unsigned> accesschain_members;
1484
1485 for (auto insn : module) {
1486 switch (insn.opcode()) {
1487 case spv::OpStore:
1488 case spv::OpAtomicStore: {
1489 store_members.insert(insn.word(1)); // object id or AccessChain id
1490 break;
1491 }
1492 case spv::OpAccessChain: {
1493 // 2: AccessChain id, 3: object id
1494 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1495 break;
1496 }
1497 default:
1498 break;
1499 }
1500 }
1501 if (store_members.empty()) {
1502 return location_list;
1503 }
1504 for (auto output : outputs) {
1505 auto store_it = store_members.find(output.second.id);
1506 if (store_it != store_members.end()) {
1507 location_list.insert(output.first.first);
1508 store_members.erase(store_it);
1509 continue;
1510 }
1511 store_it = store_members.begin();
1512 while (store_it != store_members.end()) {
1513 auto accesschain_it = accesschain_members.find(*store_it);
1514 if (accesschain_it == accesschain_members.end()) {
1515 ++store_it;
1516 continue;
1517 }
1518 if (accesschain_it->second == output.second.id) {
1519 location_list.insert(output.first.first);
1520 store_members.erase(store_it);
1521 accesschain_members.erase(accesschain_it);
1522 break;
1523 }
1524 ++store_it;
1525 }
1526 }
1527 return location_list;
1528}
1529
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001530bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001531 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1532 // be specified only once.
1533 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1534 bool skip = false;
1535
1536 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1537 auto desc = &vi->pVertexBindingDescriptions[i];
1538 auto &binding = bindings[desc->binding];
1539 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001540 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001541 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1542 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001543 } else {
1544 binding = desc;
1545 }
1546 }
1547
1548 return skip;
1549}
1550
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001551bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1552 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001553 bool skip = false;
1554
Petr Kraus25810d02019-08-27 17:41:15 +02001555 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001556
1557 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001558 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001559 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001560 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1561 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1562 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001563 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1564 }
1565 }
1566 }
1567
Petr Kraus25810d02019-08-27 17:41:15 +02001568 struct AttribInputPair {
1569 const VkVertexInputAttributeDescription *attrib = nullptr;
1570 const interface_var *input = nullptr;
1571 };
1572 std::map<uint32_t, AttribInputPair> location_map;
1573 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1574 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001575
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001576 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001577 const auto location = location_it.first;
1578 const auto attrib = location_it.second.attrib;
1579 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001580
Petr Kraus25810d02019-08-27 17:41:15 +02001581 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001582 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1583 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001584 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001585 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1586 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001587 } else if (attrib && input) {
1588 const auto attrib_type = GetFormatType(attrib->format);
1589 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001590
1591 // Type checking
1592 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001593 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1594 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1595 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001596 }
Petr Kraus25810d02019-08-27 17:41:15 +02001597 } else { // !attrib && !input
1598 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001599 }
1600 }
1601
1602 return skip;
1603}
1604
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001605bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1606 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001607 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001608
Petr Kraus25810d02019-08-27 17:41:15 +02001609 const auto rpci = pipeline->rp_state->createInfo.ptr();
1610
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001611 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001612 const VkAttachmentReference2 *reference = nullptr;
1613 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001614 const interface_var *output = nullptr;
1615 };
1616 std::map<uint32_t, Attachment> location_map;
1617
Petr Kraus25810d02019-08-27 17:41:15 +02001618 const auto subpass = rpci->pSubpasses[subpass_index];
1619 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001620 auto const &reference = subpass.pColorAttachments[i];
1621 location_map[i].reference = &reference;
1622 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1623 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1624 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001625 }
1626 }
1627
Chris Forbes47567b72017-06-09 12:09:45 -07001628 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1629
Petr Kraus25810d02019-08-27 17:41:15 +02001630 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001631 for (const auto &output_it : outputs) {
1632 auto const location = output_it.first.first;
1633 location_map[location].output = &output_it.second;
1634 }
Chris Forbes47567b72017-06-09 12:09:45 -07001635
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001636 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1637 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001638
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001639 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001640 const auto reference = location_it.second.reference;
1641 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1642 continue;
1643 }
1644
Petr Kraus25810d02019-08-27 17:41:15 +02001645 const auto location = location_it.first;
1646 const auto attachment = location_it.second.attachment;
1647 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001648 if (attachment && !output) {
1649 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001650 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1651 "Attachment %" PRIu32
1652 " not written by fragment shader; undefined values will be written to attachment",
1653 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001654 }
1655 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001656 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001657 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1658 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001659 }
Petr Kraus25810d02019-08-27 17:41:15 +02001660 } else if (attachment && output) {
1661 const auto attachment_type = GetFormatType(attachment->format);
1662 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001663
1664 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001665 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001666 skip |=
1667 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1668 "Attachment %" PRIu32
1669 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1670 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001671 }
Petr Kraus25810d02019-08-27 17:41:15 +02001672 } else { // !attachment && !output
1673 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001674 }
1675 }
1676
Petr Kraus25810d02019-08-27 17:41:15 +02001677 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001678 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1679 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1680 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001681 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1682 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001683 }
1684
Chris Forbes47567b72017-06-09 12:09:45 -07001685 return skip;
1686}
1687
Tobias Hector6663c9b2020-11-05 10:18:02 +00001688// 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 -06001689// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001690static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001691 auto type = builtin_instr.opcode();
1692 uint32_t target_id = builtin_instr.word(1);
1693 bool init_complete = false;
1694
1695 if (type == spv::OpMemberDecorate) {
1696 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1697 auto insn = entrypoint;
1698 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1699 switch (insn.opcode()) {
1700 case spv::OpTypePointer:
1701 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1702 target_id = insn.word(1);
1703 }
1704 break;
1705 case spv::OpVariable:
1706 if (insn.word(1) == target_id) {
1707 target_id = insn.word(2);
1708 init_complete = true;
1709 }
1710 break;
1711 }
1712 insn++;
1713 }
1714 }
1715
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001716 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1717
1718 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001719 std::unordered_set<uint32_t> worklist;
1720 worklist.insert(entrypoint.word(2));
1721
1722 // Follow instructions in call graph looking for writes to target
1723 while (!worklist.empty() && !found_write) {
1724 auto id_iter = worklist.begin();
1725 auto id = *id_iter;
1726 worklist.erase(id_iter);
1727
1728 auto insn = src->get_def(id);
1729 if (insn == src->end()) {
1730 continue;
1731 }
1732
1733 if (insn.opcode() == spv::OpFunction) {
1734 // Scan body of function looking for other function calls or items in our ID chain
1735 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1736 switch (insn.opcode()) {
1737 case spv::OpAccessChain:
1738 if (insn.word(3) == target_id) {
1739 if (type == spv::OpMemberDecorate) {
1740 auto value = GetConstantValue(src, insn.word(4));
1741 if (value == builtin_instr.word(2)) {
1742 target_id = insn.word(2);
1743 }
1744 } else {
1745 target_id = insn.word(2);
1746 }
1747 }
1748 break;
1749 case spv::OpStore:
1750 if (insn.word(1) == target_id) {
1751 found_write = true;
1752 }
1753 break;
1754 case spv::OpFunctionCall:
1755 worklist.insert(insn.word(3));
1756 break;
1757 }
1758 }
1759 }
1760 }
1761 return found_write;
1762}
1763
Chris Forbes47567b72017-06-09 12:09:45 -07001764// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1765// important for identifying the set of shader resources actually used by an entrypoint, for example.
1766// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1767// - NOT the shader input/output interfaces.
1768//
1769// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1770// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001771std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001772 std::unordered_set<uint32_t> ids;
1773 std::unordered_set<uint32_t> worklist;
1774 worklist.insert(entrypoint.word(2));
1775
1776 while (!worklist.empty()) {
1777 auto id_iter = worklist.begin();
1778 auto id = *id_iter;
1779 worklist.erase(id_iter);
1780
1781 auto insn = src->get_def(id);
1782 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001783 // 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 -07001784 // that we may not care about.
1785 continue;
1786 }
1787
1788 // Try to add to the output set
1789 if (!ids.insert(id).second) {
1790 continue; // If we already saw this id, we don't want to walk it again.
1791 }
1792
1793 switch (insn.opcode()) {
1794 case spv::OpFunction:
1795 // Scan whole body of the function, enlisting anything interesting
1796 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1797 switch (insn.opcode()) {
1798 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001799 worklist.insert(insn.word(3)); // ptr
1800 break;
1801 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001802 worklist.insert(insn.word(1)); // ptr
1803 break;
1804 case spv::OpAccessChain:
1805 case spv::OpInBoundsAccessChain:
1806 worklist.insert(insn.word(3)); // base ptr
1807 break;
1808 case spv::OpSampledImage:
1809 case spv::OpImageSampleImplicitLod:
1810 case spv::OpImageSampleExplicitLod:
1811 case spv::OpImageSampleDrefImplicitLod:
1812 case spv::OpImageSampleDrefExplicitLod:
1813 case spv::OpImageSampleProjImplicitLod:
1814 case spv::OpImageSampleProjExplicitLod:
1815 case spv::OpImageSampleProjDrefImplicitLod:
1816 case spv::OpImageSampleProjDrefExplicitLod:
1817 case spv::OpImageFetch:
1818 case spv::OpImageGather:
1819 case spv::OpImageDrefGather:
1820 case spv::OpImageRead:
1821 case spv::OpImage:
1822 case spv::OpImageQueryFormat:
1823 case spv::OpImageQueryOrder:
1824 case spv::OpImageQuerySizeLod:
1825 case spv::OpImageQuerySize:
1826 case spv::OpImageQueryLod:
1827 case spv::OpImageQueryLevels:
1828 case spv::OpImageQuerySamples:
1829 case spv::OpImageSparseSampleImplicitLod:
1830 case spv::OpImageSparseSampleExplicitLod:
1831 case spv::OpImageSparseSampleDrefImplicitLod:
1832 case spv::OpImageSparseSampleDrefExplicitLod:
1833 case spv::OpImageSparseSampleProjImplicitLod:
1834 case spv::OpImageSparseSampleProjExplicitLod:
1835 case spv::OpImageSparseSampleProjDrefImplicitLod:
1836 case spv::OpImageSparseSampleProjDrefExplicitLod:
1837 case spv::OpImageSparseFetch:
1838 case spv::OpImageSparseGather:
1839 case spv::OpImageSparseDrefGather:
1840 case spv::OpImageTexelPointer:
1841 worklist.insert(insn.word(3)); // Image or sampled image
1842 break;
1843 case spv::OpImageWrite:
1844 worklist.insert(insn.word(1)); // Image -- different operand order to above
1845 break;
1846 case spv::OpFunctionCall:
1847 for (uint32_t i = 3; i < insn.len(); i++) {
1848 worklist.insert(insn.word(i)); // fn itself, and all args
1849 }
1850 break;
1851
1852 case spv::OpExtInst:
1853 for (uint32_t i = 5; i < insn.len(); i++) {
1854 worklist.insert(insn.word(i)); // Operands to ext inst
1855 }
1856 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001857
1858 default: {
1859 if (AtomicOperation(insn.opcode())) {
1860 if (insn.opcode() == spv::OpAtomicStore) {
1861 worklist.insert(insn.word(1)); // ptr
1862 } else {
1863 worklist.insert(insn.word(3)); // ptr
1864 }
1865 }
1866 break;
1867 }
Chris Forbes47567b72017-06-09 12:09:45 -07001868 }
1869 }
1870 break;
1871 }
1872 }
1873
1874 return ids;
1875}
1876
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001877PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1878 const shader_struct_member &push_constant_used_in_shader,
1879 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001880 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001881 const auto used_bytes_size = used_bytes->size();
1882 if (used_bytes_size == 0) return PC_Byte_Updated;
1883
1884 const auto push_constant_data_update_size = push_constant_data_update.size();
1885 const auto *data = push_constant_data_update.data();
1886 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1887 if (used_bytes_size <= push_constant_data_update_size) {
1888 return PC_Byte_Updated;
1889 }
1890 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1891
1892 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1893 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1894 return PC_Byte_Updated;
1895 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001896 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001897
locke-lunargde3f0fa2020-09-10 11:55:31 -06001898 uint32_t i = 0;
1899 for (const auto used : *used_bytes) {
1900 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001901 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001902 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001903 return PC_Byte_Not_Set;
1904 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001905 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001906 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001907 }
1908 }
1909 ++i;
1910 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001911 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001912}
1913
1914bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1915 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001916 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001917 // 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 -06001918 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1919 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1920 return skip;
1921 }
1922 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001923
locke-lunargde3f0fa2020-09-10 11:55:31 -06001924 bool found_stage = false;
1925 for (auto const &range : *push_constant_ranges) {
1926 if (range.stageFlags & pStage->stage) {
1927 found_stage = true;
1928 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001929 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001930 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001931 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001932 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001933 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001934 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001935 const auto ret =
1936 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001937
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001938 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001939 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1940 LogObjectList objlist(src->vk_shader_module);
1941 objlist.add(pipeline.pipeline_layout->layout);
1942 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1943 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1944 string_VkShaderStageFlags(pStage->stage).c_str(),
1945 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1946 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001947 }
1948 }
1949 }
1950
locke-lunargde3f0fa2020-09-10 11:55:31 -06001951 if (!found_stage) {
1952 LogObjectList objlist(src->vk_shader_module);
1953 objlist.add(pipeline.pipeline_layout->layout);
1954 skip |= LogError(
1955 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1956 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1957 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001958 }
Chris Forbes47567b72017-06-09 12:09:45 -07001959 return skip;
1960}
1961
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001962bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1963 VkShaderStageFlagBits stage) const {
1964 bool skip = false;
1965
1966 // Currently all builtin tested are only found in fragment shaders
1967 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1968 return skip;
1969 }
1970
1971 for (const auto id : accessible_ids) {
1972 auto insn = src->get_def(id);
1973 const decoration_set decorations = src->get_decorations(insn.word(2));
1974
1975 // Built-ins are obtained from OpVariable
1976 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1977 auto type_pointer = src->get_def(insn.word(1));
1978 assert(type_pointer.opcode() == spv::OpTypePointer);
1979
1980 auto type = src->get_def(type_pointer.word(3));
1981 if (type.opcode() == spv::OpTypeArray) {
1982 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1983
1984 switch (decorations.builtin) {
1985 case spv::BuiltInSampleMask:
1986 // Handles both the input and output sampleMask
1987 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1988 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1989 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1990 "maxSampleMaskWords of %u in %s.",
1991 length, phys_dev_props.limits.maxSampleMaskWords,
1992 report_data->FormatHandle(src->vk_shader_module).c_str());
1993 }
1994 break;
1995 }
1996 }
1997 }
1998 }
1999
2000 return skip;
2001}
2002
Chris Forbes47567b72017-06-09 12:09:45 -07002003// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002004bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002005 bool skip = false;
2006
2007 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2008
2009 if (spec) {
2010 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002011 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002012 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2013 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2014 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2015 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2016 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002017
2018 continue;
2019 }
Chris Forbes47567b72017-06-09 12:09:45 -07002020 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002021 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2022 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2023 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2024 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2025 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002026 }
2027 }
2028 }
2029
2030 return skip;
2031}
2032
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002033// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002034static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2035 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002036 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002037 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002038 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002039 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002040
2041 // 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 -05002042 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2043 if (type.opcode() == spv::OpTypeRuntimeArray) {
2044 descriptor_count = 0;
2045 type = module->get_def(type.word(2));
2046 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002047 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002048 type = module->get_def(type.word(2));
2049 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002050 if (type.word(2) == spv::StorageClassStorageBuffer) {
2051 is_storage_buffer = true;
2052 }
Chris Forbes47567b72017-06-09 12:09:45 -07002053 type = module->get_def(type.word(3));
2054 }
2055 }
2056
2057 switch (type.opcode()) {
2058 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002059 for (auto insn : module->decoration_inst) {
2060 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002061 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002062 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002063 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2064 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2065 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002066 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002067 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2068 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2069 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2070 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002071 }
Chris Forbes47567b72017-06-09 12:09:45 -07002072 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002073 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2074 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2075 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002076 }
2077 }
2078 }
2079
2080 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002081 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002082 }
2083
2084 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002085 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2086 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2087 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002088
Chris Forbes73c00bf2018-06-22 16:28:06 -07002089 case spv::OpTypeSampledImage: {
2090 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2091 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2092 auto image_type = module->get_def(type.word(2));
2093 auto dim = image_type.word(3);
2094 auto sampled = image_type.word(7);
2095 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002096 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2097 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002098 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002099 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002100 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2101 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002102
2103 case spv::OpTypeImage: {
2104 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2105 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2106 auto dim = type.word(3);
2107 auto sampled = type.word(7);
2108
2109 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002110 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2111 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002112 } else if (dim == spv::DimBuffer) {
2113 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002114 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2115 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002116 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002117 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2118 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002119 }
2120 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002121 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2122 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2123 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002124 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002125 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2126 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002127 }
2128 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002129 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002130 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2131 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002132 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002133
2134 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2135 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002136 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002137 }
2138}
2139
Jeff Bolze54ae892018-09-08 12:16:29 -05002140static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002141 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002142 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2143 if (ss.tellp()) ss << ", ";
2144 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002145 }
2146 return ss.str();
2147}
2148
sfricke-samsung0065ce02020-12-03 22:46:37 -08002149bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002150 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002151 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 -05002152 return true;
2153 }
2154 }
2155
2156 return false;
2157}
2158
sfricke-samsung0065ce02020-12-03 22:46:37 -08002159bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002160 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002161 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002162 return true;
2163 }
2164 }
2165
2166 return false;
2167}
2168
locke-lunarg63e4daf2020-08-17 17:53:25 -06002169bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2170 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002171 bool skip = false;
2172
locke-lunarg63e4daf2020-08-17 17:53:25 -06002173 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002174 switch (stage) {
2175 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002176 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2177 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2178 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2179 case VK_SHADER_STAGE_MISS_BIT_NV:
2180 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2181 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2182 case VK_SHADER_STAGE_TASK_BIT_NV:
2183 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002184 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002185 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002186 break;
2187 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002188 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2189 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002190 break;
2191 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002192 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2193 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002194 break;
2195 }
2196 }
2197
Chris Forbes47567b72017-06-09 12:09:45 -07002198 return skip;
2199}
2200
sfricke-samsung94167ca2021-02-26 04:14:59 -08002201bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2202 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002203 bool skip = false;
2204
sfricke-samsung94167ca2021-02-26 04:14:59 -08002205 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2206 if (GroupOperation(insn.opcode()) == true) {
2207 // Check the quad operations.
2208 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2209 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2210 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2211 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2212 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002213 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002214 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002215
sfricke-samsung94167ca2021-02-26 04:14:59 -08002216 uint32_t scope_type = spv::ScopeMax;
2217 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2218 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2219 scope_type = spv::ScopeSubgroup;
2220 } else {
2221 // "All <id> used for Scope <id> must be of an OpConstant"
2222 auto scope_id = module->get_def(insn.word(3));
2223 scope_type = scope_id.word(3);
2224 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002225
sfricke-samsung94167ca2021-02-26 04:14:59 -08002226 if (scope_type == spv::ScopeSubgroup) {
2227 // "Group operations with subgroup scope" must have stage support
2228 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2229 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002230 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002231 }
2232
2233 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2234 auto type = module->get_def(insn.word(1));
2235
2236 if (type.opcode() == spv::OpTypeVector) {
2237 // Get the element type
2238 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002239 }
2240
sfricke-samsung94167ca2021-02-26 04:14:59 -08002241 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002242 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2243 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002244
sfricke-samsung0065ce02020-12-03 22:46:37 -08002245 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2246 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2247 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2248 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2249 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002250 }
2251 }
2252 }
Jeff Bolzee743412019-06-20 22:24:32 -05002253 }
2254
2255 return skip;
2256}
2257
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002258bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002259 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002260 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2261 pStage->stage == VK_SHADER_STAGE_ALL) {
2262 return false;
2263 }
2264
2265 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002266 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002267
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002268 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002269 struct Variable {
2270 uint32_t baseTypePtrID;
2271 uint32_t ID;
2272 uint32_t storageClass;
2273 };
2274 std::vector<Variable> variables;
2275
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002276 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002277 bool is_iso_lines = false;
2278 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002279
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002280 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002281
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002282 for (auto insn : *src) {
2283 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002284 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002285 case spv::OpDecorate:
2286 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002287 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002288 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002289 break;
2290 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002291 default:
2292 break;
2293 }
2294 break;
2295 // Find all input and output variables
2296 case spv::OpVariable: {
2297 Variable var = {};
2298 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002299 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2300 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002301 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002302 var.baseTypePtrID = insn.word(1);
2303 var.ID = insn.word(2);
2304 variables.push_back(var);
2305 }
2306 break;
2307 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002308 case spv::OpExecutionMode:
2309 if (insn.word(1) == entrypoint.word(2)) {
2310 switch (insn.word(2)) {
2311 default:
2312 break;
2313 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002314 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002315 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002316 case spv::ExecutionModeIsolines:
2317 is_iso_lines = true;
2318 break;
2319 case spv::ExecutionModePointMode:
2320 is_point_mode = true;
2321 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002322 }
2323 }
2324 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002325 default:
2326 break;
2327 }
2328 }
2329
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002330 bool strip_output_array_level =
2331 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2332 bool strip_input_array_level =
2333 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2334 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2335
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002336 uint32_t num_comp_in = 0, num_comp_out = 0;
2337 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002338
2339 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2340 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2341
2342 // Find max component location used for input variables.
2343 for (auto &var : inputs) {
2344 int location = var.first.first;
2345 int component = var.first.second;
2346 interface_var &iv = var.second;
2347
2348 // Only need to look at the first location, since we use the type's whole size
2349 if (iv.offset != 0) {
2350 continue;
2351 }
2352
2353 if (iv.is_patch) {
2354 continue;
2355 }
2356
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002357 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2358 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002359 }
2360
2361 // Find max component location used for output variables.
2362 for (auto &var : outputs) {
2363 int location = var.first.first;
2364 int component = var.first.second;
2365 interface_var &iv = var.second;
2366
2367 // Only need to look at the first location, since we use the type's whole size
2368 if (iv.offset != 0) {
2369 continue;
2370 }
2371
2372 if (iv.is_patch) {
2373 continue;
2374 }
2375
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002376 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2377 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002378 }
2379
2380 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2381 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002382 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002383 // Check if the variable is a patch. Patches can also be members of blocks,
2384 // but if they are then the top-level arrayness has already been stripped
2385 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002386 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002387
2388 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002389 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002390 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002391 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002392 }
2393 }
2394
2395 switch (pStage->stage) {
2396 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002397 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002398 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2399 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2400 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2401 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002402 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002403 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002404 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002405 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2406 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2407 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2408 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002409 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002410 break;
2411
2412 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002413 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002414 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2415 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2416 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2417 "components by %u components",
2418 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002419 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002420 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002421 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002422 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002423 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2424 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2425 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2426 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002427 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002429 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2430 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2431 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2432 "components by %u components",
2433 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002435 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002436 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002437 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002438 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2439 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2440 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2441 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002442 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002443 break;
2444
2445 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002446 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002447 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2448 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2449 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2450 "components by %u components",
2451 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002452 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002453 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002454 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002455 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002456 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2457 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2458 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2459 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002460 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002461 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002462 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2463 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2464 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2465 "components by %u components",
2466 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002467 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002468 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002469 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002470 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002471 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2472 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2473 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2474 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002475 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002476 // Portability validation
2477 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2478 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2479 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2480 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2481 " is using abstract patch type IsoLines, but this is not supported on this platform");
2482 }
2483 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2484 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2485 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2486 " is using abstract patch type PointMode, but this is not supported on this platform");
2487 }
2488 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002489 break;
2490
2491 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002493 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2494 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2495 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2496 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002497 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002498 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002499 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002500 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2501 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2502 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2503 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002504 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002505 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002506 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2507 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2508 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2509 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002510 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002511 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002512 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002513 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2514 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2515 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2516 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002517 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002518 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002519 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2520 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2521 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2522 "components by %u components",
2523 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002524 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002525 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002526 break;
2527
2528 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002529 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002530 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2531 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2532 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2533 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002534 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002535 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002536 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002537 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2538 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2539 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2540 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002541 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002542 break;
2543
Jeff Bolz148d94e2018-12-13 21:25:56 -06002544 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2545 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2546 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2547 case VK_SHADER_STAGE_MISS_BIT_NV:
2548 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2549 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2550 case VK_SHADER_STAGE_TASK_BIT_NV:
2551 case VK_SHADER_STAGE_MESH_BIT_NV:
2552 break;
2553
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002554 default:
2555 assert(false); // This should never happen
2556 }
2557 return skip;
2558}
2559
sfricke-samsungdc96f302020-03-18 20:42:10 -07002560bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2561 bool skip = false;
2562 uint32_t total_resources = 0;
2563
2564 // Only currently testing for graphics and compute pipelines
2565 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2566 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2567 return false;
2568 }
2569
2570 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2571 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2572 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2573 }
2574
2575 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2576 // input from CreatePipeline and CreatePipelineLayout level
2577 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2578 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2579 continue;
2580 }
2581
2582 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2583 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2584 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2585 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2586 // Check only descriptor types listed in maxPerStageResources description in spec
2587 switch (binding->descriptorType) {
2588 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2589 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2590 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2591 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2592 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2593 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2594 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2595 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2596 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2597 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2598 total_resources += binding->descriptorCount;
2599 break;
2600 default:
2601 break;
2602 }
2603 }
2604 }
2605 }
2606
2607 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2608 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2609 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2610 skip |= LogError(pipeline->pipeline, vuid,
2611 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2612 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2613 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2614 }
2615
2616 return skip;
2617}
2618
Jeff Bolze4356752019-03-07 11:23:46 -06002619// copy the specialization constant value into buf, if it is present
2620void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2621 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2622
2623 if (spec && spec_id < spec->mapEntryCount) {
2624 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2625 }
2626}
2627
2628// Fill in value with the constant or specialization constant value, if available.
2629// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002630static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002631 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2632 auto type_id = src->get_def(insn.word(1));
2633 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2634 return false;
2635 }
2636 switch (insn.opcode()) {
2637 case spv::OpSpecConstant:
2638 *value = insn.word(3);
2639 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2640 return true;
2641 case spv::OpConstant:
2642 *value = insn.word(3);
2643 return true;
2644 default:
2645 return false;
2646 }
2647}
2648
2649// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002650VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002651 switch (insn.opcode()) {
2652 case spv::OpTypeInt:
2653 switch (insn.word(2)) {
2654 case 8:
2655 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2656 case 16:
2657 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2658 case 32:
2659 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2660 case 64:
2661 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2662 default:
2663 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2664 }
2665 case spv::OpTypeFloat:
2666 switch (insn.word(2)) {
2667 case 16:
2668 return VK_COMPONENT_TYPE_FLOAT16_NV;
2669 case 32:
2670 return VK_COMPONENT_TYPE_FLOAT32_NV;
2671 case 64:
2672 return VK_COMPONENT_TYPE_FLOAT64_NV;
2673 default:
2674 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2675 }
2676 default:
2677 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2678 }
2679}
2680
2681// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2682// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002683bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002684 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002685 bool skip = false;
2686
2687 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2688 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2689 // Map SPIR-V result ID to the ID of its type.
2690 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2691
2692 struct CoopMatType {
2693 uint32_t scope, rows, cols;
2694 VkComponentTypeNV component_type;
2695 bool all_constant;
2696
2697 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2698
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002699 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002700 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2701 spirv_inst_iter insn = src->get_def(id);
2702 uint32_t component_type_id = insn.word(2);
2703 uint32_t scope_id = insn.word(3);
2704 uint32_t rows_id = insn.word(4);
2705 uint32_t cols_id = insn.word(5);
2706 auto component_type_iter = src->get_def(component_type_id);
2707 auto scope_iter = src->get_def(scope_id);
2708 auto rows_iter = src->get_def(rows_id);
2709 auto cols_iter = src->get_def(cols_id);
2710
2711 all_constant = true;
2712 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2713 all_constant = false;
2714 }
2715 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2716 all_constant = false;
2717 }
2718 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2719 all_constant = false;
2720 }
2721 component_type = GetComponentType(component_type_iter, src);
2722 }
2723 };
2724
2725 bool seen_coopmat_capability = false;
2726
2727 for (auto insn : *src) {
2728 // Whitelist instructions whose result can be a cooperative matrix type, and
2729 // keep track of their types. It would be nice if SPIRV-Headers generated code
2730 // to identify which instructions have a result type and result id. Lacking that,
2731 // this whitelist is based on the set of instructions that
2732 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2733 switch (insn.opcode()) {
2734 case spv::OpLoad:
2735 case spv::OpCooperativeMatrixLoadNV:
2736 case spv::OpCooperativeMatrixMulAddNV:
2737 case spv::OpSNegate:
2738 case spv::OpFNegate:
2739 case spv::OpIAdd:
2740 case spv::OpFAdd:
2741 case spv::OpISub:
2742 case spv::OpFSub:
2743 case spv::OpFDiv:
2744 case spv::OpSDiv:
2745 case spv::OpUDiv:
2746 case spv::OpMatrixTimesScalar:
2747 case spv::OpConstantComposite:
2748 case spv::OpCompositeConstruct:
2749 case spv::OpConvertFToU:
2750 case spv::OpConvertFToS:
2751 case spv::OpConvertSToF:
2752 case spv::OpConvertUToF:
2753 case spv::OpUConvert:
2754 case spv::OpSConvert:
2755 case spv::OpFConvert:
2756 id_to_type_id[insn.word(2)] = insn.word(1);
2757 break;
2758 default:
2759 break;
2760 }
2761
2762 switch (insn.opcode()) {
2763 case spv::OpDecorate:
2764 if (insn.word(2) == spv::DecorationSpecId) {
2765 id_to_spec_id[insn.word(1)] = insn.word(3);
2766 }
2767 break;
2768 case spv::OpCapability:
2769 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2770 seen_coopmat_capability = true;
2771
2772 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002773 skip |= LogError(
2774 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2775 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2776 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002777 }
2778 }
2779 break;
2780 case spv::OpMemoryModel:
2781 // If the capability isn't enabled, don't bother with the rest of this function.
2782 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2783 if (!seen_coopmat_capability) {
2784 return skip;
2785 }
2786 break;
2787 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002788 CoopMatType m;
2789 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002790
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002791 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002792 // Validate that the type parameters are all supported for one of the
2793 // operands of a cooperative matrix property.
2794 bool valid = false;
2795 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002796 if (cooperative_matrix_properties[i].AType == m.component_type &&
2797 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2798 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002799 valid = true;
2800 break;
2801 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002802 if (cooperative_matrix_properties[i].BType == m.component_type &&
2803 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2804 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002805 valid = true;
2806 break;
2807 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002808 if (cooperative_matrix_properties[i].CType == m.component_type &&
2809 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2810 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002811 valid = true;
2812 break;
2813 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002814 if (cooperative_matrix_properties[i].DType == m.component_type &&
2815 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2816 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002817 valid = true;
2818 break;
2819 }
2820 }
2821 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002822 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2823 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2824 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002825 }
2826 }
2827 break;
2828 }
2829 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002830 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002831 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2832 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2833 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2834 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002835 // Couldn't find type of matrix
2836 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002837 break;
2838 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002839 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2840 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2841 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2842 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002843
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002844 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002845 // Validate that the type parameters are all supported for the same
2846 // cooperative matrix property.
2847 bool valid = false;
2848 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002849 if (cooperative_matrix_properties[i].AType == a.component_type &&
2850 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2851 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002852
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002853 cooperative_matrix_properties[i].BType == b.component_type &&
2854 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2855 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002856
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002857 cooperative_matrix_properties[i].CType == c.component_type &&
2858 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2859 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002860
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002861 cooperative_matrix_properties[i].DType == d.component_type &&
2862 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2863 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002864 valid = true;
2865 break;
2866 }
2867 }
2868 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002869 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2870 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2871 "VkCooperativeMatrixPropertiesNV",
2872 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002873 }
2874 }
2875 break;
2876 }
2877 default:
2878 break;
2879 }
2880 }
2881
2882 return skip;
2883}
2884
John Zulaufac4c6e12019-07-01 16:05:58 -06002885bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002886 auto entrypoint_id = entrypoint.word(2);
2887
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002888 // The first denorm execution mode encountered, along with its bit width.
2889 // Used to check if SeparateDenormSettings is respected.
2890 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002891
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002892 // The first rounding mode encountered, along with its bit width.
2893 // Used to check if SeparateRoundingModeSettings is respected.
2894 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002895
2896 bool skip = false;
2897
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002898 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002899 uint32_t invocations = 0;
2900
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002901 auto it = src->execution_mode_inst.find(entrypoint_id);
2902 if (it != src->execution_mode_inst.end()) {
2903 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002904 auto mode = insn.word(2);
2905 switch (mode) {
2906 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2907 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002908 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2909 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2910 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002911 skip |= LogError(
2912 device, kVUID_Core_Shader_FeatureNotEnabled,
2913 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2914 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002915 }
2916 break;
2917 }
2918
2919 case spv::ExecutionModeDenormPreserve: {
2920 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002921 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2922 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2923 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002924 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2925 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2926 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002927 }
2928
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002929 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2930 // Register the first denorm execution mode found
2931 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002932 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002933 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002934 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002935 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002936 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2937 "Shader uses different denorm execution modes for 16 and 64-bit but "
2938 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002939 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002940 }
2941 break;
2942
Mike Schuchardt2df08912020-12-15 16:28:09 -08002943 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002944 break;
2945
Mike Schuchardt2df08912020-12-15 16:28:09 -08002946 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002947 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2948 "Shader uses different denorm execution modes for different bit widths but "
2949 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002950 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002951 break;
2952
2953 default:
2954 break;
2955 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002956 }
2957 break;
2958 }
2959
2960 case spv::ExecutionModeDenormFlushToZero: {
2961 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002962 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2963 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2964 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002965 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2966 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2967 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002968 }
2969
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002970 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2971 // Register the first denorm execution mode found
2972 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002973 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002974 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002975 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002976 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002977 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2978 "Shader uses different denorm execution modes for 16 and 64-bit but "
2979 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002980 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002981 }
2982 break;
2983
Mike Schuchardt2df08912020-12-15 16:28:09 -08002984 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002985 break;
2986
Mike Schuchardt2df08912020-12-15 16:28:09 -08002987 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002988 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2989 "Shader uses different denorm execution modes for different bit widths but "
2990 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002991 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002992 break;
2993
2994 default:
2995 break;
2996 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002997 }
2998 break;
2999 }
3000
3001 case spv::ExecutionModeRoundingModeRTE: {
3002 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003003 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3004 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3005 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003006 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3007 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3008 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003009 }
3010
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003011 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3012 // Register the first rounding mode found
3013 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003014 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003015 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003016 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003017 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003018 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3019 "Shader uses different rounding modes for 16 and 64-bit but "
3020 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003021 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003022 }
3023 break;
3024
Mike Schuchardt2df08912020-12-15 16:28:09 -08003025 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003026 break;
3027
Mike Schuchardt2df08912020-12-15 16:28:09 -08003028 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003029 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3030 "Shader uses different rounding modes for different bit widths but "
3031 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003032 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003033 break;
3034
3035 default:
3036 break;
3037 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003038 }
3039 break;
3040 }
3041
3042 case spv::ExecutionModeRoundingModeRTZ: {
3043 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003044 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3045 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3046 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003047 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3048 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3049 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003050 }
3051
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003052 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3053 // Register the first rounding mode found
3054 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003055 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003056 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003057 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003058 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003059 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3060 "Shader uses different rounding modes for 16 and 64-bit but "
3061 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003062 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003063 }
3064 break;
3065
Mike Schuchardt2df08912020-12-15 16:28:09 -08003066 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003067 break;
3068
Mike Schuchardt2df08912020-12-15 16:28:09 -08003069 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003070 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3071 "Shader uses different rounding modes for different bit widths but "
3072 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003073 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003074 break;
3075
3076 default:
3077 break;
3078 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003079 }
3080 break;
3081 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003082
3083 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003084 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003085 break;
3086 }
3087
3088 case spv::ExecutionModeInvocations: {
3089 invocations = insn.word(3);
3090 break;
3091 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003092 }
3093 }
3094 }
3095
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003096 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003097 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003098 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3099 "Geometry shader entry point must have an OpExecutionMode instruction that "
3100 "specifies a maximum output vertex count that is greater than 0 and less "
3101 "than or equal to maxGeometryOutputVertices. "
3102 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003103 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003104 }
3105
3106 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003107 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3108 "Geometry shader entry point must have an OpExecutionMode instruction that "
3109 "specifies an invocation count that is greater than 0 and less "
3110 "than or equal to maxGeometryShaderInvocations. "
3111 "Invocations=%d, maxGeometryShaderInvocations=%d",
3112 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003113 }
3114 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003115 return skip;
3116}
3117
locke-lunargd9a069d2019-09-17 01:50:19 -06003118uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003119 auto type = module->get_def(type_id);
3120
3121 while (true) {
3122 switch (type.opcode()) {
3123 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003124 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003125 case spv::OpTypeSampledImage:
3126 type = module->get_def(type.word(2));
3127 break;
3128 case spv::OpTypePointer:
3129 type = module->get_def(type.word(3));
3130 break;
3131 case spv::OpTypeImage: {
3132 auto dim = type.word(3);
3133 auto arrayed = type.word(5);
3134 auto msaa = type.word(6);
3135
Chris Forbes74ba2232018-08-27 15:19:27 -07003136 uint32_t bits = 0;
3137 switch (GetFundamentalType(module, type.word(2))) {
3138 case FORMAT_TYPE_FLOAT:
3139 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3140 break;
3141 case FORMAT_TYPE_UINT:
3142 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3143 break;
3144 case FORMAT_TYPE_SINT:
3145 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3146 break;
3147 default:
3148 break;
3149 }
3150
Chris Forbes47567b72017-06-09 12:09:45 -07003151 switch (dim) {
3152 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003153 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3154 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003155 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003156 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3157 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3158 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003159 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003160 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3161 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003162 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003163 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3164 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003165 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003166 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3167 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003168 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003169 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003170 }
3171 }
3172 default:
3173 return 0;
3174 }
3175 }
3176}
3177
3178// For given pipelineLayout verify that the set_layout_node at slot.first
3179// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003180static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003181 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003182 if (!pipelineLayout) return nullptr;
3183
3184 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3185
3186 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3187}
3188
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003189int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3190 if (module == nullptr) return -1;
3191
3192 auto type = module->get_def(resource.type_id);
3193 while (true) {
3194 switch (type.opcode()) {
3195 case spv::OpTypeSampledImage:
3196 type = module->get_def(type.word(2));
3197 break;
3198 case spv::OpTypePointer:
3199 type = module->get_def(type.word(3));
3200 break;
3201 case spv::OpTypeImage:
3202 return type.word(3);
3203 default:
3204 return -1;
3205 }
3206 }
3207}
3208
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003209// Because the following is legal, need the entry point
3210// OpEntryPoint GLCompute %main "name_a"
3211// OpEntryPoint GLCompute %main "name_b"
3212bool FindLocalSize(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, uint32_t &local_size_x,
3213 uint32_t &local_size_y, uint32_t &local_size_z) {
3214 auto entrypoint_id = entrypoint.word(2);
3215 auto it = src->execution_mode_inst.find(entrypoint_id);
3216 if (it != src->execution_mode_inst.end()) {
3217 for (auto insn : it->second) {
3218 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
3219 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
3220 assert(insn.opcode() == spv::OpExecutionMode);
3221 if (insn.word(2) == spv::ExecutionModeLocalSize) {
3222 local_size_x = insn.word(3);
3223 local_size_y = insn.word(4);
3224 local_size_z = insn.word(5);
3225 return true;
Locke1ec6d952019-04-02 11:57:21 -06003226 }
3227 }
3228 }
3229 return false;
3230}
3231
locke-lunargd9a069d2019-09-17 01:50:19 -06003232void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003233 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003234 bool is_point_mode = false;
3235
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003236 auto it = src->execution_mode_inst.find(entrypoint_id);
3237 if (it != src->execution_mode_inst.end()) {
3238 for (auto insn : it->second) {
Chris Forbes0771b672018-03-22 21:13:46 -07003239 switch (insn.word(2)) {
3240 case spv::ExecutionModePointMode:
3241 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3242 is_point_mode = true;
3243 break;
3244
3245 case spv::ExecutionModeOutputPoints:
3246 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3247 break;
3248
3249 case spv::ExecutionModeIsolines:
3250 case spv::ExecutionModeOutputLineStrip:
3251 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3252 break;
3253
3254 case spv::ExecutionModeTriangles:
3255 case spv::ExecutionModeQuads:
3256 case spv::ExecutionModeOutputTriangleStrip:
3257 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3258 break;
3259 }
3260 }
3261 }
3262
3263 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3264}
3265
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003266// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3267// o If there is only a vertex shader : gl_PointSize must be written when using points
3268// o If there is a geometry or tessellation shader:
3269// - If shaderTessellationAndGeometryPointSize feature is enabled:
3270// * gl_PointSize must be written in the final geometry stage
3271// - If shaderTessellationAndGeometryPointSize feature is disabled:
3272// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003273bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003274 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003275 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3276 return false;
3277 }
3278
3279 bool pointsize_written = false;
3280 bool skip = false;
3281
3282 // Search for PointSize built-in decorations
3283 std::vector<uint32_t> pointsize_builtin_offsets;
3284 spirv_inst_iter insn = entrypoint;
3285 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3286 if (insn.opcode() == spv::OpMemberDecorate) {
3287 if (insn.word(3) == spv::DecorationBuiltIn) {
3288 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003289 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003290 }
3291 }
3292 } else if (insn.opcode() == spv::OpDecorate) {
3293 if (insn.word(2) == spv::DecorationBuiltIn) {
3294 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003295 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003296 }
3297 }
3298 }
3299
3300 insn++;
3301 }
3302
3303 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003304 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003305 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003306 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3307 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3308 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003309 }
3310 } else if (!pointsize_written) {
3311 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003312 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3313 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3314 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003315 }
3316 return skip;
3317}
John Zulauf14c355b2019-06-27 16:09:37 -06003318
Tobias Hector6663c9b2020-11-05 10:18:02 +00003319bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3320 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3321 bool primitiverate_written = false;
3322 bool viewportindex_written = false;
3323 bool viewportmask_written = false;
3324 bool skip = false;
3325
3326 // Check if the primitive shading rate is written
3327 spirv_inst_iter insn = entrypoint;
3328 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3329 if (insn.opcode() == spv::OpMemberDecorate) {
3330 if (insn.word(3) == spv::DecorationBuiltIn) {
3331 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3332 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3333 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3334 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3335 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3336 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3337 }
3338 }
3339 } else if (insn.opcode() == spv::OpDecorate) {
3340 if (insn.word(2) == spv::DecorationBuiltIn) {
3341 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3342 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3343 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3344 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3345 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3346 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3347 }
3348 }
3349 }
3350
3351 insn++;
3352 }
3353
Tony-LunarGd44844c2021-01-22 13:24:37 -07003354 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3355 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003356 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3357 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003358 skip |= LogError(pipeline->pipeline,
3359 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3360 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3361 "multiple viewports "
3362 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3363 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003364 }
3365
3366 if (primitiverate_written && viewportindex_written) {
3367 skip |= LogError(pipeline->pipeline,
3368 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3369 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3370 "ViewportIndex built-ins,"
3371 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3372 string_VkShaderStageFlagBits(stage));
3373 }
3374
3375 if (primitiverate_written && viewportmask_written) {
3376 skip |= LogError(pipeline->pipeline,
3377 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3378 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3379 "ViewportMaskNV built-ins,"
3380 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3381 string_VkShaderStageFlagBits(stage));
3382 }
3383 }
3384 return skip;
3385}
3386
sfricke-samsung486a51e2021-01-02 00:10:15 -08003387// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003388bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003389 bool skip = false;
3390
sfricke-samsung94167ca2021-02-26 04:14:59 -08003391 switch (insn.opcode()) {
3392 case spv::OpReadClockKHR: {
3393 auto scope_id = module->get_def(insn.word(3));
3394 auto scope_type = scope_id.word(3);
3395 // if scope isn't Subgroup or Device, spirv-val will catch
3396 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3397 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3398 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3399 report_data->FormatHandle(module->vk_shader_module).c_str());
3400 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3401 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3402 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3403 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003404 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003405 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003406 }
3407 }
3408 return skip;
3409}
3410
John Zulauf14c355b2019-06-27 16:09:37 -06003411bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3412 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003413 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003414 bool skip = false;
3415
3416 // Check the module
3417 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003418 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3419 "%s does not contain valid spirv for stage %s.",
3420 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003421 }
3422
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003423 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3424 // specializations should be applied and validated.
3425 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3426 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3427 // Gather the specialization-constant values.
3428 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003429 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003430 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3431 id_value_map.reserve(specialization_info->mapEntryCount);
3432 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3433 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003434
Jeremy Hayes521221d2020-01-15 16:48:49 -07003435 // Expect only scalar types.
3436 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3437 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3438 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003439 }
3440
3441 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003442 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003443 spvtools::Optimizer optimizer(spirv_environment);
3444 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3445 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003446 skip |= LogError(
3447 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003448 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3449 };
3450 optimizer.SetMessageConsumer(consumer);
3451 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3452 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3453 std::vector<uint32_t> specialized_spirv;
3454 auto const optimized =
3455 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3456 assert(optimized == true);
3457
3458 if (optimized) {
3459 spv_context ctx = spvContextCreate(spirv_environment);
3460 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3461 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003462 spvtools::ValidatorOptions options;
3463 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003464 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3465 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003466 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003467 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3468 report_data->FormatHandle(module->vk_shader_module).c_str(),
3469 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003470 }
3471
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003472 spvDiagnosticDestroy(diag);
3473 spvContextDestroy(ctx);
3474 }
3475 }
3476
John Zulauf14c355b2019-06-27 16:09:37 -06003477 // Check the entrypoint
3478 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003479 skip |=
3480 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3481 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003482 }
3483 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3484
3485 // Mark accessible ids
3486 auto &accessible_ids = stage_state.accessible_ids;
3487
Chris Forbes47567b72017-06-09 12:09:45 -07003488 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003489 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3490 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003491
sfricke-samsung94167ca2021-02-26 04:14:59 -08003492 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3493 // and mainly only checking the instruction in detail for a single operation
3494 for (auto insn : *module) {
3495 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3496 skip |= ValidatePropertiesAndFeatures(module, insn);
3497 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3498 }
3499
locke-lunarg63e4daf2020-08-17 17:53:25 -06003500 skip |=
3501 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003502 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003503 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003504 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003505 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003506 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003507 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003508 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003509 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003510 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003511 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003512 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3513 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3514 }
Chris Forbes47567b72017-06-09 12:09:45 -07003515
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003516 std::string vuid_layout_mismatch;
3517 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3518 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3519 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3520 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3521 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3522 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3523 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3524 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3525 }
3526
Chris Forbes47567b72017-06-09 12:09:45 -07003527 // Validate descriptor use
3528 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003529 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003530 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003531 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003532 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3533 std::set<uint32_t> descriptor_types =
3534 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003535
3536 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003537 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003538 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3539 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003540 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003541 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003542 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3543 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003544 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003545 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003546 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3547 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3548 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003549 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003550 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003551 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3552 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003553 }
3554 }
3555
3556 // Validate use of input attachments against subpass structure
3557 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003558 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003559
Petr Krause91f7a12017-12-14 20:57:36 +01003560 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003561 auto subpass = pipeline->graphicsPipelineCI.subpass;
3562
3563 for (auto use : input_attachment_uses) {
3564 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3565 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003566 ? input_attachments[use.first].attachment
3567 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003568
3569 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003570 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3571 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003572 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003573 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003574 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3575 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3576 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003577 }
3578 }
3579 }
Lockeaa8fdc02019-04-02 11:59:20 -06003580 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003581 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06003582 }
Chris Forbes47567b72017-06-09 12:09:45 -07003583 return skip;
3584}
3585
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003586bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3587 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3588 spirv_inst_iter consumer_entrypoint,
3589 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003590 bool skip = false;
3591
3592 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003593 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3594 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003595
3596 auto a_it = outputs.begin();
3597 auto b_it = inputs.begin();
3598
3599 // Maps sorted by key (location); walk them together to find mismatches
3600 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3601 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3602 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3603 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3604 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3605
3606 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003607 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3608 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3609 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003610 a_it++;
3611 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003612 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3613 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3614 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003615 b_it++;
3616 } else {
3617 // subtleties of arrayed interfaces:
3618 // - if is_patch, then the member is not arrayed, even though the interface may be.
3619 // - if is_block_member, then the extra array level of an arrayed interface is not
3620 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003621 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3622 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3623 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003624 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3625 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3626 DescribeType(producer, a_it->second.type_id).c_str(),
3627 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003628 }
3629 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003630 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3631 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3632 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3633 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003634 }
3635 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003636 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3637 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3638 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003639 }
3640 a_it++;
3641 b_it++;
3642 }
3643 }
3644
Ari Suonpaa696b3432019-03-11 14:02:57 +02003645 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3646 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3647 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3648
3649 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3650 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003651 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3652 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003653 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3654 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003655 } else {
3656 auto it_producer = builtins_producer.begin();
3657 auto it_consumer = builtins_consumer.begin();
3658 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3659 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003660 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3661 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3662 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003663 break;
3664 }
3665 it_producer++;
3666 it_consumer++;
3667 }
3668 }
3669 }
3670 }
3671
Chris Forbes47567b72017-06-09 12:09:45 -07003672 return skip;
3673}
3674
John Zulauf14c355b2019-06-27 16:09:37 -06003675static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003676 uint32_t stage_mask = 0;
3677 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3678 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3679 stage_mask |= pCreateInfo->pStages[i].stage;
3680 }
3681 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003682 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3683 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3684 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003685 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3686 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3687 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3688 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3689 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003690 }
3691 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003692 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003693}
3694
Chris Forbes47567b72017-06-09 12:09:45 -07003695// Validate that the shaders used by the given pipeline and store the active_slots
3696// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003697bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003698 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003699 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3700 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003701
John Zulauf14c355b2019-06-27 16:09:37 -06003702 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003703 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003704 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003705 bool skip = false;
3706
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003707 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003708
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003709 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3710 auto stage = &create_info->pStages[i];
3711 auto stage_id = GetShaderStageId(stage->stage);
3712 shaders[stage_id] = GetShaderModuleState(stage->module);
3713 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3714 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3715 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003716 }
3717
3718 // if the shader stages are no good individually, cross-stage validation is pointless.
3719 if (skip) return true;
3720
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003721 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003722
3723 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003724 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003725 }
3726
3727 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003728 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003729 }
3730
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003731 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3732 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003733
3734 while (!shaders[producer] && producer != fragment_stage) {
3735 producer++;
3736 consumer++;
3737 }
3738
3739 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3740 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003741 if (shaders[consumer]) {
3742 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003743 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3744 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003745 }
Chris Forbes47567b72017-06-09 12:09:45 -07003746
3747 producer = consumer;
3748 }
3749 }
3750
3751 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003752 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003753 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003754 }
3755
3756 return skip;
3757}
3758
Tony-LunarGb2ded512021-02-02 16:03:30 -07003759void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3760 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3761
3762 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3763 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3764 return;
3765 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003766
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003767 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3768 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003769 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003770
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003771 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3772 auto stage = &create_info->pStages[i];
3773 auto stage_id = GetShaderStageId(stage->stage);
3774 shaders[stage_id] = GetShaderModuleState(stage->module);
3775 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003776
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003777 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3778 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003779 spirv_inst_iter insn = entrypoints[stage_id];
3780 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003781
Tony-LunarGb2ded512021-02-02 16:03:30 -07003782 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3783 if (insn.opcode() == spv::OpMemberDecorate) {
3784 if (insn.word(3) == spv::DecorationBuiltIn) {
3785 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3786 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003787 }
3788 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003789 } else if (insn.opcode() == spv::OpDecorate) {
3790 if (insn.word(2) == spv::DecorationBuiltIn) {
3791 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3792 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3793 }
3794 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003795 }
3796
Tony-LunarGb2ded512021-02-02 16:03:30 -07003797 insn++;
3798 }
3799 if (primitiverate_written) {
3800 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3801 }
3802 }
3803 }
3804}
3805
3806bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3807 const char *caller, const DrawDispatchVuid &vuid) const {
3808 auto create_info = pipeline->graphicsPipelineCI.ptr();
3809 bool skip = false;
3810
3811 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3812 auto stage = &create_info->pStages[i];
3813 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3814 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3815 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3816 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3817 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003818 skip |=
3819 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3820 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3821 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3822 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003823 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003824 }
3825 }
3826 }
3827 }
3828
3829 return skip;
3830}
3831
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003832bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003833 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003834
John Zulauf14c355b2019-06-27 16:09:37 -06003835 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3836 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003837
John Zulauf14c355b2019-06-27 16:09:37 -06003838 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003839}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003840
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003841uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3842 uint32_t total = 0;
3843
3844 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3845 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3846 if (stages[stage_index].stage == stageBit) {
3847 total++;
3848 }
3849 }
3850
3851 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3852 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3853 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3854 total += CalcShaderStageCount(library_pipeline, stageBit);
3855 }
3856 }
3857
3858 return total;
3859}
3860
sourav parmarcd5fb182020-07-17 12:58:44 -07003861bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003862 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003863
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003864 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003865 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3866 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3867 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3868 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3869 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3870 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3871 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003872 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003873 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3874 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003877 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003878 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3879 skip |= LogError(
3880 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3881 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3882 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003883 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003884 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3885 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003886 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3887 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003888 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003889 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003890 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3891 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3892 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3893 "member must have been created with values of the maxPipelineRayPayloadSize and "
3894 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3895 }
3896 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003897 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003898 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3899 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3900 "vkCreateRayTracingPipelinesKHR: If flags includes "
3901 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3902 "the pLibraries member of libraries must have been created with the "
3903 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3904 }
sourav parmar83c31b12020-05-06 12:30:54 -07003905 }
3906 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003907 } else {
3908 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003909 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3910 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3911 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003912 pipeline->raytracingPipelineCI.maxRecursionDepth,
3913 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3914 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003915 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003916 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3917 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3918
John Zulaufe4474e72019-07-01 17:28:27 -06003919 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003920 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003921
John Zulaufe4474e72019-07-01 17:28:27 -06003922 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3923 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003924
John Zulaufe4474e72019-07-01 17:28:27 -06003925 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003926 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003927
3928 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3929 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3930 if (raygen_stages_count == 0) {
3931 skip |= LogError(
3932 device,
3933 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3934 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3935 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003936 }
3937
3938 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3939 const auto &group = groups[group_index];
3940
3941 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3942 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3943 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3944 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3945 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003946 skip |= LogError(device,
3947 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3948 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3949 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003950 }
3951 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3952 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003953 skip |= LogError(device,
3954 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3955 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3956 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003957 }
3958 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3959 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3960 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003961 skip |= LogError(device,
3962 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3963 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3964 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003965 }
3966 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3967 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003968 skip |= LogError(device,
3969 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3970 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3971 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003972 }
3973 }
3974
3975 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3976 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3977 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3978 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003979 skip |= LogError(device,
3980 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3981 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3982 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003983 }
3984 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3985 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3986 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003987 skip |= LogError(device,
3988 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3989 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3990 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003991 }
3992 }
John Zulaufe4474e72019-07-01 17:28:27 -06003993 }
3994 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003995}
3996
Dave Houltona9df0ce2018-02-07 10:51:23 -07003997uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003998
Dave Houltona9df0ce2018-02-07 10:51:23 -07003999static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07004000 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06004001 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06004002 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07004003 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004004 return nullptr;
4005}
4006
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07004007bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004008 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004009 bool skip = false;
4010 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004011
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06004012 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004013 return false;
4014 }
4015
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06004016 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004017
4018 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004019 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
4020 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
4021 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004022 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004023 auto cache = GetValidationCacheInfo(pCreateInfo);
4024 uint32_t hash = 0;
4025 if (cache) {
4026 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004027 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004028 }
4029
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004030 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4031 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004032 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004033 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004034 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004035 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004036 spvtools::ValidatorOptions options;
4037 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004038 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004039 if (spv_valid != SPV_SUCCESS) {
4040 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004041 if (spv_valid == SPV_WARNING) {
4042 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4043 diag && diag->error ? diag->error : "(no error text)");
4044 } else {
4045 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4046 diag && diag->error ? diag->error : "(no error text)");
4047 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004048 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004049 } else {
4050 if (cache) {
4051 cache->Insert(hash);
4052 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004053 }
4054
4055 spvDiagnosticDestroy(diag);
4056 spvContextDestroy(ctx);
4057 }
4058
Chris Forbes4ae55b32017-06-09 14:42:56 -07004059 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004060}
4061
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004062bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004063 bool skip = false;
4064 uint32_t local_size_x = 0;
4065 uint32_t local_size_y = 0;
4066 uint32_t local_size_z = 0;
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004067 if (FindLocalSize(shader, entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06004068 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004069 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4070 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4071 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4072 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004073 }
4074 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004075 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4076 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4077 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4078 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004079 }
4080 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004081 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4082 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4083 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4084 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004085 }
4086
4087 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4088 uint64_t invocations = local_size_x * local_size_y;
4089 // Prevent overflow.
4090 bool fail = false;
4091 if (invocations > UINT32_MAX || invocations > limit) {
4092 fail = true;
4093 }
4094 if (!fail) {
4095 invocations *= local_size_z;
4096 if (invocations > UINT32_MAX || invocations > limit) {
4097 fail = true;
4098 }
4099 }
4100 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004101 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4102 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4103 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4104 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4105 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004106 }
4107 }
4108 return skip;
4109}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004110
4111spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4112 if (api_version >= VK_API_VERSION_1_2) {
4113 return SPV_ENV_VULKAN_1_2;
4114 } else if (api_version >= VK_API_VERSION_1_1) {
4115 if (spirv_1_4) {
4116 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4117 } else {
4118 return SPV_ENV_VULKAN_1_1;
4119 }
4120 }
4121 return SPV_ENV_VULKAN_1_0;
4122}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004123
4124void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4125 spvtools::ValidatorOptions &options) {
4126 if (device_extensions.vk_khr_relaxed_block_layout) {
4127 options.SetRelaxBlockLayout(true);
4128 }
4129 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4130 options.SetUniformBufferStandardLayout(true);
4131 }
4132 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4133 options.SetScalarBlockLayout(true);
4134 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004135 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4136 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4137 options.SetWorkgroupScalarBlockLayout(true);
4138 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004139}