blob: 47bf83b51e9ed30df5e4c1e2b4afdba3cc84484a [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>
Chris Forbes47567b72017-06-09 12:09:45 -070030#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020031#include <string>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <vector>
33
Mark Lobodzinski102687e2020-04-28 11:03:28 -060034#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070035#include "vk_loader_platform.h"
36#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_layer_data.h"
38#include "vk_layer_extension_utils.h"
39#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070040#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070041#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020042
Chris Forbes4ae55b32017-06-09 14:42:56 -070043#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070044#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070045
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080046void decoration_set::add(uint32_t decoration, uint32_t value) {
47 switch (decoration) {
48 case spv::DecorationLocation:
49 flags |= location_bit;
50 location = value;
51 break;
52 case spv::DecorationPatch:
53 flags |= patch_bit;
54 break;
55 case spv::DecorationRelaxedPrecision:
56 flags |= relaxed_precision_bit;
57 break;
58 case spv::DecorationBlock:
59 flags |= block_bit;
60 break;
61 case spv::DecorationBufferBlock:
62 flags |= buffer_block_bit;
63 break;
64 case spv::DecorationComponent:
65 flags |= component_bit;
66 component = value;
67 break;
68 case spv::DecorationInputAttachmentIndex:
69 flags |= input_attachment_index_bit;
70 input_attachment_index = value;
71 break;
72 case spv::DecorationDescriptorSet:
73 flags |= descriptor_set_bit;
74 descriptor_set = value;
75 break;
76 case spv::DecorationBinding:
77 flags |= binding_bit;
78 binding = value;
79 break;
80 case spv::DecorationNonWritable:
81 flags |= nonwritable_bit;
82 break;
83 case spv::DecorationBuiltIn:
84 flags |= builtin_bit;
85 builtin = value;
86 break;
87 }
88}
89
Chris Forbes47567b72017-06-09 12:09:45 -070090enum FORMAT_TYPE {
91 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
92 FORMAT_TYPE_SINT = 2,
93 FORMAT_TYPE_UINT = 4,
94};
95
96typedef std::pair<unsigned, unsigned> location_t;
97
Chris Forbes47567b72017-06-09 12:09:45 -070098static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +020099 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
100 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
101 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
102 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
103 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700104};
105
John Zulauf14c355b2019-06-27 16:09:37 -0600106unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
107
Chris Forbes47567b72017-06-09 12:09:45 -0700108// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600109void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600110 function_set func_set = {};
111 EntryPoint *entry_point = nullptr;
112
Chris Forbes47567b72017-06-09 12:09:45 -0700113 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600114 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700115 if (func_set.offset) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600116 func_set.op_lists.insert({insn.opcode(), insn.offset()});
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 } else if (entry_point) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600118 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
119 }
120
Chris Forbes47567b72017-06-09 12:09:45 -0700121 switch (insn.opcode()) {
122 // Types
123 case spv::OpTypeVoid:
124 case spv::OpTypeBool:
125 case spv::OpTypeInt:
126 case spv::OpTypeFloat:
127 case spv::OpTypeVector:
128 case spv::OpTypeMatrix:
129 case spv::OpTypeImage:
130 case spv::OpTypeSampler:
131 case spv::OpTypeSampledImage:
132 case spv::OpTypeArray:
133 case spv::OpTypeRuntimeArray:
134 case spv::OpTypeStruct:
135 case spv::OpTypeOpaque:
136 case spv::OpTypePointer:
137 case spv::OpTypeFunction:
138 case spv::OpTypeEvent:
139 case spv::OpTypeDeviceEvent:
140 case spv::OpTypeReserveId:
141 case spv::OpTypeQueue:
142 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600143 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600144 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700145 def_index[insn.word(1)] = insn.offset();
146 break;
147
148 // Fixed constants
149 case spv::OpConstantTrue:
150 case spv::OpConstantFalse:
151 case spv::OpConstant:
152 case spv::OpConstantComposite:
153 case spv::OpConstantSampler:
154 case spv::OpConstantNull:
155 def_index[insn.word(2)] = insn.offset();
156 break;
157
158 // Specialization constants
159 case spv::OpSpecConstantTrue:
160 case spv::OpSpecConstantFalse:
161 case spv::OpSpecConstant:
162 case spv::OpSpecConstantComposite:
163 case spv::OpSpecConstantOp:
164 def_index[insn.word(2)] = insn.offset();
165 break;
166
167 // Variables
168 case spv::OpVariable:
169 def_index[insn.word(2)] = insn.offset();
170 break;
171
172 // Functions
173 case spv::OpFunction:
174 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600175 func_set.id = insn.word(2);
176 func_set.offset = insn.offset();
177 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700178 break;
179
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800180 // Decorations
181 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700182 auto target_id = insn.word(1);
183 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
sfricke-samsung94d71a52021-02-26 05:25:43 -0800184 decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800185 if (insn.word(2) == spv::DecorationBuiltIn) {
186 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
187 }
188
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800189 } break;
190 case spv::OpGroupDecorate: {
191 auto const &src = decorations[insn.word(1)];
192 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
193 } break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800194 case spv::OpMemberDecorate: {
195 member_decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800196 if (insn.word(3) == spv::DecorationBuiltIn) {
197 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
198 }
sfricke-samsung94d71a52021-02-26 05:25:43 -0800199 } break;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800200
John Zulauf14c355b2019-06-27 16:09:37 -0600201 // Entry points ... add to the entrypoint table
202 case spv::OpEntryPoint: {
203 // 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 -0700204 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600205 auto execution_model = insn.word(1);
206 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600207 entry_points.emplace(entrypoint_name,
208 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
209
210 auto range = entry_points.equal_range(entrypoint_name);
211 for (auto it = range.first; it != range.second; ++it) {
212 if (it->second.offset == insn.offset()) {
213 entry_point = &(it->second);
214 break;
215 }
216 }
217 assert(entry_point != nullptr);
218 break;
219 }
220 case spv::OpFunctionEnd: {
221 assert(entry_point != nullptr);
222 func_set.length = insn.offset() - func_set.offset;
223 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600224 break;
225 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800226
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700227 // Copy operations
228 case spv::OpCopyLogical:
229 case spv::OpCopyObject: {
230 def_index[insn.word(2)] = insn.offset();
231 break;
232 }
233
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800234 // Execution Mode
235 case spv::OpExecutionMode: {
236 execution_mode_inst[insn.word(1)].push_back(insn);
237 } break;
238
Chris Forbes47567b72017-06-09 12:09:45 -0700239 default:
240 // We don't care about any other defs for now.
241 break;
242 }
243 }
244}
245
Jeff Bolz105d6492018-09-29 15:46:44 -0500246unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
247 switch (mode) {
248 case spv::ExecutionModelVertex:
249 return VK_SHADER_STAGE_VERTEX_BIT;
250 case spv::ExecutionModelTessellationControl:
251 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
252 case spv::ExecutionModelTessellationEvaluation:
253 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
254 case spv::ExecutionModelGeometry:
255 return VK_SHADER_STAGE_GEOMETRY_BIT;
256 case spv::ExecutionModelFragment:
257 return VK_SHADER_STAGE_FRAGMENT_BIT;
258 case spv::ExecutionModelGLCompute:
259 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600260 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700261 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600262 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700263 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600264 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700265 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600266 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700267 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600268 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700269 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600270 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700271 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500272 case spv::ExecutionModelTaskNV:
273 return VK_SHADER_STAGE_TASK_BIT_NV;
274 case spv::ExecutionModelMeshNV:
275 return VK_SHADER_STAGE_MESH_BIT_NV;
276 default:
277 return 0;
278 }
279}
280
locke-lunargde3f0fa2020-09-10 11:55:31 -0600281const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
282 VkShaderStageFlagBits stageBits) {
283 auto range = src->entry_points.equal_range(name);
284 for (auto it = range.first; it != range.second; ++it) {
285 if (it->second.stage == stageBits) {
286 return &(it->second);
287 }
288 }
289 return nullptr;
290}
291
locke-lunargd9a069d2019-09-17 01:50:19 -0600292spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600293 auto range = src->entry_points.equal_range(name);
294 for (auto it = range.first; it != range.second; ++it) {
295 if (it->second.stage == stageBits) {
296 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700297 }
298 }
Chris Forbes47567b72017-06-09 12:09:45 -0700299 return src->end();
300}
301
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600302static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700303 switch (sc) {
304 case spv::StorageClassInput:
305 return "input";
306 case spv::StorageClassOutput:
307 return "output";
308 case spv::StorageClassUniformConstant:
309 return "const uniform";
310 case spv::StorageClassUniform:
311 return "uniform";
312 case spv::StorageClassWorkgroup:
313 return "workgroup local";
314 case spv::StorageClassCrossWorkgroup:
315 return "workgroup global";
316 case spv::StorageClassPrivate:
317 return "private global";
318 case spv::StorageClassFunction:
319 return "function";
320 case spv::StorageClassGeneric:
321 return "generic";
322 case spv::StorageClassAtomicCounter:
323 return "atomic counter";
324 case spv::StorageClassImage:
325 return "image";
326 case spv::StorageClassPushConstant:
327 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800328 case spv::StorageClassStorageBuffer:
329 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700330 default:
331 return "unknown";
332 }
333}
334
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700335// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
336// Otherwise, returns src->end().
337spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700338 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700339
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700340 // If id is a copy, see where it was copied from
341 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
342 id = value.word(3);
343 value = src->get_def(id);
344 }
345
346 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
347 return value;
348 }
349 return src->end();
350}
351
352// Assumes itr points to an OpConstant instruction
353uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
354
355// Either returns the constant value described by the instruction at id, or 1
356uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
357 auto value = GetConstantDef(src, id);
358
359 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700360 // TODO: Either ensure that the specialization transform is already performed on a module we're
361 // considering here, OR -- specialize on the fly now.
362 return 1;
363 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700364 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700365}
366
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600367static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700368 auto insn = src->get_def(type);
369 assert(insn != src->end());
370
371 switch (insn.opcode()) {
372 case spv::OpTypeBool:
373 ss << "bool";
374 break;
375 case spv::OpTypeInt:
376 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
377 break;
378 case spv::OpTypeFloat:
379 ss << "float" << insn.word(2);
380 break;
381 case spv::OpTypeVector:
382 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600383 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700384 break;
385 case spv::OpTypeMatrix:
386 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600387 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700388 break;
389 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600390 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
391 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700392 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700393 case spv::OpTypeRuntimeArray:
394 ss << "runtime arr[] of ";
395 DescribeTypeInner(ss, src, insn.word(2));
396 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700397 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600398 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
399 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700400 break;
401 case spv::OpTypeStruct: {
402 ss << "struct of (";
403 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600404 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700405 if (i == insn.len() - 1) {
406 ss << ")";
407 } else {
408 ss << ", ";
409 }
410 }
411 break;
412 }
413 case spv::OpTypeSampler:
414 ss << "sampler";
415 break;
416 case spv::OpTypeSampledImage:
417 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600418 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700419 break;
420 case spv::OpTypeImage:
421 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
422 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600423 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500424 ss << "accelerationStruture";
425 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700426 default:
427 ss << "oddtype";
428 break;
429 }
430}
431
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600432static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700433 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600434 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700435 return ss.str();
436}
437
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600438static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700439 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
440 return type.word(2) < 64;
441}
442
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600443static 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 -0600444 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700445 // Walk two type trees together, and complain about differences
446 auto a_insn = a->get_def(a_type);
447 auto b_insn = b->get_def(b_type);
448 assert(a_insn != a->end());
449 assert(b_insn != b->end());
450
Chris Forbes062f1222018-08-21 15:34:15 -0700451 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
452
Chris Forbes47567b72017-06-09 12:09:45 -0700453 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600454 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700455 }
456
457 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
458 // 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 -0600459 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700460 }
461
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600462 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
463 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700464 }
465
466 if (a_insn.opcode() != b_insn.opcode()) {
467 return false;
468 }
469
470 if (a_insn.opcode() == spv::OpTypePointer) {
471 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600472 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700473 }
474
475 if (a_arrayed || b_arrayed) {
476 // If we havent resolved array-of-verts by here, we're not going to.
477 return false;
478 }
479
480 switch (a_insn.opcode()) {
481 case spv::OpTypeBool:
482 return true;
483 case spv::OpTypeInt:
484 // Match on width, signedness
485 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
486 case spv::OpTypeFloat:
487 // Match on width
488 return a_insn.word(2) == b_insn.word(2);
489 case spv::OpTypeVector:
490 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600491 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
492 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700493 return a_insn.word(3) >= b_insn.word(3);
494 } else {
495 return a_insn.word(3) == b_insn.word(3);
496 }
497 case spv::OpTypeMatrix:
498 // Match on element type, count.
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) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700500 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700501 case spv::OpTypeArray:
502 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
503 // 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 -0600504 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
505 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700506 case spv::OpTypeStruct:
507 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700508 {
509 if (a_insn.len() != b_insn.len()) {
510 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700511 }
Chris Forbes47567b72017-06-09 12:09:45 -0700512
Dave Houltona9df0ce2018-02-07 10:51:23 -0700513 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600514 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700515 return false;
516 }
517 }
518
519 return true;
520 }
Chris Forbes47567b72017-06-09 12:09:45 -0700521 default:
522 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
523 return false;
524 }
525}
526
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600527static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700528 auto insn = src->get_def(type);
529 assert(insn != src->end());
530
531 switch (insn.opcode()) {
532 case spv::OpTypePointer:
533 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
534 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600535 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700536 case spv::OpTypeArray:
537 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600538 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700539 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600540 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700541 }
542 case spv::OpTypeMatrix:
543 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600544 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700545 case spv::OpTypeVector: {
546 auto scalar_type = src->get_def(insn.word(2));
547 auto bit_width =
548 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
549
550 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
551 return (bit_width * insn.word(3) + 127) / 128;
552 }
553 default:
554 // Everything else is just 1.
555 return 1;
556
557 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
558 }
559}
560
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600561static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200562 auto insn = src->get_def(type);
563 assert(insn != src->end());
564
565 switch (insn.opcode()) {
566 case spv::OpTypePointer:
567 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
568 // pointers around.
569 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
570 case spv::OpTypeStruct: {
571 uint32_t sum = 0;
572 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
573 sum += GetComponentsConsumedByType(src, insn.word(i), false);
574 }
575 return sum;
576 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500577 case spv::OpTypeArray:
578 if (strip_array_level) {
579 return GetComponentsConsumedByType(src, insn.word(2), false);
580 } else {
581 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200582 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200583 case spv::OpTypeMatrix:
584 // Num locations is the dimension * element size
585 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
586 case spv::OpTypeVector: {
587 auto scalar_type = src->get_def(insn.word(2));
588 auto bit_width =
589 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
590 // One component is 32-bit
591 return (bit_width * insn.word(3) + 31) / 32;
592 }
593 case spv::OpTypeFloat: {
594 auto bit_width = insn.word(2);
595 return (bit_width + 31) / 32;
596 }
597 case spv::OpTypeInt: {
598 auto bit_width = insn.word(2);
599 return (bit_width + 31) / 32;
600 }
601 case spv::OpConstant:
602 return GetComponentsConsumedByType(src, insn.word(1), false);
603 default:
604 return 0;
605 }
606}
607
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600608static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700609 switch (format) {
610 case VK_FORMAT_R64G64B64A64_SFLOAT:
611 case VK_FORMAT_R64G64B64A64_SINT:
612 case VK_FORMAT_R64G64B64A64_UINT:
613 case VK_FORMAT_R64G64B64_SFLOAT:
614 case VK_FORMAT_R64G64B64_SINT:
615 case VK_FORMAT_R64G64B64_UINT:
616 return 2;
617 default:
618 return 1;
619 }
620}
621
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600622static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700623 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
624 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
625 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
626 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700627 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
628 return FORMAT_TYPE_FLOAT;
629}
630
631// 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 -0700632// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600633static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700634 auto insn = src->get_def(type);
635 assert(insn != src->end());
636
637 switch (insn.opcode()) {
638 case spv::OpTypeInt:
639 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
640 case spv::OpTypeFloat:
641 return FORMAT_TYPE_FLOAT;
642 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700643 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700644 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700645 case spv::OpTypeRuntimeArray:
646 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600647 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700648 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600649 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700650
651 default:
652 return 0;
653 }
654}
655
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600656static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700657 uint32_t bit_pos = uint32_t(u_ffs(stage));
658 return bit_pos - 1;
659}
660
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600661static 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 -0700662 while (true) {
663 if (def.opcode() == spv::OpTypePointer) {
664 def = src->get_def(def.word(3));
665 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
666 def = src->get_def(def.word(2));
667 is_array_of_verts = false;
668 } else if (def.opcode() == spv::OpTypeStruct) {
669 return def;
670 } else {
671 return src->end();
672 }
673 }
674}
675
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600676static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800677 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
678 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700679 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600680 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800681 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700682 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700683 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700684 }
685
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700686 layer_data::unordered_map<unsigned, unsigned> member_components;
687 layer_data::unordered_map<unsigned, unsigned> member_relaxed_precision;
688 layer_data::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700689
690 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800691 for (auto insn : src->member_decoration_inst) {
692 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700693 unsigned member_index = insn.word(2);
694
695 if (insn.word(3) == spv::DecorationComponent) {
696 unsigned component = insn.word(4);
697 member_components[member_index] = component;
698 }
699
700 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
701 member_relaxed_precision[member_index] = 1;
702 }
Chris Forbesa313d772017-06-13 13:59:41 -0700703
704 if (insn.word(3) == spv::DecorationPatch) {
705 member_patch[member_index] = 1;
706 }
Chris Forbes47567b72017-06-09 12:09:45 -0700707 }
708 }
709
Chris Forbesa313d772017-06-13 13:59:41 -0700710 // TODO: correctly handle location assignment from outside
711
Chris Forbes47567b72017-06-09 12:09:45 -0700712 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800713 for (auto insn : src->member_decoration_inst) {
714 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700715 unsigned member_index = insn.word(2);
716 unsigned member_type_id = type.word(2 + member_index);
717
718 if (insn.word(3) == spv::DecorationLocation) {
719 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600720 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700721 auto component_it = member_components.find(member_index);
722 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
723 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700724 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700725
726 for (unsigned int offset = 0; offset < num_locations; offset++) {
727 interface_var v = {};
728 v.id = id;
729 // TODO: member index in interface_var too?
730 v.type_id = member_type_id;
731 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700732 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700733 v.is_block_member = true;
734 v.is_relaxed_precision = is_relaxed_precision;
735 (*out)[std::make_pair(location + offset, component)] = v;
736 }
737 }
738 }
739 }
Chris Forbesa313d772017-06-13 13:59:41 -0700740
741 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700742}
743
Ari Suonpaa696b3432019-03-11 14:02:57 +0200744static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800745 assert(entrypoint.opcode() == spv::OpEntryPoint);
746
Ari Suonpaa696b3432019-03-11 14:02:57 +0200747 std::vector<uint32_t> interfaces;
748 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
749 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
750 uint32_t word = 3;
751 while (entrypoint.word(word) & 0xff000000u) {
752 ++word;
753 }
754 ++word;
755
756 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
757
758 return interfaces;
759}
760
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600761static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600762 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700763 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
764
Chris Forbes47567b72017-06-09 12:09:45 -0700765 std::map<location_t, interface_var> out;
766
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800767 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
768 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700769 assert(insn != src->end());
770 assert(insn.opcode() == spv::OpVariable);
771
772 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800773 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700774 unsigned id = insn.word(2);
775 unsigned type = insn.word(1);
776
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800777 int location = d.location;
778 int builtin = d.builtin;
779 unsigned component = d.component;
780 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
781 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700782
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700783 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700784 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700785 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700786 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
787 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600788 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700789 for (unsigned int offset = 0; offset < num_locations; offset++) {
790 interface_var v = {};
791 v.id = id;
792 v.type_id = type;
793 v.offset = offset;
794 v.is_patch = is_patch;
795 v.is_relaxed_precision = is_relaxed_precision;
796 out[std::make_pair(location + offset, component)] = v;
797 }
Chris Forbes47567b72017-06-09 12:09:45 -0700798 }
799 }
800 }
801
802 return out;
803}
804
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600805static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200806 uint32_t storageClass) {
807 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700808 std::vector<uint32_t> builtin_struct_members;
809 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200810
sfricke-samsung94d71a52021-02-26 05:25:43 -0800811 for (auto insn : src->member_decoration_inst) {
812 if (insn.word(3) == spv::DecorationBuiltIn) {
813 builtin_struct_members.push_back(insn.word(1));
814 }
815 }
816 for (auto insn : src->decoration_inst) {
817 switch (insn.word(2)) {
818 case spv::DecorationBlock: {
819 uint32_t block_id = insn.word(1);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800820 for (auto builtin_block_id : builtin_struct_members) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800821 // Check if one of the members of the block are built-in -> the block is built-in
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800822 if (block_id == builtin_block_id) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800823 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200824 break;
825 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200826 }
827 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800828 }
829 case spv::DecorationBuiltIn:
830 builtin_decorations.push_back(insn.word(1));
831 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200832 default:
833 break;
834 }
835 }
836
837 // Find all interface variables belonging to the entrypoint and matching the storage class
838 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
839 auto def = src->get_def(id);
840 assert(def != src->end());
841 assert(def.opcode() == spv::OpVariable);
842
843 if (def.word(3) == storageClass) variables.push_back(def.word(1));
844 }
845
846 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700847 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200848 for (auto &var : variables) {
849 auto def = src->get_def(src->get_def(var).word(3));
850
851 // It could be an array of IO blocks. The element type should be the struct defining the block contents
852 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
853
854 // Now find all members belonging to the struct defining the IO block
855 if (def.opcode() == spv::OpTypeStruct) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800856 for (auto builtin_id : builtin_decorations) {
857 if (builtin_id == def.word(1)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700858 for (int i = 2; i < static_cast<int>(def.len()); i++) {
859 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
860 }
861 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800862 for (auto insn : src->member_decoration_inst) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800863 if (insn.word(1) == builtin_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700864 auto struct_index = insn.word(2);
865 assert(struct_index < builtin_block_members.size());
866 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200867 }
868 }
869 }
870 }
871 }
872 }
873
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700874 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200875}
876
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600877static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700878 SHADER_MODULE_STATE const *src, layer_data::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700879 std::vector<std::pair<uint32_t, interface_var>> out;
880
sfricke-samsung94d71a52021-02-26 05:25:43 -0800881 for (auto insn : src->decoration_inst) {
882 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
883 auto attachment_index = insn.word(3);
884 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700885
sfricke-samsung94d71a52021-02-26 05:25:43 -0800886 if (accessible_ids.count(id)) {
887 auto def = src->get_def(id);
888 assert(def != src->end());
889 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
890 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
891 for (unsigned int offset = 0; offset < num_locations; offset++) {
892 interface_var v = {};
893 v.id = id;
894 v.type_id = def.word(1);
895 v.offset = offset;
896 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700897 }
898 }
899 }
900 }
901 }
902
903 return out;
904}
905
locke-lunarg25b6c352020-08-06 17:44:18 -0600906static bool AtomicOperation(uint32_t opcode) {
907 switch (opcode) {
908 case spv::OpAtomicLoad:
909 case spv::OpAtomicStore:
910 case spv::OpAtomicExchange:
911 case spv::OpAtomicCompareExchange:
912 case spv::OpAtomicCompareExchangeWeak:
913 case spv::OpAtomicIIncrement:
914 case spv::OpAtomicIDecrement:
915 case spv::OpAtomicIAdd:
916 case spv::OpAtomicISub:
917 case spv::OpAtomicSMin:
918 case spv::OpAtomicUMin:
919 case spv::OpAtomicSMax:
920 case spv::OpAtomicUMax:
921 case spv::OpAtomicAnd:
922 case spv::OpAtomicOr:
923 case spv::OpAtomicXor:
924 case spv::OpAtomicFAddEXT:
925 return true;
926 default:
927 return false;
928 }
929 return false;
930}
931
sfricke-samsung0065ce02020-12-03 22:46:37 -0800932// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
933// covered with VUID 01090
934static bool GroupOperation(uint32_t opcode) {
935 switch (opcode) {
936 case spv::OpGroupNonUniformElect:
937 case spv::OpGroupNonUniformAll:
938 case spv::OpGroupNonUniformAny:
939 case spv::OpGroupNonUniformAllEqual:
940 case spv::OpGroupNonUniformBroadcast:
941 case spv::OpGroupNonUniformBroadcastFirst:
942 case spv::OpGroupNonUniformBallot:
943 case spv::OpGroupNonUniformInverseBallot:
944 case spv::OpGroupNonUniformBallotBitExtract:
945 case spv::OpGroupNonUniformBallotBitCount:
946 case spv::OpGroupNonUniformBallotFindLSB:
947 case spv::OpGroupNonUniformBallotFindMSB:
948 case spv::OpGroupNonUniformShuffle:
949 case spv::OpGroupNonUniformShuffleXor:
950 case spv::OpGroupNonUniformShuffleUp:
951 case spv::OpGroupNonUniformShuffleDown:
952 case spv::OpGroupNonUniformIAdd:
953 case spv::OpGroupNonUniformFAdd:
954 case spv::OpGroupNonUniformIMul:
955 case spv::OpGroupNonUniformFMul:
956 case spv::OpGroupNonUniformSMin:
957 case spv::OpGroupNonUniformUMin:
958 case spv::OpGroupNonUniformFMin:
959 case spv::OpGroupNonUniformSMax:
960 case spv::OpGroupNonUniformUMax:
961 case spv::OpGroupNonUniformFMax:
962 case spv::OpGroupNonUniformBitwiseAnd:
963 case spv::OpGroupNonUniformBitwiseOr:
964 case spv::OpGroupNonUniformBitwiseXor:
965 case spv::OpGroupNonUniformLogicalAnd:
966 case spv::OpGroupNonUniformLogicalOr:
967 case spv::OpGroupNonUniformLogicalXor:
968 case spv::OpGroupNonUniformQuadBroadcast:
969 case spv::OpGroupNonUniformQuadSwap:
970 case spv::OpGroupNonUniformPartitionNV:
971 return true;
972 default:
973 return false;
974 }
975 return false;
976}
977
locke-lunarg12d20992020-09-21 12:46:49 -0600978bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700979 const layer_data::unordered_map<unsigned, unsigned> &load_members,
980 const layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
locke-lunarg12d20992020-09-21 12:46:49 -0600981 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600982 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600983 auto load_it = load_members.find(load_id);
984 if (load_it == load_members.end()) {
985 continue;
986 }
987 if (load_it->second == object_id) {
988 return true;
989 }
990
991 auto accesschain_it = accesschain_members.find(load_it->second);
992 if (accesschain_it == accesschain_members.end()) {
993 continue;
994 }
995 if (accesschain_it->second.first == object_id) {
996 return true;
997 }
998 }
999 return false;
1000}
1001
locke-lunargae2a43c2020-09-22 17:21:57 -06001002bool CheckImageOperandsBiasOffset(uint32_t type) {
1003 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1004 spv::ImageOperandsConstOffsetsMask)
1005 ? true
1006 : false;
1007}
1008
locke-lunargd3da0422020-09-23 01:02:11 -06001009struct shader_module_used_operators {
1010 bool updated;
1011 std::vector<unsigned> imagwrite_members;
1012 std::vector<unsigned> atomic_members;
1013 std::vector<unsigned> store_members;
1014 std::vector<unsigned> atomic_store_members;
1015 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1016 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001017 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001018 layer_data::unordered_map<unsigned, unsigned> load_members;
1019 layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1020 layer_data::unordered_map<unsigned, unsigned> image_texel_pointer_members;
locke-lunargd3da0422020-09-23 01:02:11 -06001021
1022 shader_module_used_operators() : updated(false) {}
1023
1024 void update(SHADER_MODULE_STATE const *module) {
1025 if (updated) return;
1026 updated = true;
1027
1028 for (auto insn : *module) {
1029 switch (insn.opcode()) {
1030 case spv::OpImageSampleImplicitLod:
1031 case spv::OpImageSampleProjImplicitLod:
1032 case spv::OpImageSampleProjExplicitLod:
1033 case spv::OpImageSparseSampleImplicitLod:
1034 case spv::OpImageSparseSampleProjImplicitLod:
1035 case spv::OpImageSparseSampleProjExplicitLod: {
1036 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1037 // ImageOperands in index: 5
1038 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1039 sampler_bias_offset_members.emplace_back(insn.word(3));
1040 }
1041 break;
1042 }
1043 case spv::OpImageSampleDrefImplicitLod:
1044 case spv::OpImageSampleDrefExplicitLod:
1045 case spv::OpImageSampleProjDrefImplicitLod:
1046 case spv::OpImageSampleProjDrefExplicitLod:
1047 case spv::OpImageSparseSampleDrefImplicitLod:
1048 case spv::OpImageSparseSampleDrefExplicitLod:
1049 case spv::OpImageSparseSampleProjDrefImplicitLod:
1050 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1051 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1052 // ImageOperands in index: 6
1053 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1054 sampler_bias_offset_members.emplace_back(insn.word(3));
1055 }
1056 break;
1057 }
1058 case spv::OpImageSampleExplicitLod:
1059 case spv::OpImageSparseSampleExplicitLod: {
1060 // ImageOperands in index: 5
1061 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1062 sampler_bias_offset_members.emplace_back(insn.word(3));
1063 }
1064 break;
1065 }
1066 case spv::OpStore: {
1067 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1068 break;
1069 }
1070 case spv::OpImageWrite: {
1071 imagwrite_members.emplace_back(insn.word(1)); // Load id
1072 break;
1073 }
1074 case spv::OpSampledImage: {
1075 // 3: image load id, 4: sampler load id
1076 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1077 break;
1078 }
1079 case spv::OpLoad: {
1080 // 2: Load id, 3: object id or AccessChain id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001081 load_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001082 break;
1083 }
1084 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001085 if (insn.len() == 4) {
1086 // If it is for struct, the length is only 4.
1087 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001088 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0));
locke-lunarg025daa72020-10-13 11:07:51 -06001089 } else {
1090 // 2: AccessChain id, 3: object id, 4: object id of array index
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001091 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
locke-lunarg025daa72020-10-13 11:07:51 -06001092 }
locke-lunargd3da0422020-09-23 01:02:11 -06001093 break;
1094 }
1095 case spv::OpImageTexelPointer: {
1096 // 2: ImageTexelPointer id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001097 image_texel_pointer_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001098 break;
1099 }
1100 default: {
1101 if (AtomicOperation(insn.opcode())) {
1102 if (insn.opcode() == spv::OpAtomicStore) {
1103 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1104 } else {
1105 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1106 }
1107 }
1108 break;
1109 }
1110 }
1111 }
1112 }
1113};
1114
sfricke-samsung691299b2021-01-01 20:48:48 -08001115// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1116// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001117static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001118 bool is_check_writable, interface_var &out_interface_var,
1119 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001120 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001121 unsigned int id = id_it.word(2);
1122
Chris Forbes8af24522018-03-07 11:37:45 -08001123 auto type = module->get_def(type_id);
1124
1125 // 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 -06001126 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1127 type.opcode() == spv::OpTypeSampledImage) {
1128 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1129 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001130 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001131 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001132 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001133 }
1134 }
Chris Forbes8af24522018-03-07 11:37:45 -08001135 switch (type.opcode()) {
1136 case spv::OpTypeImage: {
1137 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001138 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001139 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001140
locke-lunargd3da0422020-09-23 01:02:11 -06001141 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1142 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001143 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001144 }
1145 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1146 used_operators.accesschain_members)) {
1147 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001148 }
locke-lunargd3da0422020-09-23 01:02:11 -06001149 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1150 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001151 out_interface_var.is_sampler_bias_offset = true;
1152 }
locke-lunargd3da0422020-09-23 01:02:11 -06001153 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1154 used_operators.accesschain_members) ||
1155 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1156 used_operators.accesschain_members)) {
1157 out_interface_var.is_atomic_operation = true;
1158 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001159
locke-lunargd3da0422020-09-23 01:02:11 -06001160 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001161 // Find if image id match.
1162 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001163 auto load_it = used_operators.load_members.find(itp_id.first);
1164 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001165 continue;
1166 } else {
1167 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001168 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1169 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001170 continue;
1171 } else {
1172 if (accesschain_it->second.first != id) {
1173 continue;
1174 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001175
1176 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1177 if (const_itr == module->end()) {
1178 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001179 break;
1180 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001181 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001182 }
1183 }
1184 }
1185 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001186 load_it = used_operators.load_members.find(itp_id.second);
1187 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001188 continue;
1189 } else {
1190 uint32_t sampler_id = load_it->second;
1191 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001192 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001193
locke-lunargd3da0422020-09-23 01:02:11 -06001194 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001195 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1196 if (const_itr == module->end()) {
1197 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001198 break;
1199 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001200 sampler_id = const_itr.offset();
1201 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001202 }
1203 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001204 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1205 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1206 }
1207 out_interface_var.samplers_used_by_image[image_index].emplace(
1208 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001209 }
1210 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001211 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001212 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001213 }
1214
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001215 case spv::OpTypeStruct: {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001216 layer_data::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001217 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001218 for (auto insn : module->member_decoration_inst) {
1219 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001220 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001221 }
1222 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001223
1224 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1225 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001226 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001227 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001228
locke-lunargd3da0422020-09-23 01:02:11 -06001229 for (auto oid : used_operators.store_members) {
1230 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001231 out_interface_var.is_writable = true;
1232 return;
1233 }
locke-lunargd3da0422020-09-23 01:02:11 -06001234 auto accesschain_it = used_operators.accesschain_members.find(oid);
1235 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001236 continue;
1237 }
locke-lunargd3da0422020-09-23 01:02:11 -06001238 if (accesschain_it->second.first == id) {
1239 out_interface_var.is_writable = true;
1240 return;
1241 }
1242 }
1243 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1244 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001245 out_interface_var.is_writable = true;
1246 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001247 }
1248 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001249 }
Chris Forbes8af24522018-03-07 11:37:45 -08001250 }
Chris Forbes8af24522018-03-07 11:37:45 -08001251}
1252
locke-lunargd9a069d2019-09-17 01:50:19 -06001253std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001254 SHADER_MODULE_STATE const *src, layer_data::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
locke-lunarg63e4daf2020-08-17 17:53:25 -06001255 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001256 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001257 shader_module_used_operators operators;
1258
Chris Forbes47567b72017-06-09 12:09:45 -07001259 for (auto id : accessible_ids) {
1260 auto insn = src->get_def(id);
1261 assert(insn != src->end());
1262
1263 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001264 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1265 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001266 auto d = src->get_decorations(insn.word(2));
1267 unsigned set = d.descriptor_set;
1268 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001269
1270 interface_var v = {};
1271 v.id = insn.word(2);
1272 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001273
locke-lunarg25b6c352020-08-06 17:44:18 -06001274 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001275 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001276 if (v.is_writable) *has_writable_descriptor = true;
1277 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001278 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001279 }
1280 }
1281
1282 return out;
1283}
1284
locke-lunargde3f0fa2020-09-10 11:55:31 -06001285void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1286 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1287 const auto struct_it = GetStructType(&src, it, false);
1288 assert(struct_it != src.end());
1289 data.size = 0;
1290
1291 shader_struct_member data1;
1292 uint32_t i = 2;
1293 uint32_t local_offset = 0;
1294 std::vector<uint32_t> offsets;
1295 offsets.resize(struct_it.len() - i);
1296
1297 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1298 for (const auto offset : memberDecorate_offsets) {
1299 const auto member_decorate = src.at(offset);
1300 if (member_decorate.word(1) != struct_it.word(1)) {
1301 continue;
1302 }
1303
1304 offsets[member_decorate.word(2)] = member_decorate.word(4);
1305 }
1306
1307 for (const auto offset : offsets) {
1308 local_offset = offset;
1309 data1 = {};
1310 data1.root = data.root;
1311 data1.offset = local_offset;
1312 auto def_member = src.get_def(struct_it.word(i));
1313
1314 // Array could be multi-dimensional
1315 while (def_member.opcode() == spv::OpTypeArray) {
1316 const auto len_id = def_member.word(3);
1317 const auto def_len = src.get_def(len_id);
1318 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1319 def_member = src.get_def(def_member.word(2));
1320 }
1321
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001322 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001323 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001324 } else if (def_member.opcode() == spv::OpTypePointer) {
1325 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1326 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1327 // that "points to something."
1328 data1.size = 8;
1329 } else {
1330 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1331 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1332 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001333 } else {
1334 if (def_member.opcode() == spv::OpTypeMatrix) {
1335 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1336 def_member = src.get_def(def_member.word(2));
1337 }
1338
1339 if (def_member.opcode() == spv::OpTypeVector) {
1340 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1341 def_member = src.get_def(def_member.word(2));
1342 }
1343
1344 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1345 data1.size = (def_member.word(2) / 8);
1346 }
1347 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1348 if (array_length_hierarchy_szie > 0) {
1349 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1350
1351 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1352 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1353 }
1354 }
1355 data.struct_members.emplace_back(data1);
1356 ++i;
1357 }
1358 uint32_t total_array_length = 1;
1359 for (const auto length : data1.array_length_hierarchy) {
1360 total_array_length *= length;
1361 }
1362 data.size = local_offset + data1.size * total_array_length;
1363}
1364
1365uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1366 int array_indices_size = static_cast<int>(array_indices.size());
1367 if (array_indices_size) {
1368 uint32_t array_index = 0;
1369 uint32_t i = 0;
1370 for (const auto index : array_indices) {
1371 array_index += (data.array_block_size[i] * index);
1372 ++i;
1373 }
1374 offset += (array_index * data.size);
1375 }
1376 return offset;
1377}
1378
1379void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1380 int array_indices_size = static_cast<int>(array_indices.size());
1381 uint32_t block_memory_size = data.size;
1382 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1383 block_memory_size *= data.array_length_hierarchy[i];
1384 }
1385
1386 offset = UpdateOffset(offset, array_indices, data);
1387
1388 uint32_t end = offset + block_memory_size;
1389 auto used_bytes = data.GetUsedbytes();
1390 if (used_bytes->size() < end) {
1391 used_bytes->resize(end, 0);
1392 }
1393 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1394}
1395
1396void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1397 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1398 if (access_chain_word_index < access_chain_it.len()) {
1399 if (data.array_length_hierarchy.size() > array_indices.size()) {
1400 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1401 ++access_chain_word_index;
1402
1403 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1404 array_indices.emplace_back(def_it.word(3));
1405 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1406 } else {
1407 // If it is a variable, set the all array is used.
1408 if (access_chain_word_index < access_chain_it.len()) {
1409 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1410 for (uint32_t i = 0; i < array_length; ++i) {
1411 auto array_indices2 = array_indices;
1412 array_indices2.emplace_back(i);
1413 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1414 }
1415 } else {
1416 SetUsedBytes(offset, array_indices, data);
1417 }
1418 }
1419 } else {
1420 offset = UpdateOffset(offset, array_indices, data);
1421 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1422 }
1423 } else {
1424 SetUsedBytes(offset, array_indices, data);
1425 }
1426}
1427
1428void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1429 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1430 std::vector<uint32_t> array_indices_emptry;
1431
1432 if (access_chain_word_index < access_chain_it.len()) {
1433 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1434 ++access_chain_word_index;
1435
1436 auto data1 = data.struct_members[strcut_member_index];
1437 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1438 }
1439}
1440
1441void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1442 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1443 for (const auto &func_set : function_set_list) {
1444 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1445 for (auto it = range.first; it != range.second; ++it) {
1446 auto access_chain = src.at(it->second);
1447 if (access_chain.word(3) == variable_id) {
1448 RunUsedStruct(src, 0, 4, access_chain, data);
1449 }
1450 }
1451 }
1452}
1453
1454void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1455 for (auto &entrypoint : src.entry_points) {
1456 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1457 for (auto it = range.first; it != range.second; ++it) {
1458 const auto def_insn = src.at(it->second);
1459
1460 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1461 spirv_inst_iter type = src.get_def(def_insn.word(1));
1462 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1463 std::vector<uint32_t> offsets;
1464
1465 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1466 auto member_decorate = src.at(it2->second);
1467 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1468 offsets.emplace_back(member_decorate.offset());
1469 }
1470 }
1471 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1472 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1473 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1474 entrypoint.second.push_constant_used_in_shader);
1475 }
1476 }
1477 }
1478}
1479
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001480layer_data::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
locke-lunarg96dc9632020-06-10 17:22:18 -06001481 const VkPipelineShaderStageCreateInfo &stage_info) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001482 layer_data::unordered_set<uint32_t> location_list;
locke-lunarg96dc9632020-06-10 17:22:18 -06001483 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1484 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1485 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001486 layer_data::unordered_set<unsigned> store_members;
1487 layer_data::unordered_map<unsigned, unsigned> accesschain_members;
locke-lunarg96dc9632020-06-10 17:22:18 -06001488
1489 for (auto insn : module) {
1490 switch (insn.opcode()) {
1491 case spv::OpStore:
1492 case spv::OpAtomicStore: {
1493 store_members.insert(insn.word(1)); // object id or AccessChain id
1494 break;
1495 }
1496 case spv::OpAccessChain: {
1497 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001498 if (insn.word(3)) accesschain_members.emplace(insn.word(2), insn.word(3));
locke-lunarg96dc9632020-06-10 17:22:18 -06001499 break;
1500 }
1501 default:
1502 break;
1503 }
1504 }
1505 if (store_members.empty()) {
1506 return location_list;
1507 }
1508 for (auto output : outputs) {
1509 auto store_it = store_members.find(output.second.id);
1510 if (store_it != store_members.end()) {
1511 location_list.insert(output.first.first);
1512 store_members.erase(store_it);
1513 continue;
1514 }
1515 store_it = store_members.begin();
1516 while (store_it != store_members.end()) {
1517 auto accesschain_it = accesschain_members.find(*store_it);
1518 if (accesschain_it == accesschain_members.end()) {
1519 ++store_it;
1520 continue;
1521 }
1522 if (accesschain_it->second == output.second.id) {
1523 location_list.insert(output.first.first);
1524 store_members.erase(store_it);
1525 accesschain_members.erase(accesschain_it);
1526 break;
1527 }
1528 ++store_it;
1529 }
1530 }
1531 return location_list;
1532}
1533
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001534bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001535 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1536 // be specified only once.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001537 layer_data::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
Chris Forbes47567b72017-06-09 12:09:45 -07001538 bool skip = false;
1539
1540 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1541 auto desc = &vi->pVertexBindingDescriptions[i];
1542 auto &binding = bindings[desc->binding];
1543 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001544 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001545 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1546 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001547 } else {
1548 binding = desc;
1549 }
1550 }
1551
1552 return skip;
1553}
1554
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001555bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1556 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001557 bool skip = false;
1558
Petr Kraus25810d02019-08-27 17:41:15 +02001559 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001560
1561 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001562 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001563 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001564 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1565 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1566 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001567 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1568 }
1569 }
1570 }
1571
Petr Kraus25810d02019-08-27 17:41:15 +02001572 struct AttribInputPair {
1573 const VkVertexInputAttributeDescription *attrib = nullptr;
1574 const interface_var *input = nullptr;
1575 };
1576 std::map<uint32_t, AttribInputPair> location_map;
1577 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1578 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001579
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001580 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001581 const auto location = location_it.first;
1582 const auto attrib = location_it.second.attrib;
1583 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001584
Petr Kraus25810d02019-08-27 17:41:15 +02001585 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001586 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1587 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001588 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001589 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1590 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001591 } else if (attrib && input) {
1592 const auto attrib_type = GetFormatType(attrib->format);
1593 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001594
1595 // Type checking
1596 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001597 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1598 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1599 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001600 }
Petr Kraus25810d02019-08-27 17:41:15 +02001601 } else { // !attrib && !input
1602 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001603 }
1604 }
1605
1606 return skip;
1607}
1608
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001609bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1610 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001611 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001612
Petr Kraus25810d02019-08-27 17:41:15 +02001613 const auto rpci = pipeline->rp_state->createInfo.ptr();
1614
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001615 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001616 const VkAttachmentReference2 *reference = nullptr;
1617 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001618 const interface_var *output = nullptr;
1619 };
1620 std::map<uint32_t, Attachment> location_map;
1621
Petr Kraus25810d02019-08-27 17:41:15 +02001622 const auto subpass = rpci->pSubpasses[subpass_index];
1623 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001624 auto const &reference = subpass.pColorAttachments[i];
1625 location_map[i].reference = &reference;
1626 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1627 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1628 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001629 }
1630 }
1631
Chris Forbes47567b72017-06-09 12:09:45 -07001632 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1633
Petr Kraus25810d02019-08-27 17:41:15 +02001634 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001635 for (const auto &output_it : outputs) {
1636 auto const location = output_it.first.first;
1637 location_map[location].output = &output_it.second;
1638 }
Chris Forbes47567b72017-06-09 12:09:45 -07001639
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001640 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1641 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001642
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001643 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001644 const auto reference = location_it.second.reference;
1645 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1646 continue;
1647 }
1648
Petr Kraus25810d02019-08-27 17:41:15 +02001649 const auto location = location_it.first;
1650 const auto attachment = location_it.second.attachment;
1651 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001652 if (attachment && !output) {
1653 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001654 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1655 "Attachment %" PRIu32
1656 " not written by fragment shader; undefined values will be written to attachment",
1657 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001658 }
1659 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001660 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001661 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1662 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001663 }
Petr Kraus25810d02019-08-27 17:41:15 +02001664 } else if (attachment && output) {
1665 const auto attachment_type = GetFormatType(attachment->format);
1666 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001667
1668 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001669 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001670 skip |=
1671 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1672 "Attachment %" PRIu32
1673 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1674 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001675 }
Petr Kraus25810d02019-08-27 17:41:15 +02001676 } else { // !attachment && !output
1677 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001678 }
1679 }
1680
Petr Kraus25810d02019-08-27 17:41:15 +02001681 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001682 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1683 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1684 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001685 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1686 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001687 }
1688
Chris Forbes47567b72017-06-09 12:09:45 -07001689 return skip;
1690}
1691
Tobias Hector6663c9b2020-11-05 10:18:02 +00001692// 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 -06001693// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001694static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001695 auto type = builtin_instr.opcode();
1696 uint32_t target_id = builtin_instr.word(1);
1697 bool init_complete = false;
1698
1699 if (type == spv::OpMemberDecorate) {
1700 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1701 auto insn = entrypoint;
1702 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1703 switch (insn.opcode()) {
1704 case spv::OpTypePointer:
1705 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1706 target_id = insn.word(1);
1707 }
1708 break;
1709 case spv::OpVariable:
1710 if (insn.word(1) == target_id) {
1711 target_id = insn.word(2);
1712 init_complete = true;
1713 }
1714 break;
1715 }
1716 insn++;
1717 }
1718 }
1719
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001720 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1721
1722 bool found_write = false;
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001723 layer_data::unordered_set<uint32_t> worklist;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001724 worklist.insert(entrypoint.word(2));
1725
1726 // Follow instructions in call graph looking for writes to target
1727 while (!worklist.empty() && !found_write) {
1728 auto id_iter = worklist.begin();
1729 auto id = *id_iter;
1730 worklist.erase(id_iter);
1731
1732 auto insn = src->get_def(id);
1733 if (insn == src->end()) {
1734 continue;
1735 }
1736
1737 if (insn.opcode() == spv::OpFunction) {
1738 // Scan body of function looking for other function calls or items in our ID chain
1739 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1740 switch (insn.opcode()) {
1741 case spv::OpAccessChain:
1742 if (insn.word(3) == target_id) {
1743 if (type == spv::OpMemberDecorate) {
1744 auto value = GetConstantValue(src, insn.word(4));
1745 if (value == builtin_instr.word(2)) {
1746 target_id = insn.word(2);
1747 }
1748 } else {
1749 target_id = insn.word(2);
1750 }
1751 }
1752 break;
1753 case spv::OpStore:
1754 if (insn.word(1) == target_id) {
1755 found_write = true;
1756 }
1757 break;
1758 case spv::OpFunctionCall:
1759 worklist.insert(insn.word(3));
1760 break;
1761 }
1762 }
1763 }
1764 }
1765 return found_write;
1766}
1767
Chris Forbes47567b72017-06-09 12:09:45 -07001768// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1769// important for identifying the set of shader resources actually used by an entrypoint, for example.
1770// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1771// - NOT the shader input/output interfaces.
1772//
1773// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1774// converting parts of this to be generated from the machine-readable spec instead.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001775layer_data::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
1776 layer_data::unordered_set<uint32_t> ids;
1777 layer_data::unordered_set<uint32_t> worklist;
Chris Forbes47567b72017-06-09 12:09:45 -07001778 worklist.insert(entrypoint.word(2));
1779
1780 while (!worklist.empty()) {
1781 auto id_iter = worklist.begin();
1782 auto id = *id_iter;
1783 worklist.erase(id_iter);
1784
1785 auto insn = src->get_def(id);
1786 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001787 // 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 -07001788 // that we may not care about.
1789 continue;
1790 }
1791
1792 // Try to add to the output set
1793 if (!ids.insert(id).second) {
1794 continue; // If we already saw this id, we don't want to walk it again.
1795 }
1796
1797 switch (insn.opcode()) {
1798 case spv::OpFunction:
1799 // Scan whole body of the function, enlisting anything interesting
1800 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1801 switch (insn.opcode()) {
1802 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001803 worklist.insert(insn.word(3)); // ptr
1804 break;
1805 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001806 worklist.insert(insn.word(1)); // ptr
1807 break;
1808 case spv::OpAccessChain:
1809 case spv::OpInBoundsAccessChain:
1810 worklist.insert(insn.word(3)); // base ptr
1811 break;
1812 case spv::OpSampledImage:
1813 case spv::OpImageSampleImplicitLod:
1814 case spv::OpImageSampleExplicitLod:
1815 case spv::OpImageSampleDrefImplicitLod:
1816 case spv::OpImageSampleDrefExplicitLod:
1817 case spv::OpImageSampleProjImplicitLod:
1818 case spv::OpImageSampleProjExplicitLod:
1819 case spv::OpImageSampleProjDrefImplicitLod:
1820 case spv::OpImageSampleProjDrefExplicitLod:
1821 case spv::OpImageFetch:
1822 case spv::OpImageGather:
1823 case spv::OpImageDrefGather:
1824 case spv::OpImageRead:
1825 case spv::OpImage:
1826 case spv::OpImageQueryFormat:
1827 case spv::OpImageQueryOrder:
1828 case spv::OpImageQuerySizeLod:
1829 case spv::OpImageQuerySize:
1830 case spv::OpImageQueryLod:
1831 case spv::OpImageQueryLevels:
1832 case spv::OpImageQuerySamples:
1833 case spv::OpImageSparseSampleImplicitLod:
1834 case spv::OpImageSparseSampleExplicitLod:
1835 case spv::OpImageSparseSampleDrefImplicitLod:
1836 case spv::OpImageSparseSampleDrefExplicitLod:
1837 case spv::OpImageSparseSampleProjImplicitLod:
1838 case spv::OpImageSparseSampleProjExplicitLod:
1839 case spv::OpImageSparseSampleProjDrefImplicitLod:
1840 case spv::OpImageSparseSampleProjDrefExplicitLod:
1841 case spv::OpImageSparseFetch:
1842 case spv::OpImageSparseGather:
1843 case spv::OpImageSparseDrefGather:
1844 case spv::OpImageTexelPointer:
1845 worklist.insert(insn.word(3)); // Image or sampled image
1846 break;
1847 case spv::OpImageWrite:
1848 worklist.insert(insn.word(1)); // Image -- different operand order to above
1849 break;
1850 case spv::OpFunctionCall:
1851 for (uint32_t i = 3; i < insn.len(); i++) {
1852 worklist.insert(insn.word(i)); // fn itself, and all args
1853 }
1854 break;
1855
1856 case spv::OpExtInst:
1857 for (uint32_t i = 5; i < insn.len(); i++) {
1858 worklist.insert(insn.word(i)); // Operands to ext inst
1859 }
1860 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001861
1862 default: {
1863 if (AtomicOperation(insn.opcode())) {
1864 if (insn.opcode() == spv::OpAtomicStore) {
1865 worklist.insert(insn.word(1)); // ptr
1866 } else {
1867 worklist.insert(insn.word(3)); // ptr
1868 }
1869 }
1870 break;
1871 }
Chris Forbes47567b72017-06-09 12:09:45 -07001872 }
1873 }
1874 break;
1875 }
1876 }
1877
1878 return ids;
1879}
1880
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001881PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1882 const shader_struct_member &push_constant_used_in_shader,
1883 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001884 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001885 const auto used_bytes_size = used_bytes->size();
1886 if (used_bytes_size == 0) return PC_Byte_Updated;
1887
1888 const auto push_constant_data_update_size = push_constant_data_update.size();
1889 const auto *data = push_constant_data_update.data();
1890 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1891 if (used_bytes_size <= push_constant_data_update_size) {
1892 return PC_Byte_Updated;
1893 }
1894 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1895
1896 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1897 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1898 return PC_Byte_Updated;
1899 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001900 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001901
locke-lunargde3f0fa2020-09-10 11:55:31 -06001902 uint32_t i = 0;
1903 for (const auto used : *used_bytes) {
1904 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001905 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001906 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001907 return PC_Byte_Not_Set;
1908 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001909 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001910 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001911 }
1912 }
1913 ++i;
1914 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001915 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001916}
1917
1918bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1919 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001920 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001921 // 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 -06001922 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1923 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1924 return skip;
1925 }
1926 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001927
locke-lunargde3f0fa2020-09-10 11:55:31 -06001928 bool found_stage = false;
1929 for (auto const &range : *push_constant_ranges) {
1930 if (range.stageFlags & pStage->stage) {
1931 found_stage = true;
1932 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001933 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001934 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001935 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001936 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001937 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001938 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001939 const auto ret =
1940 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001941
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001942 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001943 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1944 LogObjectList objlist(src->vk_shader_module);
1945 objlist.add(pipeline.pipeline_layout->layout);
1946 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1947 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1948 string_VkShaderStageFlags(pStage->stage).c_str(),
1949 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1950 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001951 }
1952 }
1953 }
1954
locke-lunargde3f0fa2020-09-10 11:55:31 -06001955 if (!found_stage) {
1956 LogObjectList objlist(src->vk_shader_module);
1957 objlist.add(pipeline.pipeline_layout->layout);
1958 skip |= LogError(
1959 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1960 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1961 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001962 }
Chris Forbes47567b72017-06-09 12:09:45 -07001963 return skip;
1964}
1965
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001966bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const layer_data::unordered_set<uint32_t> &accessible_ids,
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001967 VkShaderStageFlagBits stage) const {
1968 bool skip = false;
1969
1970 // Currently all builtin tested are only found in fragment shaders
1971 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1972 return skip;
1973 }
1974
1975 for (const auto id : accessible_ids) {
1976 auto insn = src->get_def(id);
1977 const decoration_set decorations = src->get_decorations(insn.word(2));
1978
1979 // Built-ins are obtained from OpVariable
1980 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1981 auto type_pointer = src->get_def(insn.word(1));
1982 assert(type_pointer.opcode() == spv::OpTypePointer);
1983
1984 auto type = src->get_def(type_pointer.word(3));
1985 if (type.opcode() == spv::OpTypeArray) {
1986 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1987
1988 switch (decorations.builtin) {
1989 case spv::BuiltInSampleMask:
1990 // Handles both the input and output sampleMask
1991 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1992 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1993 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1994 "maxSampleMaskWords of %u in %s.",
1995 length, phys_dev_props.limits.maxSampleMaskWords,
1996 report_data->FormatHandle(src->vk_shader_module).c_str());
1997 }
1998 break;
1999 }
2000 }
2001 }
2002 }
2003
2004 return skip;
2005}
2006
Chris Forbes47567b72017-06-09 12:09:45 -07002007// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002008bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002009 bool skip = false;
2010
2011 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2012
2013 if (spec) {
2014 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002015 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002016 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2017 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2018 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2019 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2020 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002021
2022 continue;
2023 }
Chris Forbes47567b72017-06-09 12:09:45 -07002024 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002025 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2026 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2027 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2028 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2029 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002030 }
2031 }
2032 }
2033
2034 return skip;
2035}
2036
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002037// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002038static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2039 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002040 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002041 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002042 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002043 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002044
2045 // 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 -05002046 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2047 if (type.opcode() == spv::OpTypeRuntimeArray) {
2048 descriptor_count = 0;
2049 type = module->get_def(type.word(2));
2050 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002051 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002052 type = module->get_def(type.word(2));
2053 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002054 if (type.word(2) == spv::StorageClassStorageBuffer) {
2055 is_storage_buffer = true;
2056 }
Chris Forbes47567b72017-06-09 12:09:45 -07002057 type = module->get_def(type.word(3));
2058 }
2059 }
2060
2061 switch (type.opcode()) {
2062 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002063 for (auto insn : module->decoration_inst) {
2064 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002065 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002066 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002067 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2068 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2069 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002070 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002071 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2072 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2073 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2074 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002075 }
Chris Forbes47567b72017-06-09 12:09:45 -07002076 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002077 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2078 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2079 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002080 }
2081 }
2082 }
2083
2084 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002085 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002086 }
2087
2088 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002089 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2090 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2091 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002092
Chris Forbes73c00bf2018-06-22 16:28:06 -07002093 case spv::OpTypeSampledImage: {
2094 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2095 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2096 auto image_type = module->get_def(type.word(2));
2097 auto dim = image_type.word(3);
2098 auto sampled = image_type.word(7);
2099 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002100 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2101 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002102 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002103 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002104 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2105 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002106
2107 case spv::OpTypeImage: {
2108 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2109 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2110 auto dim = type.word(3);
2111 auto sampled = type.word(7);
2112
2113 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002114 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2115 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002116 } else if (dim == spv::DimBuffer) {
2117 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002118 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2119 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002120 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002121 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2122 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002123 }
2124 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002125 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2126 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2127 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002128 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002129 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2130 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002131 }
2132 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002133 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002134 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2135 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002136 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002137
2138 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2139 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002140 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002141 }
2142}
2143
Jeff Bolze54ae892018-09-08 12:16:29 -05002144static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002145 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002146 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2147 if (ss.tellp()) ss << ", ";
2148 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002149 }
2150 return ss.str();
2151}
2152
sfricke-samsung0065ce02020-12-03 22:46:37 -08002153bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002154 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002155 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 -05002156 return true;
2157 }
2158 }
2159
2160 return false;
2161}
2162
sfricke-samsung0065ce02020-12-03 22:46:37 -08002163bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002164 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002165 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002166 return true;
2167 }
2168 }
2169
2170 return false;
2171}
2172
locke-lunarg63e4daf2020-08-17 17:53:25 -06002173bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2174 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002175 bool skip = false;
2176
locke-lunarg63e4daf2020-08-17 17:53:25 -06002177 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002178 switch (stage) {
2179 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002180 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2181 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2182 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2183 case VK_SHADER_STAGE_MISS_BIT_NV:
2184 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2185 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2186 case VK_SHADER_STAGE_TASK_BIT_NV:
2187 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002188 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002189 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002190 break;
2191 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002192 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2193 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002194 break;
2195 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002196 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2197 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002198 break;
2199 }
2200 }
2201
Chris Forbes47567b72017-06-09 12:09:45 -07002202 return skip;
2203}
2204
sfricke-samsung94167ca2021-02-26 04:14:59 -08002205bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2206 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002207 bool skip = false;
2208
sfricke-samsung94167ca2021-02-26 04:14:59 -08002209 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2210 if (GroupOperation(insn.opcode()) == true) {
2211 // Check the quad operations.
2212 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2213 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2214 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2215 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2216 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002217 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002218 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002219
sfricke-samsung94167ca2021-02-26 04:14:59 -08002220 uint32_t scope_type = spv::ScopeMax;
2221 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2222 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2223 scope_type = spv::ScopeSubgroup;
2224 } else {
2225 // "All <id> used for Scope <id> must be of an OpConstant"
2226 auto scope_id = module->get_def(insn.word(3));
2227 scope_type = scope_id.word(3);
2228 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002229
sfricke-samsung94167ca2021-02-26 04:14:59 -08002230 if (scope_type == spv::ScopeSubgroup) {
2231 // "Group operations with subgroup scope" must have stage support
2232 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2233 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002234 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002235 }
2236
2237 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2238 auto type = module->get_def(insn.word(1));
2239
2240 if (type.opcode() == spv::OpTypeVector) {
2241 // Get the element type
2242 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002243 }
2244
sfricke-samsung94167ca2021-02-26 04:14:59 -08002245 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002246 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2247 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002248
sfricke-samsung0065ce02020-12-03 22:46:37 -08002249 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2250 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2251 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2252 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2253 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002254 }
2255 }
2256 }
Jeff Bolzee743412019-06-20 22:24:32 -05002257 }
2258
2259 return skip;
2260}
2261
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002262bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002263 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002264 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2265 pStage->stage == VK_SHADER_STAGE_ALL) {
2266 return false;
2267 }
2268
2269 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002270 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002271
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002272 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002273 struct Variable {
2274 uint32_t baseTypePtrID;
2275 uint32_t ID;
2276 uint32_t storageClass;
2277 };
2278 std::vector<Variable> variables;
2279
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002280 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002281 bool is_iso_lines = false;
2282 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002283
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002284 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002285
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002286 for (auto insn : *src) {
2287 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002288 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002289 case spv::OpDecorate:
2290 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002291 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002292 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002293 break;
2294 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002295 default:
2296 break;
2297 }
2298 break;
2299 // Find all input and output variables
2300 case spv::OpVariable: {
2301 Variable var = {};
2302 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002303 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2304 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002305 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002306 var.baseTypePtrID = insn.word(1);
2307 var.ID = insn.word(2);
2308 variables.push_back(var);
2309 }
2310 break;
2311 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002312 case spv::OpExecutionMode:
2313 if (insn.word(1) == entrypoint.word(2)) {
2314 switch (insn.word(2)) {
2315 default:
2316 break;
2317 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002318 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002319 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002320 case spv::ExecutionModeIsolines:
2321 is_iso_lines = true;
2322 break;
2323 case spv::ExecutionModePointMode:
2324 is_point_mode = true;
2325 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002326 }
2327 }
2328 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002329 default:
2330 break;
2331 }
2332 }
2333
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002334 bool strip_output_array_level =
2335 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2336 bool strip_input_array_level =
2337 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2338 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2339
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002340 uint32_t num_comp_in = 0, num_comp_out = 0;
2341 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002342
2343 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2344 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2345
2346 // Find max component location used for input variables.
2347 for (auto &var : inputs) {
2348 int location = var.first.first;
2349 int component = var.first.second;
2350 interface_var &iv = var.second;
2351
2352 // Only need to look at the first location, since we use the type's whole size
2353 if (iv.offset != 0) {
2354 continue;
2355 }
2356
2357 if (iv.is_patch) {
2358 continue;
2359 }
2360
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002361 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2362 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002363 }
2364
2365 // Find max component location used for output variables.
2366 for (auto &var : outputs) {
2367 int location = var.first.first;
2368 int component = var.first.second;
2369 interface_var &iv = var.second;
2370
2371 // Only need to look at the first location, since we use the type's whole size
2372 if (iv.offset != 0) {
2373 continue;
2374 }
2375
2376 if (iv.is_patch) {
2377 continue;
2378 }
2379
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002380 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2381 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002382 }
2383
2384 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2385 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002386 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002387 // Check if the variable is a patch. Patches can also be members of blocks,
2388 // but if they are then the top-level arrayness has already been stripped
2389 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002390 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002391
2392 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002393 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002394 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002395 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002396 }
2397 }
2398
2399 switch (pStage->stage) {
2400 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002401 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002402 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2403 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2404 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2405 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002406 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002407 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002408 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002409 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2410 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2411 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2412 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002413 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002414 break;
2415
2416 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002417 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002418 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2419 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2420 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2421 "components by %u components",
2422 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002423 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002424 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002425 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002426 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002427 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2428 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2429 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2430 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002431 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002432 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002433 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2434 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2435 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2436 "components by %u components",
2437 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002438 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002439 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002440 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002441 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002442 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2443 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2444 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2445 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002446 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002447 break;
2448
2449 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002450 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002451 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2452 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2453 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2454 "components by %u components",
2455 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002456 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002457 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002458 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002459 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002460 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2461 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2462 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2463 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002464 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002465 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002466 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2467 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2468 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2469 "components by %u components",
2470 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002471 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002472 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002473 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002474 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002475 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2476 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2477 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2478 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002479 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002480 // Portability validation
2481 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2482 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2483 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2484 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2485 " is using abstract patch type IsoLines, but this is not supported on this platform");
2486 }
2487 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2488 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2489 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2490 " is using abstract patch type PointMode, but this is not supported on this platform");
2491 }
2492 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002493 break;
2494
2495 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002496 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002497 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2498 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2499 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2500 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002501 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002502 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002503 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002504 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2505 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2506 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2507 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002508 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002509 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002510 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2511 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2512 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2513 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002514 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002515 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002516 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002517 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2518 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2519 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2520 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002521 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002522 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002523 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2524 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2525 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2526 "components by %u components",
2527 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002528 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002529 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002530 break;
2531
2532 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002533 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002534 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2535 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2536 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2537 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002538 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002539 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002540 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002541 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2542 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2543 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2544 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002545 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002546 break;
2547
Jeff Bolz148d94e2018-12-13 21:25:56 -06002548 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2549 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2550 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2551 case VK_SHADER_STAGE_MISS_BIT_NV:
2552 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2553 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2554 case VK_SHADER_STAGE_TASK_BIT_NV:
2555 case VK_SHADER_STAGE_MESH_BIT_NV:
2556 break;
2557
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002558 default:
2559 assert(false); // This should never happen
2560 }
2561 return skip;
2562}
2563
sfricke-samsungdc96f302020-03-18 20:42:10 -07002564bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2565 bool skip = false;
2566 uint32_t total_resources = 0;
2567
2568 // Only currently testing for graphics and compute pipelines
2569 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2570 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2571 return false;
2572 }
2573
2574 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2575 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2576 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2577 }
2578
2579 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2580 // input from CreatePipeline and CreatePipelineLayout level
2581 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2582 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2583 continue;
2584 }
2585
2586 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2587 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2588 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2589 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2590 // Check only descriptor types listed in maxPerStageResources description in spec
2591 switch (binding->descriptorType) {
2592 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2593 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2594 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2595 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2596 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2597 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2598 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2599 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2600 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2601 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2602 total_resources += binding->descriptorCount;
2603 break;
2604 default:
2605 break;
2606 }
2607 }
2608 }
2609 }
2610
2611 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2612 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2613 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2614 skip |= LogError(pipeline->pipeline, vuid,
2615 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2616 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2617 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2618 }
2619
2620 return skip;
2621}
2622
Jeff Bolze4356752019-03-07 11:23:46 -06002623// copy the specialization constant value into buf, if it is present
2624void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2625 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2626
2627 if (spec && spec_id < spec->mapEntryCount) {
2628 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2629 }
2630}
2631
2632// Fill in value with the constant or specialization constant value, if available.
2633// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002634static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002635 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
Jeff Bolze4356752019-03-07 11:23:46 -06002636 auto type_id = src->get_def(insn.word(1));
2637 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2638 return false;
2639 }
2640 switch (insn.opcode()) {
2641 case spv::OpSpecConstant:
2642 *value = insn.word(3);
2643 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2644 return true;
2645 case spv::OpConstant:
2646 *value = insn.word(3);
2647 return true;
2648 default:
2649 return false;
2650 }
2651}
2652
2653// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002654VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002655 switch (insn.opcode()) {
2656 case spv::OpTypeInt:
2657 switch (insn.word(2)) {
2658 case 8:
2659 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2660 case 16:
2661 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2662 case 32:
2663 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2664 case 64:
2665 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2666 default:
2667 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2668 }
2669 case spv::OpTypeFloat:
2670 switch (insn.word(2)) {
2671 case 16:
2672 return VK_COMPONENT_TYPE_FLOAT16_NV;
2673 case 32:
2674 return VK_COMPONENT_TYPE_FLOAT32_NV;
2675 case 64:
2676 return VK_COMPONENT_TYPE_FLOAT64_NV;
2677 default:
2678 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2679 }
2680 default:
2681 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2682 }
2683}
2684
2685// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2686// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002687bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002688 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002689 bool skip = false;
2690
2691 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002692 layer_data::unordered_map<uint32_t, uint32_t> id_to_spec_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002693 // Map SPIR-V result ID to the ID of its type.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002694 layer_data::unordered_map<uint32_t, uint32_t> id_to_type_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002695
2696 struct CoopMatType {
2697 uint32_t scope, rows, cols;
2698 VkComponentTypeNV component_type;
2699 bool all_constant;
2700
2701 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2702
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002703 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002704 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
Jeff Bolze4356752019-03-07 11:23:46 -06002705 spirv_inst_iter insn = src->get_def(id);
2706 uint32_t component_type_id = insn.word(2);
2707 uint32_t scope_id = insn.word(3);
2708 uint32_t rows_id = insn.word(4);
2709 uint32_t cols_id = insn.word(5);
2710 auto component_type_iter = src->get_def(component_type_id);
2711 auto scope_iter = src->get_def(scope_id);
2712 auto rows_iter = src->get_def(rows_id);
2713 auto cols_iter = src->get_def(cols_id);
2714
2715 all_constant = true;
2716 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2717 all_constant = false;
2718 }
2719 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2720 all_constant = false;
2721 }
2722 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2723 all_constant = false;
2724 }
2725 component_type = GetComponentType(component_type_iter, src);
2726 }
2727 };
2728
2729 bool seen_coopmat_capability = false;
2730
2731 for (auto insn : *src) {
2732 // Whitelist instructions whose result can be a cooperative matrix type, and
2733 // keep track of their types. It would be nice if SPIRV-Headers generated code
2734 // to identify which instructions have a result type and result id. Lacking that,
2735 // this whitelist is based on the set of instructions that
2736 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2737 switch (insn.opcode()) {
2738 case spv::OpLoad:
2739 case spv::OpCooperativeMatrixLoadNV:
2740 case spv::OpCooperativeMatrixMulAddNV:
2741 case spv::OpSNegate:
2742 case spv::OpFNegate:
2743 case spv::OpIAdd:
2744 case spv::OpFAdd:
2745 case spv::OpISub:
2746 case spv::OpFSub:
2747 case spv::OpFDiv:
2748 case spv::OpSDiv:
2749 case spv::OpUDiv:
2750 case spv::OpMatrixTimesScalar:
2751 case spv::OpConstantComposite:
2752 case spv::OpCompositeConstruct:
2753 case spv::OpConvertFToU:
2754 case spv::OpConvertFToS:
2755 case spv::OpConvertSToF:
2756 case spv::OpConvertUToF:
2757 case spv::OpUConvert:
2758 case spv::OpSConvert:
2759 case spv::OpFConvert:
2760 id_to_type_id[insn.word(2)] = insn.word(1);
2761 break;
2762 default:
2763 break;
2764 }
2765
2766 switch (insn.opcode()) {
2767 case spv::OpDecorate:
2768 if (insn.word(2) == spv::DecorationSpecId) {
2769 id_to_spec_id[insn.word(1)] = insn.word(3);
2770 }
2771 break;
2772 case spv::OpCapability:
2773 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2774 seen_coopmat_capability = true;
2775
2776 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002777 skip |= LogError(
2778 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2779 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2780 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002781 }
2782 }
2783 break;
2784 case spv::OpMemoryModel:
2785 // If the capability isn't enabled, don't bother with the rest of this function.
2786 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2787 if (!seen_coopmat_capability) {
2788 return skip;
2789 }
2790 break;
2791 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002792 CoopMatType m;
2793 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002794
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002795 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002796 // Validate that the type parameters are all supported for one of the
2797 // operands of a cooperative matrix property.
2798 bool valid = false;
2799 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002800 if (cooperative_matrix_properties[i].AType == m.component_type &&
2801 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2802 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002803 valid = true;
2804 break;
2805 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002806 if (cooperative_matrix_properties[i].BType == m.component_type &&
2807 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2808 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002809 valid = true;
2810 break;
2811 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002812 if (cooperative_matrix_properties[i].CType == m.component_type &&
2813 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2814 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002815 valid = true;
2816 break;
2817 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002818 if (cooperative_matrix_properties[i].DType == m.component_type &&
2819 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2820 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002821 valid = true;
2822 break;
2823 }
2824 }
2825 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002826 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2827 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2828 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002829 }
2830 }
2831 break;
2832 }
2833 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002834 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002835 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2836 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2837 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2838 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002839 // Couldn't find type of matrix
2840 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002841 break;
2842 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002843 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2844 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2845 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2846 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002847
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002848 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002849 // Validate that the type parameters are all supported for the same
2850 // cooperative matrix property.
2851 bool valid = false;
2852 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002853 if (cooperative_matrix_properties[i].AType == a.component_type &&
2854 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2855 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002856
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002857 cooperative_matrix_properties[i].BType == b.component_type &&
2858 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2859 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002860
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002861 cooperative_matrix_properties[i].CType == c.component_type &&
2862 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2863 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002864
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002865 cooperative_matrix_properties[i].DType == d.component_type &&
2866 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2867 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002868 valid = true;
2869 break;
2870 }
2871 }
2872 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002873 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2874 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2875 "VkCooperativeMatrixPropertiesNV",
2876 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002877 }
2878 }
2879 break;
2880 }
2881 default:
2882 break;
2883 }
2884 }
2885
2886 return skip;
2887}
2888
John Zulaufac4c6e12019-07-01 16:05:58 -06002889bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002890 auto entrypoint_id = entrypoint.word(2);
2891
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002892 // The first denorm execution mode encountered, along with its bit width.
2893 // Used to check if SeparateDenormSettings is respected.
2894 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002895
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002896 // The first rounding mode encountered, along with its bit width.
2897 // Used to check if SeparateRoundingModeSettings is respected.
2898 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002899
2900 bool skip = false;
2901
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002902 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002903 uint32_t invocations = 0;
2904
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002905 auto it = src->execution_mode_inst.find(entrypoint_id);
2906 if (it != src->execution_mode_inst.end()) {
2907 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002908 auto mode = insn.word(2);
2909 switch (mode) {
2910 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2911 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002912 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2913 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2914 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002915 skip |= LogError(
2916 device, kVUID_Core_Shader_FeatureNotEnabled,
2917 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2918 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002919 }
2920 break;
2921 }
2922
2923 case spv::ExecutionModeDenormPreserve: {
2924 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002925 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2926 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2927 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002928 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2929 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2930 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002931 }
2932
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002933 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2934 // Register the first denorm execution mode found
2935 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002936 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002937 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002938 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002939 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002940 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2941 "Shader uses different denorm execution modes for 16 and 64-bit but "
2942 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002943 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002944 }
2945 break;
2946
Mike Schuchardt2df08912020-12-15 16:28:09 -08002947 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002948 break;
2949
Mike Schuchardt2df08912020-12-15 16:28:09 -08002950 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002951 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2952 "Shader uses different denorm execution modes for different bit widths but "
2953 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002954 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002955 break;
2956
2957 default:
2958 break;
2959 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002960 }
2961 break;
2962 }
2963
2964 case spv::ExecutionModeDenormFlushToZero: {
2965 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002966 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2967 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2968 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002969 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2970 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2971 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002972 }
2973
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002974 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2975 // Register the first denorm execution mode found
2976 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002977 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002978 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002979 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002980 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002981 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2982 "Shader uses different denorm execution modes for 16 and 64-bit but "
2983 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002984 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002985 }
2986 break;
2987
Mike Schuchardt2df08912020-12-15 16:28:09 -08002988 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002989 break;
2990
Mike Schuchardt2df08912020-12-15 16:28:09 -08002991 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002992 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2993 "Shader uses different denorm execution modes for different bit widths but "
2994 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002995 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002996 break;
2997
2998 default:
2999 break;
3000 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003001 }
3002 break;
3003 }
3004
3005 case spv::ExecutionModeRoundingModeRTE: {
3006 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003007 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3008 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3009 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003010 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3011 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3012 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003013 }
3014
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003015 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3016 // Register the first rounding mode found
3017 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003018 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003019 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003020 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003021 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003022 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3023 "Shader uses different rounding modes for 16 and 64-bit but "
3024 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003025 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003026 }
3027 break;
3028
Mike Schuchardt2df08912020-12-15 16:28:09 -08003029 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003030 break;
3031
Mike Schuchardt2df08912020-12-15 16:28:09 -08003032 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003033 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3034 "Shader uses different rounding modes for different bit widths but "
3035 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003036 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003037 break;
3038
3039 default:
3040 break;
3041 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003042 }
3043 break;
3044 }
3045
3046 case spv::ExecutionModeRoundingModeRTZ: {
3047 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003048 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3049 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3050 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003051 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3052 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3053 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003054 }
3055
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003056 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3057 // Register the first rounding mode found
3058 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003059 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003060 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003061 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003062 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003063 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3064 "Shader uses different rounding modes for 16 and 64-bit but "
3065 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003066 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003067 }
3068 break;
3069
Mike Schuchardt2df08912020-12-15 16:28:09 -08003070 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003071 break;
3072
Mike Schuchardt2df08912020-12-15 16:28:09 -08003073 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003074 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3075 "Shader uses different rounding modes for different bit widths but "
3076 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003077 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003078 break;
3079
3080 default:
3081 break;
3082 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003083 }
3084 break;
3085 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003086
3087 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003088 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003089 break;
3090 }
3091
3092 case spv::ExecutionModeInvocations: {
3093 invocations = insn.word(3);
3094 break;
3095 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003096 }
3097 }
3098 }
3099
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003100 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003101 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003102 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3103 "Geometry shader entry point must have an OpExecutionMode instruction that "
3104 "specifies a maximum output vertex count that is greater than 0 and less "
3105 "than or equal to maxGeometryOutputVertices. "
3106 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003107 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003108 }
3109
3110 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003111 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3112 "Geometry shader entry point must have an OpExecutionMode instruction that "
3113 "specifies an invocation count that is greater than 0 and less "
3114 "than or equal to maxGeometryShaderInvocations. "
3115 "Invocations=%d, maxGeometryShaderInvocations=%d",
3116 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003117 }
3118 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003119 return skip;
3120}
3121
locke-lunargd9a069d2019-09-17 01:50:19 -06003122uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003123 auto type = module->get_def(type_id);
3124
3125 while (true) {
3126 switch (type.opcode()) {
3127 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003128 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003129 case spv::OpTypeSampledImage:
3130 type = module->get_def(type.word(2));
3131 break;
3132 case spv::OpTypePointer:
3133 type = module->get_def(type.word(3));
3134 break;
3135 case spv::OpTypeImage: {
3136 auto dim = type.word(3);
3137 auto arrayed = type.word(5);
3138 auto msaa = type.word(6);
3139
Chris Forbes74ba2232018-08-27 15:19:27 -07003140 uint32_t bits = 0;
3141 switch (GetFundamentalType(module, type.word(2))) {
3142 case FORMAT_TYPE_FLOAT:
3143 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3144 break;
3145 case FORMAT_TYPE_UINT:
3146 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3147 break;
3148 case FORMAT_TYPE_SINT:
3149 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3150 break;
3151 default:
3152 break;
3153 }
3154
Chris Forbes47567b72017-06-09 12:09:45 -07003155 switch (dim) {
3156 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003157 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3158 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003159 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003160 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3161 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3162 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003163 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003164 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3165 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003166 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003167 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3168 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003169 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003170 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3171 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003172 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003173 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003174 }
3175 }
3176 default:
3177 return 0;
3178 }
3179 }
3180}
3181
3182// For given pipelineLayout verify that the set_layout_node at slot.first
3183// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003184static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003185 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003186 if (!pipelineLayout) return nullptr;
3187
3188 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3189
3190 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3191}
3192
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003193int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3194 if (module == nullptr) return -1;
3195
3196 auto type = module->get_def(resource.type_id);
3197 while (true) {
3198 switch (type.opcode()) {
3199 case spv::OpTypeSampledImage:
3200 type = module->get_def(type.word(2));
3201 break;
3202 case spv::OpTypePointer:
3203 type = module->get_def(type.word(3));
3204 break;
3205 case spv::OpTypeImage:
3206 return type.word(3);
3207 default:
3208 return -1;
3209 }
3210 }
3211}
3212
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003213// Because the following is legal, need the entry point
3214// OpEntryPoint GLCompute %main "name_a"
3215// OpEntryPoint GLCompute %main "name_b"
3216bool FindLocalSize(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, uint32_t &local_size_x,
3217 uint32_t &local_size_y, uint32_t &local_size_z) {
3218 auto entrypoint_id = entrypoint.word(2);
3219 auto it = src->execution_mode_inst.find(entrypoint_id);
3220 if (it != src->execution_mode_inst.end()) {
3221 for (auto insn : it->second) {
3222 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
3223 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
3224 assert(insn.opcode() == spv::OpExecutionMode);
3225 if (insn.word(2) == spv::ExecutionModeLocalSize) {
3226 local_size_x = insn.word(3);
3227 local_size_y = insn.word(4);
3228 local_size_z = insn.word(5);
3229 return true;
Locke1ec6d952019-04-02 11:57:21 -06003230 }
3231 }
3232 }
3233 return false;
3234}
3235
locke-lunargd9a069d2019-09-17 01:50:19 -06003236void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003237 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003238 bool is_point_mode = false;
3239
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003240 auto it = src->execution_mode_inst.find(entrypoint_id);
3241 if (it != src->execution_mode_inst.end()) {
3242 for (auto insn : it->second) {
Chris Forbes0771b672018-03-22 21:13:46 -07003243 switch (insn.word(2)) {
3244 case spv::ExecutionModePointMode:
3245 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3246 is_point_mode = true;
3247 break;
3248
3249 case spv::ExecutionModeOutputPoints:
3250 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3251 break;
3252
3253 case spv::ExecutionModeIsolines:
3254 case spv::ExecutionModeOutputLineStrip:
3255 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3256 break;
3257
3258 case spv::ExecutionModeTriangles:
3259 case spv::ExecutionModeQuads:
3260 case spv::ExecutionModeOutputTriangleStrip:
3261 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3262 break;
3263 }
3264 }
3265 }
3266
3267 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3268}
3269
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003270// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3271// o If there is only a vertex shader : gl_PointSize must be written when using points
3272// o If there is a geometry or tessellation shader:
3273// - If shaderTessellationAndGeometryPointSize feature is enabled:
3274// * gl_PointSize must be written in the final geometry stage
3275// - If shaderTessellationAndGeometryPointSize feature is disabled:
3276// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003277bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003278 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003279 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3280 return false;
3281 }
3282
3283 bool pointsize_written = false;
3284 bool skip = false;
3285
3286 // Search for PointSize built-in decorations
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003287 for (auto set : src->builtin_decoration_list) {
3288 auto insn = src->at(set.offset);
3289 if (set.builtin == spv::BuiltInPointSize) {
3290 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
3291 if (pointsize_written) {
3292 break;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003293 }
3294 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003295 }
3296
3297 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003298 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003299 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003300 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3301 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3302 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003303 }
3304 } else if (!pointsize_written) {
3305 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003306 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3307 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3308 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003309 }
3310 return skip;
3311}
John Zulauf14c355b2019-06-27 16:09:37 -06003312
Tobias Hector6663c9b2020-11-05 10:18:02 +00003313bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3314 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3315 bool primitiverate_written = false;
3316 bool viewportindex_written = false;
3317 bool viewportmask_written = false;
3318 bool skip = false;
3319
3320 // Check if the primitive shading rate is written
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003321 for (auto set : src->builtin_decoration_list) {
3322 auto insn = src->at(set.offset);
3323 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3324 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3325 } else if (set.builtin == spv::BuiltInViewportIndex) {
3326 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3327 } else if (set.builtin == spv::BuiltInViewportMaskNV) {
3328 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003329 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003330 if (primitiverate_written && viewportindex_written && viewportmask_written) {
3331 break;
3332 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003333 }
3334
Tony-LunarGd44844c2021-01-22 13:24:37 -07003335 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3336 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003337 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3338 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003339 skip |= LogError(pipeline->pipeline,
3340 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3341 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3342 "multiple viewports "
3343 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3344 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003345 }
3346
3347 if (primitiverate_written && viewportindex_written) {
3348 skip |= LogError(pipeline->pipeline,
3349 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3350 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3351 "ViewportIndex built-ins,"
3352 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3353 string_VkShaderStageFlagBits(stage));
3354 }
3355
3356 if (primitiverate_written && viewportmask_written) {
3357 skip |= LogError(pipeline->pipeline,
3358 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3359 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3360 "ViewportMaskNV built-ins,"
3361 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3362 string_VkShaderStageFlagBits(stage));
3363 }
3364 }
3365 return skip;
3366}
3367
sfricke-samsung486a51e2021-01-02 00:10:15 -08003368// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003369bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003370 bool skip = false;
3371
sfricke-samsung94167ca2021-02-26 04:14:59 -08003372 switch (insn.opcode()) {
3373 case spv::OpReadClockKHR: {
3374 auto scope_id = module->get_def(insn.word(3));
3375 auto scope_type = scope_id.word(3);
3376 // if scope isn't Subgroup or Device, spirv-val will catch
3377 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3378 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3379 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3380 report_data->FormatHandle(module->vk_shader_module).c_str());
3381 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3382 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3383 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3384 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003385 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003386 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003387 }
3388 }
3389 return skip;
3390}
3391
John Zulauf14c355b2019-06-27 16:09:37 -06003392bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3393 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003394 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003395 bool skip = false;
3396
3397 // Check the module
3398 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003399 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3400 "%s does not contain valid spirv for stage %s.",
3401 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003402 }
3403
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003404 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3405 // specializations should be applied and validated.
3406 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3407 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3408 // Gather the specialization-constant values.
3409 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003410 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003411 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map; // note: this must be std:: to work with spvtools
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003412 id_value_map.reserve(specialization_info->mapEntryCount);
3413 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3414 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003415
Jeremy Hayes521221d2020-01-15 16:48:49 -07003416 // Expect only scalar types.
3417 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3418 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3419 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003420 }
3421
3422 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003423 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003424 spvtools::Optimizer optimizer(spirv_environment);
3425 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3426 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003427 skip |= LogError(
3428 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003429 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3430 };
3431 optimizer.SetMessageConsumer(consumer);
3432 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3433 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3434 std::vector<uint32_t> specialized_spirv;
3435 auto const optimized =
3436 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3437 assert(optimized == true);
3438
3439 if (optimized) {
3440 spv_context ctx = spvContextCreate(spirv_environment);
3441 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3442 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003443 spvtools::ValidatorOptions options;
3444 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003445 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3446 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003447 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003448 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3449 report_data->FormatHandle(module->vk_shader_module).c_str(),
3450 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003451 }
3452
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003453 spvDiagnosticDestroy(diag);
3454 spvContextDestroy(ctx);
3455 }
3456 }
3457
John Zulauf14c355b2019-06-27 16:09:37 -06003458 // Check the entrypoint
3459 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003460 skip |=
3461 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3462 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003463 }
3464 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3465
3466 // Mark accessible ids
3467 auto &accessible_ids = stage_state.accessible_ids;
3468
Chris Forbes47567b72017-06-09 12:09:45 -07003469 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003470 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3471 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003472
sfricke-samsung94167ca2021-02-26 04:14:59 -08003473 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3474 // and mainly only checking the instruction in detail for a single operation
3475 for (auto insn : *module) {
3476 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3477 skip |= ValidatePropertiesAndFeatures(module, insn);
3478 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3479 }
3480
locke-lunarg63e4daf2020-08-17 17:53:25 -06003481 skip |=
3482 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003483 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003484 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003485 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003486 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003487 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003488 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003489 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003490 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003491 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
sfricke-samsungd093e522021-02-26 04:17:45 -08003492 if (enabled_features.cooperative_matrix_features.cooperativeMatrix) {
3493 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
3494 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003495 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3496 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3497 }
Chris Forbes47567b72017-06-09 12:09:45 -07003498
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003499 std::string vuid_layout_mismatch;
3500 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3501 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3502 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3503 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3504 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3505 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3506 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3507 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3508 }
3509
Chris Forbes47567b72017-06-09 12:09:45 -07003510 // Validate descriptor use
3511 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003512 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003513 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003514 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003515 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3516 std::set<uint32_t> descriptor_types =
3517 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003518
3519 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003520 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003521 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3522 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003523 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003524 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003525 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3526 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003527 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003528 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003529 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3530 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3531 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003532 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003533 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003534 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3535 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003536 }
3537 }
3538
3539 // Validate use of input attachments against subpass structure
3540 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003541 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003542
Petr Krause91f7a12017-12-14 20:57:36 +01003543 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003544 auto subpass = pipeline->graphicsPipelineCI.subpass;
3545
3546 for (auto use : input_attachment_uses) {
3547 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3548 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003549 ? input_attachments[use.first].attachment
3550 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003551
3552 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003553 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3554 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003555 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003556 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003557 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3558 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3559 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003560 }
3561 }
3562 }
Lockeaa8fdc02019-04-02 11:59:20 -06003563 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003564 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06003565 }
Chris Forbes47567b72017-06-09 12:09:45 -07003566 return skip;
3567}
3568
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003569bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3570 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3571 spirv_inst_iter consumer_entrypoint,
3572 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003573 bool skip = false;
3574
3575 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003576 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3577 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003578
3579 auto a_it = outputs.begin();
3580 auto b_it = inputs.begin();
3581
3582 // Maps sorted by key (location); walk them together to find mismatches
3583 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3584 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3585 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3586 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3587 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3588
3589 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003590 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3591 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3592 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003593 a_it++;
3594 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003595 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3596 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3597 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003598 b_it++;
3599 } else {
3600 // subtleties of arrayed interfaces:
3601 // - if is_patch, then the member is not arrayed, even though the interface may be.
3602 // - if is_block_member, then the extra array level of an arrayed interface is not
3603 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003604 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3605 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3606 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003607 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3608 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3609 DescribeType(producer, a_it->second.type_id).c_str(),
3610 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003611 }
3612 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003613 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3614 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3615 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3616 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003617 }
3618 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003619 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3620 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3621 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003622 }
3623 a_it++;
3624 b_it++;
3625 }
3626 }
3627
Ari Suonpaa696b3432019-03-11 14:02:57 +02003628 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3629 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3630 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3631
3632 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3633 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003634 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3635 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003636 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3637 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003638 } else {
3639 auto it_producer = builtins_producer.begin();
3640 auto it_consumer = builtins_consumer.begin();
3641 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3642 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003643 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3644 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3645 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003646 break;
3647 }
3648 it_producer++;
3649 it_consumer++;
3650 }
3651 }
3652 }
3653 }
3654
Chris Forbes47567b72017-06-09 12:09:45 -07003655 return skip;
3656}
3657
John Zulauf14c355b2019-06-27 16:09:37 -06003658static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003659 uint32_t stage_mask = 0;
3660 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3661 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3662 stage_mask |= pCreateInfo->pStages[i].stage;
3663 }
3664 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003665 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3666 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3667 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003668 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3669 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3670 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3671 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3672 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003673 }
3674 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003675 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003676}
3677
Chris Forbes47567b72017-06-09 12:09:45 -07003678// Validate that the shaders used by the given pipeline and store the active_slots
3679// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003680bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003681 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003682 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3683 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003684
John Zulauf14c355b2019-06-27 16:09:37 -06003685 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003686 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003687 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003688 bool skip = false;
3689
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003690 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003691
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003692 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3693 auto stage = &create_info->pStages[i];
3694 auto stage_id = GetShaderStageId(stage->stage);
3695 shaders[stage_id] = GetShaderModuleState(stage->module);
3696 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3697 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3698 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003699 }
3700
3701 // if the shader stages are no good individually, cross-stage validation is pointless.
3702 if (skip) return true;
3703
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003704 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003705
3706 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003707 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003708 }
3709
3710 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003711 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003712 }
3713
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003714 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3715 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003716
3717 while (!shaders[producer] && producer != fragment_stage) {
3718 producer++;
3719 consumer++;
3720 }
3721
3722 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3723 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003724 if (shaders[consumer]) {
3725 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003726 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3727 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003728 }
Chris Forbes47567b72017-06-09 12:09:45 -07003729
3730 producer = consumer;
3731 }
3732 }
3733
3734 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003735 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003736 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003737 }
3738
3739 return skip;
3740}
3741
Tony-LunarGb2ded512021-02-02 16:03:30 -07003742void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3743 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3744
3745 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3746 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3747 return;
3748 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003749
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003750 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3751 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003752 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003753
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003754 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3755 auto stage = &create_info->pStages[i];
3756 auto stage_id = GetShaderStageId(stage->stage);
3757 shaders[stage_id] = GetShaderModuleState(stage->module);
3758 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003759
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003760 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3761 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003762 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003763
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003764 for (auto set : shaders[stage_id]->builtin_decoration_list) {
3765 auto insn = shaders[stage_id]->at(set.offset);
3766 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3767 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003768 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003769 if (primitiverate_written) {
3770 break;
3771 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003772 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003773
Tony-LunarGb2ded512021-02-02 16:03:30 -07003774 if (primitiverate_written) {
3775 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3776 }
3777 }
3778 }
3779}
3780
3781bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3782 const char *caller, const DrawDispatchVuid &vuid) const {
3783 auto create_info = pipeline->graphicsPipelineCI.ptr();
3784 bool skip = false;
3785
3786 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3787 auto stage = &create_info->pStages[i];
3788 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3789 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3790 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3791 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3792 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003793 skip |=
3794 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3795 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3796 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3797 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003798 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003799 }
3800 }
3801 }
3802 }
3803
3804 return skip;
3805}
3806
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003807bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003808 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003809
John Zulauf14c355b2019-06-27 16:09:37 -06003810 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3811 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003812
John Zulauf14c355b2019-06-27 16:09:37 -06003813 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003814}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003815
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003816uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3817 uint32_t total = 0;
3818
3819 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3820 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3821 if (stages[stage_index].stage == stageBit) {
3822 total++;
3823 }
3824 }
3825
3826 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3827 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3828 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3829 total += CalcShaderStageCount(library_pipeline, stageBit);
3830 }
3831 }
3832
3833 return total;
3834}
3835
sourav parmarcd5fb182020-07-17 12:58:44 -07003836bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003837 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003838
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003839 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003840 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3841 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3842 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3843 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3844 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3845 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3846 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003847 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003848 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3849 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003850 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003851 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003852 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003853 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3854 skip |= LogError(
3855 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3856 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3857 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003858 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003859 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3860 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003861 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3862 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003863 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003864 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003865 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3866 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3867 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3868 "member must have been created with values of the maxPipelineRayPayloadSize and "
3869 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3870 }
3871 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003872 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003873 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3874 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3875 "vkCreateRayTracingPipelinesKHR: If flags includes "
3876 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3877 "the pLibraries member of libraries must have been created with the "
3878 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3879 }
sourav parmar83c31b12020-05-06 12:30:54 -07003880 }
3881 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003882 } else {
3883 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003884 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3885 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3886 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003887 pipeline->raytracingPipelineCI.maxRecursionDepth,
3888 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3889 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003890 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003891 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3892 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3893
John Zulaufe4474e72019-07-01 17:28:27 -06003894 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003895 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003896
John Zulaufe4474e72019-07-01 17:28:27 -06003897 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3898 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003899
John Zulaufe4474e72019-07-01 17:28:27 -06003900 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003901 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003902
3903 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3904 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3905 if (raygen_stages_count == 0) {
3906 skip |= LogError(
3907 device,
3908 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3909 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3910 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003911 }
3912
3913 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3914 const auto &group = groups[group_index];
3915
3916 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3917 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3918 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3919 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3920 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003921 skip |= LogError(device,
3922 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3923 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3924 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003925 }
3926 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3927 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003928 skip |= LogError(device,
3929 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3930 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3931 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003932 }
3933 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3934 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3935 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003936 skip |= LogError(device,
3937 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3938 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3939 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003940 }
3941 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3942 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003943 skip |= LogError(device,
3944 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3945 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3946 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003947 }
3948 }
3949
3950 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3951 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3952 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3953 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003954 skip |= LogError(device,
3955 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3956 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3957 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003958 }
3959 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3960 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3961 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003962 skip |= LogError(device,
3963 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3964 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3965 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003966 }
3967 }
John Zulaufe4474e72019-07-01 17:28:27 -06003968 }
3969 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003970}
3971
Dave Houltona9df0ce2018-02-07 10:51:23 -07003972uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003973
Dave Houltona9df0ce2018-02-07 10:51:23 -07003974static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003975 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003976 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003977 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003978 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003979 return nullptr;
3980}
3981
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003982bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003983 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003984 bool skip = false;
3985 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003986
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003987 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003988 return false;
3989 }
3990
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003991 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003992
3993 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003994 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3995 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3996 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003997 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003998 auto cache = GetValidationCacheInfo(pCreateInfo);
3999 uint32_t hash = 0;
4000 if (cache) {
4001 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004002 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004003 }
4004
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004005 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4006 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004007 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004008 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004009 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004010 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004011 spvtools::ValidatorOptions options;
4012 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004013 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004014 if (spv_valid != SPV_SUCCESS) {
4015 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004016 if (spv_valid == SPV_WARNING) {
4017 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4018 diag && diag->error ? diag->error : "(no error text)");
4019 } else {
4020 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4021 diag && diag->error ? diag->error : "(no error text)");
4022 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004023 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004024 } else {
4025 if (cache) {
4026 cache->Insert(hash);
4027 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004028 }
4029
4030 spvDiagnosticDestroy(diag);
4031 spvContextDestroy(ctx);
4032 }
4033
Chris Forbes4ae55b32017-06-09 14:42:56 -07004034 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004035}
4036
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004037bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004038 bool skip = false;
4039 uint32_t local_size_x = 0;
4040 uint32_t local_size_y = 0;
4041 uint32_t local_size_z = 0;
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004042 if (FindLocalSize(shader, entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06004043 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004044 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4045 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4046 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4047 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004048 }
4049 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004050 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4051 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4052 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4053 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004054 }
4055 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004056 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4057 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4058 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4059 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004060 }
4061
4062 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4063 uint64_t invocations = local_size_x * local_size_y;
4064 // Prevent overflow.
4065 bool fail = false;
4066 if (invocations > UINT32_MAX || invocations > limit) {
4067 fail = true;
4068 }
4069 if (!fail) {
4070 invocations *= local_size_z;
4071 if (invocations > UINT32_MAX || invocations > limit) {
4072 fail = true;
4073 }
4074 }
4075 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004076 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4077 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4078 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4079 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4080 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004081 }
4082 }
4083 return skip;
4084}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004085
4086spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4087 if (api_version >= VK_API_VERSION_1_2) {
4088 return SPV_ENV_VULKAN_1_2;
4089 } else if (api_version >= VK_API_VERSION_1_1) {
4090 if (spirv_1_4) {
4091 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4092 } else {
4093 return SPV_ENV_VULKAN_1_1;
4094 }
4095 }
4096 return SPV_ENV_VULKAN_1_0;
4097}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004098
4099void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4100 spvtools::ValidatorOptions &options) {
4101 if (device_extensions.vk_khr_relaxed_block_layout) {
4102 options.SetRelaxBlockLayout(true);
4103 }
4104 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4105 options.SetUniformBufferStandardLayout(true);
4106 }
4107 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4108 options.SetScalarBlockLayout(true);
4109 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004110 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4111 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4112 options.SetWorkgroupScalarBlockLayout(true);
4113 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004114}