blob: b2e4e8d292d5407ac180166aa8bcc5f4f114bf48 [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) {
Jeremy Gebbenfc6f8152021-03-18 16:58:55 -0600116 func_set.op_lists.emplace(insn.opcode(), insn.offset());
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 } else if (entry_point) {
Jeremy Gebbenfc6f8152021-03-18 16:58:55 -0600118 entry_point->decorate_list.emplace(insn.opcode(), insn.offset());
locke-lunargde3f0fa2020-09-10 11:55:31 -0600119 }
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: {
sfricke-samsung5c65b372021-03-25 05:39:57 -0700203 if (entry_point != nullptr) {
204 multiple_entry_points = true;
205 }
206
John Zulauf14c355b2019-06-27 16:09:37 -0600207 // 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 -0700208 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600209 auto execution_model = insn.word(1);
210 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600211 entry_points.emplace(entrypoint_name,
212 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
213
214 auto range = entry_points.equal_range(entrypoint_name);
215 for (auto it = range.first; it != range.second; ++it) {
216 if (it->second.offset == insn.offset()) {
217 entry_point = &(it->second);
218 break;
219 }
220 }
221 assert(entry_point != nullptr);
222 break;
223 }
224 case spv::OpFunctionEnd: {
225 assert(entry_point != nullptr);
226 func_set.length = insn.offset() - func_set.offset;
227 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600228 break;
229 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800230
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700231 // Copy operations
232 case spv::OpCopyLogical:
233 case spv::OpCopyObject: {
234 def_index[insn.word(2)] = insn.offset();
235 break;
236 }
237
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800238 // Execution Mode
239 case spv::OpExecutionMode: {
240 execution_mode_inst[insn.word(1)].push_back(insn);
241 } break;
242
Chris Forbes47567b72017-06-09 12:09:45 -0700243 default:
244 // We don't care about any other defs for now.
245 break;
246 }
247 }
248}
249
Jeff Bolz105d6492018-09-29 15:46:44 -0500250unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
251 switch (mode) {
252 case spv::ExecutionModelVertex:
253 return VK_SHADER_STAGE_VERTEX_BIT;
254 case spv::ExecutionModelTessellationControl:
255 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
256 case spv::ExecutionModelTessellationEvaluation:
257 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
258 case spv::ExecutionModelGeometry:
259 return VK_SHADER_STAGE_GEOMETRY_BIT;
260 case spv::ExecutionModelFragment:
261 return VK_SHADER_STAGE_FRAGMENT_BIT;
262 case spv::ExecutionModelGLCompute:
263 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600264 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700265 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600266 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700267 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600268 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700269 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600270 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700271 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600272 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700273 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600274 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700275 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500276 case spv::ExecutionModelTaskNV:
277 return VK_SHADER_STAGE_TASK_BIT_NV;
278 case spv::ExecutionModelMeshNV:
279 return VK_SHADER_STAGE_MESH_BIT_NV;
280 default:
281 return 0;
282 }
283}
284
locke-lunargde3f0fa2020-09-10 11:55:31 -0600285const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
286 VkShaderStageFlagBits stageBits) {
287 auto range = src->entry_points.equal_range(name);
288 for (auto it = range.first; it != range.second; ++it) {
289 if (it->second.stage == stageBits) {
290 return &(it->second);
291 }
292 }
293 return nullptr;
294}
295
locke-lunargd9a069d2019-09-17 01:50:19 -0600296spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600297 auto range = src->entry_points.equal_range(name);
298 for (auto it = range.first; it != range.second; ++it) {
299 if (it->second.stage == stageBits) {
300 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700301 }
302 }
Chris Forbes47567b72017-06-09 12:09:45 -0700303 return src->end();
304}
305
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600306static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700307 switch (sc) {
308 case spv::StorageClassInput:
309 return "input";
310 case spv::StorageClassOutput:
311 return "output";
312 case spv::StorageClassUniformConstant:
313 return "const uniform";
314 case spv::StorageClassUniform:
315 return "uniform";
316 case spv::StorageClassWorkgroup:
317 return "workgroup local";
318 case spv::StorageClassCrossWorkgroup:
319 return "workgroup global";
320 case spv::StorageClassPrivate:
321 return "private global";
322 case spv::StorageClassFunction:
323 return "function";
324 case spv::StorageClassGeneric:
325 return "generic";
326 case spv::StorageClassAtomicCounter:
327 return "atomic counter";
328 case spv::StorageClassImage:
329 return "image";
330 case spv::StorageClassPushConstant:
331 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800332 case spv::StorageClassStorageBuffer:
333 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700334 default:
335 return "unknown";
336 }
337}
338
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700339// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
340// Otherwise, returns src->end().
341spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700342 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700343
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700344 // If id is a copy, see where it was copied from
345 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
346 id = value.word(3);
347 value = src->get_def(id);
348 }
349
350 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
351 return value;
352 }
353 return src->end();
354}
355
356// Assumes itr points to an OpConstant instruction
357uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
358
359// Either returns the constant value described by the instruction at id, or 1
360uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
361 auto value = GetConstantDef(src, id);
362
363 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 // TODO: Either ensure that the specialization transform is already performed on a module we're
365 // considering here, OR -- specialize on the fly now.
366 return 1;
367 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700368 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700369}
370
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600371static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700372 auto insn = src->get_def(type);
373 assert(insn != src->end());
374
375 switch (insn.opcode()) {
376 case spv::OpTypeBool:
377 ss << "bool";
378 break;
379 case spv::OpTypeInt:
380 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
381 break;
382 case spv::OpTypeFloat:
383 ss << "float" << insn.word(2);
384 break;
385 case spv::OpTypeVector:
386 ss << "vec" << 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::OpTypeMatrix:
390 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600391 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700392 break;
393 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600394 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
395 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700396 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700397 case spv::OpTypeRuntimeArray:
398 ss << "runtime arr[] of ";
399 DescribeTypeInner(ss, src, insn.word(2));
400 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700401 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600402 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
403 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700404 break;
405 case spv::OpTypeStruct: {
406 ss << "struct of (";
407 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600408 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700409 if (i == insn.len() - 1) {
410 ss << ")";
411 } else {
412 ss << ", ";
413 }
414 }
415 break;
416 }
417 case spv::OpTypeSampler:
418 ss << "sampler";
419 break;
420 case spv::OpTypeSampledImage:
421 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600422 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700423 break;
424 case spv::OpTypeImage:
425 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
426 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600427 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500428 ss << "accelerationStruture";
429 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700430 default:
431 ss << "oddtype";
432 break;
433 }
434}
435
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600436static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700437 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600438 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700439 return ss.str();
440}
441
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600442static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700443 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
444 return type.word(2) < 64;
445}
446
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600447static 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 -0600448 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700449 // Walk two type trees together, and complain about differences
450 auto a_insn = a->get_def(a_type);
451 auto b_insn = b->get_def(b_type);
452 assert(a_insn != a->end());
453 assert(b_insn != b->end());
454
Chris Forbes062f1222018-08-21 15:34:15 -0700455 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
456
Chris Forbes47567b72017-06-09 12:09:45 -0700457 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600458 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700459 }
460
461 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
462 // 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 -0600463 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700464 }
465
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600466 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
467 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700468 }
469
470 if (a_insn.opcode() != b_insn.opcode()) {
471 return false;
472 }
473
474 if (a_insn.opcode() == spv::OpTypePointer) {
475 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600476 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700477 }
478
479 if (a_arrayed || b_arrayed) {
480 // If we havent resolved array-of-verts by here, we're not going to.
481 return false;
482 }
483
484 switch (a_insn.opcode()) {
485 case spv::OpTypeBool:
486 return true;
487 case spv::OpTypeInt:
488 // Match on width, signedness
489 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
490 case spv::OpTypeFloat:
491 // Match on width
492 return a_insn.word(2) == b_insn.word(2);
493 case spv::OpTypeVector:
494 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600495 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
496 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700497 return a_insn.word(3) >= b_insn.word(3);
498 } else {
499 return a_insn.word(3) == b_insn.word(3);
500 }
501 case spv::OpTypeMatrix:
502 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600503 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700504 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700505 case spv::OpTypeArray:
506 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
507 // 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 -0600508 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
509 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700510 case spv::OpTypeStruct:
511 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700512 {
513 if (a_insn.len() != b_insn.len()) {
514 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700515 }
Chris Forbes47567b72017-06-09 12:09:45 -0700516
Dave Houltona9df0ce2018-02-07 10:51:23 -0700517 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600518 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700519 return false;
520 }
521 }
522
523 return true;
524 }
Chris Forbes47567b72017-06-09 12:09:45 -0700525 default:
526 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
527 return false;
528 }
529}
530
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600531static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700532 auto insn = src->get_def(type);
533 assert(insn != src->end());
534
535 switch (insn.opcode()) {
536 case spv::OpTypePointer:
537 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
538 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600539 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700540 case spv::OpTypeArray:
541 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600542 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700543 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600544 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700545 }
546 case spv::OpTypeMatrix:
547 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600548 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700549 case spv::OpTypeVector: {
550 auto scalar_type = src->get_def(insn.word(2));
551 auto bit_width =
552 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
553
554 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
555 return (bit_width * insn.word(3) + 127) / 128;
556 }
557 default:
558 // Everything else is just 1.
559 return 1;
560
561 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
562 }
563}
564
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600565static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200566 auto insn = src->get_def(type);
567 assert(insn != src->end());
568
569 switch (insn.opcode()) {
570 case spv::OpTypePointer:
571 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
572 // pointers around.
573 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
574 case spv::OpTypeStruct: {
575 uint32_t sum = 0;
576 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
577 sum += GetComponentsConsumedByType(src, insn.word(i), false);
578 }
579 return sum;
580 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500581 case spv::OpTypeArray:
582 if (strip_array_level) {
583 return GetComponentsConsumedByType(src, insn.word(2), false);
584 } else {
585 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200586 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200587 case spv::OpTypeMatrix:
588 // Num locations is the dimension * element size
589 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
590 case spv::OpTypeVector: {
591 auto scalar_type = src->get_def(insn.word(2));
592 auto bit_width =
593 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
594 // One component is 32-bit
595 return (bit_width * insn.word(3) + 31) / 32;
596 }
597 case spv::OpTypeFloat: {
598 auto bit_width = insn.word(2);
599 return (bit_width + 31) / 32;
600 }
601 case spv::OpTypeInt: {
602 auto bit_width = insn.word(2);
603 return (bit_width + 31) / 32;
604 }
605 case spv::OpConstant:
606 return GetComponentsConsumedByType(src, insn.word(1), false);
607 default:
608 return 0;
609 }
610}
611
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600612static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700613 switch (format) {
614 case VK_FORMAT_R64G64B64A64_SFLOAT:
615 case VK_FORMAT_R64G64B64A64_SINT:
616 case VK_FORMAT_R64G64B64A64_UINT:
617 case VK_FORMAT_R64G64B64_SFLOAT:
618 case VK_FORMAT_R64G64B64_SINT:
619 case VK_FORMAT_R64G64B64_UINT:
620 return 2;
621 default:
622 return 1;
623 }
624}
625
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600626static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700627 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
628 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
629 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
630 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700631 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
632 return FORMAT_TYPE_FLOAT;
633}
634
635// 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 -0700636// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600637static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700638 auto insn = src->get_def(type);
639 assert(insn != src->end());
640
641 switch (insn.opcode()) {
642 case spv::OpTypeInt:
643 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
644 case spv::OpTypeFloat:
645 return FORMAT_TYPE_FLOAT;
646 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700647 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700648 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700649 case spv::OpTypeRuntimeArray:
650 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600651 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700652 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600653 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700654
655 default:
656 return 0;
657 }
658}
659
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600660static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700661 uint32_t bit_pos = uint32_t(u_ffs(stage));
662 return bit_pos - 1;
663}
664
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600665static 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 -0700666 while (true) {
667 if (def.opcode() == spv::OpTypePointer) {
668 def = src->get_def(def.word(3));
669 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
670 def = src->get_def(def.word(2));
671 is_array_of_verts = false;
672 } else if (def.opcode() == spv::OpTypeStruct) {
673 return def;
674 } else {
675 return src->end();
676 }
677 }
678}
679
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600680static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800681 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
682 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700683 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600684 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800685 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700686 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700687 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700688 }
689
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700690 layer_data::unordered_map<unsigned, unsigned> member_components;
691 layer_data::unordered_map<unsigned, unsigned> member_relaxed_precision;
692 layer_data::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700693
694 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800695 for (auto insn : src->member_decoration_inst) {
696 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700697 unsigned member_index = insn.word(2);
698
699 if (insn.word(3) == spv::DecorationComponent) {
700 unsigned component = insn.word(4);
701 member_components[member_index] = component;
702 }
703
704 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
705 member_relaxed_precision[member_index] = 1;
706 }
Chris Forbesa313d772017-06-13 13:59:41 -0700707
708 if (insn.word(3) == spv::DecorationPatch) {
709 member_patch[member_index] = 1;
710 }
Chris Forbes47567b72017-06-09 12:09:45 -0700711 }
712 }
713
Chris Forbesa313d772017-06-13 13:59:41 -0700714 // TODO: correctly handle location assignment from outside
715
Chris Forbes47567b72017-06-09 12:09:45 -0700716 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800717 for (auto insn : src->member_decoration_inst) {
718 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700719 unsigned member_index = insn.word(2);
720 unsigned member_type_id = type.word(2 + member_index);
721
722 if (insn.word(3) == spv::DecorationLocation) {
723 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600724 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700725 auto component_it = member_components.find(member_index);
726 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
727 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700728 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700729
730 for (unsigned int offset = 0; offset < num_locations; offset++) {
731 interface_var v = {};
732 v.id = id;
733 // TODO: member index in interface_var too?
734 v.type_id = member_type_id;
735 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700736 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700737 v.is_block_member = true;
738 v.is_relaxed_precision = is_relaxed_precision;
739 (*out)[std::make_pair(location + offset, component)] = v;
740 }
741 }
742 }
743 }
Chris Forbesa313d772017-06-13 13:59:41 -0700744
745 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700746}
747
Ari Suonpaa696b3432019-03-11 14:02:57 +0200748static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800749 assert(entrypoint.opcode() == spv::OpEntryPoint);
750
Ari Suonpaa696b3432019-03-11 14:02:57 +0200751 std::vector<uint32_t> interfaces;
752 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
753 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
754 uint32_t word = 3;
755 while (entrypoint.word(word) & 0xff000000u) {
756 ++word;
757 }
758 ++word;
759
760 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
761
762 return interfaces;
763}
764
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600765static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600766 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700767 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
768
Chris Forbes47567b72017-06-09 12:09:45 -0700769 std::map<location_t, interface_var> out;
770
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800771 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
772 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700773 assert(insn != src->end());
774 assert(insn.opcode() == spv::OpVariable);
775
776 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800777 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700778 unsigned id = insn.word(2);
779 unsigned type = insn.word(1);
780
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800781 int location = d.location;
782 int builtin = d.builtin;
783 unsigned component = d.component;
784 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
785 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700786
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700787 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700788 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700789 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700790 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
791 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600792 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700793 for (unsigned int offset = 0; offset < num_locations; offset++) {
794 interface_var v = {};
795 v.id = id;
796 v.type_id = type;
797 v.offset = offset;
798 v.is_patch = is_patch;
799 v.is_relaxed_precision = is_relaxed_precision;
800 out[std::make_pair(location + offset, component)] = v;
801 }
Chris Forbes47567b72017-06-09 12:09:45 -0700802 }
803 }
804 }
805
806 return out;
807}
808
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600809static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200810 uint32_t storageClass) {
811 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700812 std::vector<uint32_t> builtin_struct_members;
813 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200814
sfricke-samsung94d71a52021-02-26 05:25:43 -0800815 for (auto insn : src->member_decoration_inst) {
816 if (insn.word(3) == spv::DecorationBuiltIn) {
817 builtin_struct_members.push_back(insn.word(1));
818 }
819 }
820 for (auto insn : src->decoration_inst) {
821 switch (insn.word(2)) {
822 case spv::DecorationBlock: {
823 uint32_t block_id = insn.word(1);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800824 for (auto builtin_block_id : builtin_struct_members) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800825 // Check if one of the members of the block are built-in -> the block is built-in
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800826 if (block_id == builtin_block_id) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800827 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200828 break;
829 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200830 }
831 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800832 }
833 case spv::DecorationBuiltIn:
834 builtin_decorations.push_back(insn.word(1));
835 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200836 default:
837 break;
838 }
839 }
840
841 // Find all interface variables belonging to the entrypoint and matching the storage class
842 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
843 auto def = src->get_def(id);
844 assert(def != src->end());
845 assert(def.opcode() == spv::OpVariable);
846
847 if (def.word(3) == storageClass) variables.push_back(def.word(1));
848 }
849
850 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700851 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200852 for (auto &var : variables) {
853 auto def = src->get_def(src->get_def(var).word(3));
854
855 // It could be an array of IO blocks. The element type should be the struct defining the block contents
856 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
857
858 // Now find all members belonging to the struct defining the IO block
859 if (def.opcode() == spv::OpTypeStruct) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800860 for (auto builtin_id : builtin_decorations) {
861 if (builtin_id == def.word(1)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700862 for (int i = 2; i < static_cast<int>(def.len()); i++) {
863 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
864 }
865 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800866 for (auto insn : src->member_decoration_inst) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800867 if (insn.word(1) == builtin_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700868 auto struct_index = insn.word(2);
869 assert(struct_index < builtin_block_members.size());
870 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200871 }
872 }
873 }
874 }
875 }
876 }
877
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700878 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200879}
880
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600881static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700882 SHADER_MODULE_STATE const *src, layer_data::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700883 std::vector<std::pair<uint32_t, interface_var>> out;
884
sfricke-samsung94d71a52021-02-26 05:25:43 -0800885 for (auto insn : src->decoration_inst) {
886 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
887 auto attachment_index = insn.word(3);
888 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700889
sfricke-samsung94d71a52021-02-26 05:25:43 -0800890 if (accessible_ids.count(id)) {
891 auto def = src->get_def(id);
892 assert(def != src->end());
893 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
894 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
895 for (unsigned int offset = 0; offset < num_locations; offset++) {
896 interface_var v = {};
897 v.id = id;
898 v.type_id = def.word(1);
899 v.offset = offset;
900 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700901 }
902 }
903 }
904 }
905 }
906
907 return out;
908}
909
locke-lunarg25b6c352020-08-06 17:44:18 -0600910static bool AtomicOperation(uint32_t opcode) {
911 switch (opcode) {
912 case spv::OpAtomicLoad:
913 case spv::OpAtomicStore:
914 case spv::OpAtomicExchange:
915 case spv::OpAtomicCompareExchange:
916 case spv::OpAtomicCompareExchangeWeak:
917 case spv::OpAtomicIIncrement:
918 case spv::OpAtomicIDecrement:
919 case spv::OpAtomicIAdd:
920 case spv::OpAtomicISub:
921 case spv::OpAtomicSMin:
922 case spv::OpAtomicUMin:
923 case spv::OpAtomicSMax:
924 case spv::OpAtomicUMax:
925 case spv::OpAtomicAnd:
926 case spv::OpAtomicOr:
927 case spv::OpAtomicXor:
928 case spv::OpAtomicFAddEXT:
929 return true;
930 default:
931 return false;
932 }
933 return false;
934}
935
sfricke-samsung0065ce02020-12-03 22:46:37 -0800936// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
937// covered with VUID 01090
938static bool GroupOperation(uint32_t opcode) {
939 switch (opcode) {
940 case spv::OpGroupNonUniformElect:
941 case spv::OpGroupNonUniformAll:
942 case spv::OpGroupNonUniformAny:
943 case spv::OpGroupNonUniformAllEqual:
944 case spv::OpGroupNonUniformBroadcast:
945 case spv::OpGroupNonUniformBroadcastFirst:
946 case spv::OpGroupNonUniformBallot:
947 case spv::OpGroupNonUniformInverseBallot:
948 case spv::OpGroupNonUniformBallotBitExtract:
949 case spv::OpGroupNonUniformBallotBitCount:
950 case spv::OpGroupNonUniformBallotFindLSB:
951 case spv::OpGroupNonUniformBallotFindMSB:
952 case spv::OpGroupNonUniformShuffle:
953 case spv::OpGroupNonUniformShuffleXor:
954 case spv::OpGroupNonUniformShuffleUp:
955 case spv::OpGroupNonUniformShuffleDown:
956 case spv::OpGroupNonUniformIAdd:
957 case spv::OpGroupNonUniformFAdd:
958 case spv::OpGroupNonUniformIMul:
959 case spv::OpGroupNonUniformFMul:
960 case spv::OpGroupNonUniformSMin:
961 case spv::OpGroupNonUniformUMin:
962 case spv::OpGroupNonUniformFMin:
963 case spv::OpGroupNonUniformSMax:
964 case spv::OpGroupNonUniformUMax:
965 case spv::OpGroupNonUniformFMax:
966 case spv::OpGroupNonUniformBitwiseAnd:
967 case spv::OpGroupNonUniformBitwiseOr:
968 case spv::OpGroupNonUniformBitwiseXor:
969 case spv::OpGroupNonUniformLogicalAnd:
970 case spv::OpGroupNonUniformLogicalOr:
971 case spv::OpGroupNonUniformLogicalXor:
972 case spv::OpGroupNonUniformQuadBroadcast:
973 case spv::OpGroupNonUniformQuadSwap:
974 case spv::OpGroupNonUniformPartitionNV:
975 return true;
976 default:
977 return false;
978 }
979 return false;
980}
981
locke-lunarg12d20992020-09-21 12:46:49 -0600982bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700983 const layer_data::unordered_map<unsigned, unsigned> &load_members,
984 const layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
locke-lunarg12d20992020-09-21 12:46:49 -0600985 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600986 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600987 auto load_it = load_members.find(load_id);
988 if (load_it == load_members.end()) {
989 continue;
990 }
991 if (load_it->second == object_id) {
992 return true;
993 }
994
995 auto accesschain_it = accesschain_members.find(load_it->second);
996 if (accesschain_it == accesschain_members.end()) {
997 continue;
998 }
999 if (accesschain_it->second.first == object_id) {
1000 return true;
1001 }
1002 }
1003 return false;
1004}
1005
locke-lunargae2a43c2020-09-22 17:21:57 -06001006bool CheckImageOperandsBiasOffset(uint32_t type) {
1007 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1008 spv::ImageOperandsConstOffsetsMask)
1009 ? true
1010 : false;
1011}
1012
locke-lunargd3da0422020-09-23 01:02:11 -06001013struct shader_module_used_operators {
1014 bool updated;
1015 std::vector<unsigned> imagwrite_members;
1016 std::vector<unsigned> atomic_members;
1017 std::vector<unsigned> store_members;
1018 std::vector<unsigned> atomic_store_members;
1019 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1020 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001021 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001022 layer_data::unordered_map<unsigned, unsigned> load_members;
1023 layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1024 layer_data::unordered_map<unsigned, unsigned> image_texel_pointer_members;
locke-lunargd3da0422020-09-23 01:02:11 -06001025
1026 shader_module_used_operators() : updated(false) {}
1027
1028 void update(SHADER_MODULE_STATE const *module) {
1029 if (updated) return;
1030 updated = true;
1031
1032 for (auto insn : *module) {
1033 switch (insn.opcode()) {
1034 case spv::OpImageSampleImplicitLod:
1035 case spv::OpImageSampleProjImplicitLod:
1036 case spv::OpImageSampleProjExplicitLod:
1037 case spv::OpImageSparseSampleImplicitLod:
1038 case spv::OpImageSparseSampleProjImplicitLod:
1039 case spv::OpImageSparseSampleProjExplicitLod: {
1040 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1041 // ImageOperands in index: 5
1042 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1043 sampler_bias_offset_members.emplace_back(insn.word(3));
1044 }
1045 break;
1046 }
1047 case spv::OpImageSampleDrefImplicitLod:
1048 case spv::OpImageSampleDrefExplicitLod:
1049 case spv::OpImageSampleProjDrefImplicitLod:
1050 case spv::OpImageSampleProjDrefExplicitLod:
1051 case spv::OpImageSparseSampleDrefImplicitLod:
1052 case spv::OpImageSparseSampleDrefExplicitLod:
1053 case spv::OpImageSparseSampleProjDrefImplicitLod:
1054 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1055 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1056 // ImageOperands in index: 6
1057 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1058 sampler_bias_offset_members.emplace_back(insn.word(3));
1059 }
1060 break;
1061 }
1062 case spv::OpImageSampleExplicitLod:
1063 case spv::OpImageSparseSampleExplicitLod: {
1064 // ImageOperands in index: 5
1065 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1066 sampler_bias_offset_members.emplace_back(insn.word(3));
1067 }
1068 break;
1069 }
1070 case spv::OpStore: {
1071 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1072 break;
1073 }
1074 case spv::OpImageWrite: {
1075 imagwrite_members.emplace_back(insn.word(1)); // Load id
1076 break;
1077 }
1078 case spv::OpSampledImage: {
1079 // 3: image load id, 4: sampler load id
1080 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1081 break;
1082 }
1083 case spv::OpLoad: {
1084 // 2: Load id, 3: object id or AccessChain id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001085 load_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001086 break;
1087 }
1088 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001089 if (insn.len() == 4) {
1090 // If it is for struct, the length is only 4.
1091 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001092 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0));
locke-lunarg025daa72020-10-13 11:07:51 -06001093 } else {
1094 // 2: AccessChain id, 3: object id, 4: object id of array index
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001095 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
locke-lunarg025daa72020-10-13 11:07:51 -06001096 }
locke-lunargd3da0422020-09-23 01:02:11 -06001097 break;
1098 }
1099 case spv::OpImageTexelPointer: {
1100 // 2: ImageTexelPointer id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001101 image_texel_pointer_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001102 break;
1103 }
1104 default: {
1105 if (AtomicOperation(insn.opcode())) {
1106 if (insn.opcode() == spv::OpAtomicStore) {
1107 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1108 } else {
1109 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1110 }
1111 }
1112 break;
1113 }
1114 }
1115 }
1116 }
1117};
1118
sfricke-samsung691299b2021-01-01 20:48:48 -08001119// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1120// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001121static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001122 bool is_check_writable, interface_var &out_interface_var,
1123 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001124 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001125 unsigned int id = id_it.word(2);
1126
Chris Forbes8af24522018-03-07 11:37:45 -08001127 auto type = module->get_def(type_id);
1128
1129 // 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 -06001130 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1131 type.opcode() == spv::OpTypeSampledImage) {
1132 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1133 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001134 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001135 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001136 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001137 }
1138 }
Chris Forbes8af24522018-03-07 11:37:45 -08001139 switch (type.opcode()) {
1140 case spv::OpTypeImage: {
1141 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001142 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001143 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001144
locke-lunargd3da0422020-09-23 01:02:11 -06001145 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1146 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001147 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001148 }
1149 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1150 used_operators.accesschain_members)) {
1151 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001152 }
locke-lunargd3da0422020-09-23 01:02:11 -06001153 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1154 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001155 out_interface_var.is_sampler_bias_offset = true;
1156 }
locke-lunargd3da0422020-09-23 01:02:11 -06001157 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1158 used_operators.accesschain_members) ||
1159 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1160 used_operators.accesschain_members)) {
1161 out_interface_var.is_atomic_operation = true;
1162 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001163
locke-lunargd3da0422020-09-23 01:02:11 -06001164 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001165 // Find if image id match.
1166 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001167 auto load_it = used_operators.load_members.find(itp_id.first);
1168 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001169 continue;
1170 } else {
1171 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001172 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1173 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001174 continue;
1175 } else {
1176 if (accesschain_it->second.first != id) {
1177 continue;
1178 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001179
1180 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1181 if (const_itr == module->end()) {
1182 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001183 break;
1184 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001185 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001186 }
1187 }
1188 }
1189 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001190 load_it = used_operators.load_members.find(itp_id.second);
1191 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001192 continue;
1193 } else {
1194 uint32_t sampler_id = load_it->second;
1195 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001196 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001197
locke-lunargd3da0422020-09-23 01:02:11 -06001198 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001199 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1200 if (const_itr == module->end()) {
1201 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001202 break;
1203 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001204 sampler_id = const_itr.offset();
1205 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001206 }
1207 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001208 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1209 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1210 }
1211 out_interface_var.samplers_used_by_image[image_index].emplace(
1212 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001213 }
1214 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001215 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001216 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001217 }
1218
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001219 case spv::OpTypeStruct: {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001220 layer_data::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001221 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001222 for (auto insn : module->member_decoration_inst) {
1223 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001224 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001225 }
1226 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001227
1228 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1229 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001230 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001231 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001232
locke-lunargd3da0422020-09-23 01:02:11 -06001233 for (auto oid : used_operators.store_members) {
1234 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001235 out_interface_var.is_writable = true;
1236 return;
1237 }
locke-lunargd3da0422020-09-23 01:02:11 -06001238 auto accesschain_it = used_operators.accesschain_members.find(oid);
1239 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001240 continue;
1241 }
locke-lunargd3da0422020-09-23 01:02:11 -06001242 if (accesschain_it->second.first == id) {
1243 out_interface_var.is_writable = true;
1244 return;
1245 }
1246 }
1247 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1248 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001249 out_interface_var.is_writable = true;
1250 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001251 }
1252 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001253 }
Chris Forbes8af24522018-03-07 11:37:45 -08001254 }
Chris Forbes8af24522018-03-07 11:37:45 -08001255}
1256
locke-lunargd9a069d2019-09-17 01:50:19 -06001257std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001258 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 -06001259 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001260 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001261 shader_module_used_operators operators;
1262
Chris Forbes47567b72017-06-09 12:09:45 -07001263 for (auto id : accessible_ids) {
1264 auto insn = src->get_def(id);
1265 assert(insn != src->end());
1266
1267 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001268 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1269 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001270 auto d = src->get_decorations(insn.word(2));
1271 unsigned set = d.descriptor_set;
1272 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001273
1274 interface_var v = {};
1275 v.id = insn.word(2);
1276 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001277
locke-lunarg25b6c352020-08-06 17:44:18 -06001278 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001279 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001280 if (v.is_writable) *has_writable_descriptor = true;
1281 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001282 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001283 }
1284 }
1285
1286 return out;
1287}
1288
locke-lunargde3f0fa2020-09-10 11:55:31 -06001289void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1290 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1291 const auto struct_it = GetStructType(&src, it, false);
1292 assert(struct_it != src.end());
1293 data.size = 0;
1294
1295 shader_struct_member data1;
1296 uint32_t i = 2;
1297 uint32_t local_offset = 0;
1298 std::vector<uint32_t> offsets;
1299 offsets.resize(struct_it.len() - i);
1300
1301 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1302 for (const auto offset : memberDecorate_offsets) {
1303 const auto member_decorate = src.at(offset);
1304 if (member_decorate.word(1) != struct_it.word(1)) {
1305 continue;
1306 }
1307
1308 offsets[member_decorate.word(2)] = member_decorate.word(4);
1309 }
1310
1311 for (const auto offset : offsets) {
1312 local_offset = offset;
1313 data1 = {};
1314 data1.root = data.root;
1315 data1.offset = local_offset;
1316 auto def_member = src.get_def(struct_it.word(i));
1317
1318 // Array could be multi-dimensional
1319 while (def_member.opcode() == spv::OpTypeArray) {
1320 const auto len_id = def_member.word(3);
1321 const auto def_len = src.get_def(len_id);
1322 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1323 def_member = src.get_def(def_member.word(2));
1324 }
1325
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001326 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001327 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001328 } else if (def_member.opcode() == spv::OpTypePointer) {
1329 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1330 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1331 // that "points to something."
1332 data1.size = 8;
1333 } else {
1334 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1335 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1336 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001337 } else {
1338 if (def_member.opcode() == spv::OpTypeMatrix) {
1339 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1340 def_member = src.get_def(def_member.word(2));
1341 }
1342
1343 if (def_member.opcode() == spv::OpTypeVector) {
1344 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1345 def_member = src.get_def(def_member.word(2));
1346 }
1347
1348 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1349 data1.size = (def_member.word(2) / 8);
1350 }
1351 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1352 if (array_length_hierarchy_szie > 0) {
1353 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1354
1355 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1356 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1357 }
1358 }
1359 data.struct_members.emplace_back(data1);
1360 ++i;
1361 }
1362 uint32_t total_array_length = 1;
1363 for (const auto length : data1.array_length_hierarchy) {
1364 total_array_length *= length;
1365 }
1366 data.size = local_offset + data1.size * total_array_length;
1367}
1368
1369uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1370 int array_indices_size = static_cast<int>(array_indices.size());
1371 if (array_indices_size) {
1372 uint32_t array_index = 0;
1373 uint32_t i = 0;
1374 for (const auto index : array_indices) {
1375 array_index += (data.array_block_size[i] * index);
1376 ++i;
1377 }
1378 offset += (array_index * data.size);
1379 }
1380 return offset;
1381}
1382
1383void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1384 int array_indices_size = static_cast<int>(array_indices.size());
1385 uint32_t block_memory_size = data.size;
1386 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1387 block_memory_size *= data.array_length_hierarchy[i];
1388 }
1389
1390 offset = UpdateOffset(offset, array_indices, data);
1391
1392 uint32_t end = offset + block_memory_size;
1393 auto used_bytes = data.GetUsedbytes();
1394 if (used_bytes->size() < end) {
1395 used_bytes->resize(end, 0);
1396 }
1397 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1398}
1399
1400void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1401 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1402 if (access_chain_word_index < access_chain_it.len()) {
1403 if (data.array_length_hierarchy.size() > array_indices.size()) {
1404 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1405 ++access_chain_word_index;
1406
1407 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1408 array_indices.emplace_back(def_it.word(3));
1409 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1410 } else {
1411 // If it is a variable, set the all array is used.
1412 if (access_chain_word_index < access_chain_it.len()) {
1413 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1414 for (uint32_t i = 0; i < array_length; ++i) {
1415 auto array_indices2 = array_indices;
1416 array_indices2.emplace_back(i);
1417 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1418 }
1419 } else {
1420 SetUsedBytes(offset, array_indices, data);
1421 }
1422 }
1423 } else {
1424 offset = UpdateOffset(offset, array_indices, data);
1425 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1426 }
1427 } else {
1428 SetUsedBytes(offset, array_indices, data);
1429 }
1430}
1431
1432void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1433 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1434 std::vector<uint32_t> array_indices_emptry;
1435
1436 if (access_chain_word_index < access_chain_it.len()) {
1437 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1438 ++access_chain_word_index;
1439
1440 auto data1 = data.struct_members[strcut_member_index];
1441 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1442 }
1443}
1444
1445void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1446 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1447 for (const auto &func_set : function_set_list) {
1448 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1449 for (auto it = range.first; it != range.second; ++it) {
1450 auto access_chain = src.at(it->second);
1451 if (access_chain.word(3) == variable_id) {
1452 RunUsedStruct(src, 0, 4, access_chain, data);
1453 }
1454 }
1455 }
1456}
1457
1458void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1459 for (auto &entrypoint : src.entry_points) {
1460 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1461 for (auto it = range.first; it != range.second; ++it) {
1462 const auto def_insn = src.at(it->second);
1463
1464 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1465 spirv_inst_iter type = src.get_def(def_insn.word(1));
1466 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1467 std::vector<uint32_t> offsets;
1468
1469 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1470 auto member_decorate = src.at(it2->second);
1471 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1472 offsets.emplace_back(member_decorate.offset());
1473 }
1474 }
1475 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1476 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1477 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1478 entrypoint.second.push_constant_used_in_shader);
1479 }
1480 }
1481 }
1482}
1483
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001484layer_data::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
locke-lunarg96dc9632020-06-10 17:22:18 -06001485 const VkPipelineShaderStageCreateInfo &stage_info) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001486 layer_data::unordered_set<uint32_t> location_list;
locke-lunarg96dc9632020-06-10 17:22:18 -06001487 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1488 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1489 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001490 layer_data::unordered_set<unsigned> store_members;
1491 layer_data::unordered_map<unsigned, unsigned> accesschain_members;
locke-lunarg96dc9632020-06-10 17:22:18 -06001492
1493 for (auto insn : module) {
1494 switch (insn.opcode()) {
1495 case spv::OpStore:
1496 case spv::OpAtomicStore: {
1497 store_members.insert(insn.word(1)); // object id or AccessChain id
1498 break;
1499 }
1500 case spv::OpAccessChain: {
1501 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001502 if (insn.word(3)) accesschain_members.emplace(insn.word(2), insn.word(3));
locke-lunarg96dc9632020-06-10 17:22:18 -06001503 break;
1504 }
1505 default:
1506 break;
1507 }
1508 }
1509 if (store_members.empty()) {
1510 return location_list;
1511 }
1512 for (auto output : outputs) {
1513 auto store_it = store_members.find(output.second.id);
1514 if (store_it != store_members.end()) {
1515 location_list.insert(output.first.first);
1516 store_members.erase(store_it);
1517 continue;
1518 }
1519 store_it = store_members.begin();
1520 while (store_it != store_members.end()) {
1521 auto accesschain_it = accesschain_members.find(*store_it);
1522 if (accesschain_it == accesschain_members.end()) {
1523 ++store_it;
1524 continue;
1525 }
1526 if (accesschain_it->second == output.second.id) {
1527 location_list.insert(output.first.first);
1528 store_members.erase(store_it);
1529 accesschain_members.erase(accesschain_it);
1530 break;
1531 }
1532 ++store_it;
1533 }
1534 }
1535 return location_list;
1536}
1537
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001538bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001539 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1540 // be specified only once.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001541 layer_data::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
Chris Forbes47567b72017-06-09 12:09:45 -07001542 bool skip = false;
1543
1544 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1545 auto desc = &vi->pVertexBindingDescriptions[i];
1546 auto &binding = bindings[desc->binding];
1547 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001548 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001549 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1550 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001551 } else {
1552 binding = desc;
1553 }
1554 }
1555
1556 return skip;
1557}
1558
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001559bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1560 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001561 bool skip = false;
1562
Petr Kraus25810d02019-08-27 17:41:15 +02001563 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001564
1565 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001566 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001567 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001568 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1569 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1570 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001571 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1572 }
1573 }
1574 }
1575
Petr Kraus25810d02019-08-27 17:41:15 +02001576 struct AttribInputPair {
1577 const VkVertexInputAttributeDescription *attrib = nullptr;
1578 const interface_var *input = nullptr;
1579 };
1580 std::map<uint32_t, AttribInputPair> location_map;
1581 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1582 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001583
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001584 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001585 const auto location = location_it.first;
1586 const auto attrib = location_it.second.attrib;
1587 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001588
Petr Kraus25810d02019-08-27 17:41:15 +02001589 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001590 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1591 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001592 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001593 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1594 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001595 } else if (attrib && input) {
1596 const auto attrib_type = GetFormatType(attrib->format);
1597 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001598
1599 // Type checking
1600 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001601 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1602 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1603 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001604 }
Petr Kraus25810d02019-08-27 17:41:15 +02001605 } else { // !attrib && !input
1606 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001607 }
1608 }
1609
1610 return skip;
1611}
1612
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001613bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1614 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001615 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001616
Petr Kraus25810d02019-08-27 17:41:15 +02001617 const auto rpci = pipeline->rp_state->createInfo.ptr();
1618
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001619 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001620 const VkAttachmentReference2 *reference = nullptr;
1621 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001622 const interface_var *output = nullptr;
1623 };
1624 std::map<uint32_t, Attachment> location_map;
1625
Petr Kraus25810d02019-08-27 17:41:15 +02001626 const auto subpass = rpci->pSubpasses[subpass_index];
1627 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001628 auto const &reference = subpass.pColorAttachments[i];
1629 location_map[i].reference = &reference;
1630 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1631 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1632 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001633 }
1634 }
1635
Chris Forbes47567b72017-06-09 12:09:45 -07001636 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1637
Petr Kraus25810d02019-08-27 17:41:15 +02001638 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001639 for (const auto &output_it : outputs) {
1640 auto const location = output_it.first.first;
1641 location_map[location].output = &output_it.second;
1642 }
Chris Forbes47567b72017-06-09 12:09:45 -07001643
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001644 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1645 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001646
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001647 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001648 const auto reference = location_it.second.reference;
1649 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1650 continue;
1651 }
1652
Petr Kraus25810d02019-08-27 17:41:15 +02001653 const auto location = location_it.first;
1654 const auto attachment = location_it.second.attachment;
1655 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001656 if (attachment && !output) {
1657 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001658 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1659 "Attachment %" PRIu32
1660 " not written by fragment shader; undefined values will be written to attachment",
1661 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001662 }
1663 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001664 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001665 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1666 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001667 }
Petr Kraus25810d02019-08-27 17:41:15 +02001668 } else if (attachment && output) {
1669 const auto attachment_type = GetFormatType(attachment->format);
1670 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001671
1672 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001673 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001674 skip |=
1675 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1676 "Attachment %" PRIu32
1677 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1678 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001679 }
Petr Kraus25810d02019-08-27 17:41:15 +02001680 } else { // !attachment && !output
1681 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001682 }
1683 }
1684
Petr Kraus25810d02019-08-27 17:41:15 +02001685 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001686 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1687 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1688 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001689 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1690 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001691 }
1692
Chris Forbes47567b72017-06-09 12:09:45 -07001693 return skip;
1694}
1695
Tobias Hector6663c9b2020-11-05 10:18:02 +00001696// 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 -06001697// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001698static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001699 auto type = builtin_instr.opcode();
1700 uint32_t target_id = builtin_instr.word(1);
1701 bool init_complete = false;
1702
1703 if (type == spv::OpMemberDecorate) {
1704 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1705 auto insn = entrypoint;
1706 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1707 switch (insn.opcode()) {
1708 case spv::OpTypePointer:
1709 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1710 target_id = insn.word(1);
1711 }
1712 break;
1713 case spv::OpVariable:
1714 if (insn.word(1) == target_id) {
1715 target_id = insn.word(2);
1716 init_complete = true;
1717 }
1718 break;
1719 }
1720 insn++;
1721 }
1722 }
1723
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001724 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1725
1726 bool found_write = false;
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001727 layer_data::unordered_set<uint32_t> worklist;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001728 worklist.insert(entrypoint.word(2));
1729
1730 // Follow instructions in call graph looking for writes to target
1731 while (!worklist.empty() && !found_write) {
1732 auto id_iter = worklist.begin();
1733 auto id = *id_iter;
1734 worklist.erase(id_iter);
1735
1736 auto insn = src->get_def(id);
1737 if (insn == src->end()) {
1738 continue;
1739 }
1740
1741 if (insn.opcode() == spv::OpFunction) {
1742 // Scan body of function looking for other function calls or items in our ID chain
1743 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1744 switch (insn.opcode()) {
1745 case spv::OpAccessChain:
1746 if (insn.word(3) == target_id) {
1747 if (type == spv::OpMemberDecorate) {
1748 auto value = GetConstantValue(src, insn.word(4));
1749 if (value == builtin_instr.word(2)) {
1750 target_id = insn.word(2);
1751 }
1752 } else {
1753 target_id = insn.word(2);
1754 }
1755 }
1756 break;
1757 case spv::OpStore:
1758 if (insn.word(1) == target_id) {
1759 found_write = true;
1760 }
1761 break;
1762 case spv::OpFunctionCall:
1763 worklist.insert(insn.word(3));
1764 break;
1765 }
1766 }
1767 }
1768 }
1769 return found_write;
1770}
1771
Chris Forbes47567b72017-06-09 12:09:45 -07001772// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1773// important for identifying the set of shader resources actually used by an entrypoint, for example.
1774// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1775// - NOT the shader input/output interfaces.
1776//
1777// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1778// converting parts of this to be generated from the machine-readable spec instead.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001779layer_data::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
1780 layer_data::unordered_set<uint32_t> ids;
1781 layer_data::unordered_set<uint32_t> worklist;
Chris Forbes47567b72017-06-09 12:09:45 -07001782 worklist.insert(entrypoint.word(2));
1783
1784 while (!worklist.empty()) {
1785 auto id_iter = worklist.begin();
1786 auto id = *id_iter;
1787 worklist.erase(id_iter);
1788
1789 auto insn = src->get_def(id);
1790 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001791 // 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 -07001792 // that we may not care about.
1793 continue;
1794 }
1795
1796 // Try to add to the output set
1797 if (!ids.insert(id).second) {
1798 continue; // If we already saw this id, we don't want to walk it again.
1799 }
1800
1801 switch (insn.opcode()) {
1802 case spv::OpFunction:
1803 // Scan whole body of the function, enlisting anything interesting
1804 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1805 switch (insn.opcode()) {
1806 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001807 worklist.insert(insn.word(3)); // ptr
1808 break;
1809 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001810 worklist.insert(insn.word(1)); // ptr
1811 break;
1812 case spv::OpAccessChain:
1813 case spv::OpInBoundsAccessChain:
1814 worklist.insert(insn.word(3)); // base ptr
1815 break;
1816 case spv::OpSampledImage:
1817 case spv::OpImageSampleImplicitLod:
1818 case spv::OpImageSampleExplicitLod:
1819 case spv::OpImageSampleDrefImplicitLod:
1820 case spv::OpImageSampleDrefExplicitLod:
1821 case spv::OpImageSampleProjImplicitLod:
1822 case spv::OpImageSampleProjExplicitLod:
1823 case spv::OpImageSampleProjDrefImplicitLod:
1824 case spv::OpImageSampleProjDrefExplicitLod:
1825 case spv::OpImageFetch:
1826 case spv::OpImageGather:
1827 case spv::OpImageDrefGather:
1828 case spv::OpImageRead:
1829 case spv::OpImage:
1830 case spv::OpImageQueryFormat:
1831 case spv::OpImageQueryOrder:
1832 case spv::OpImageQuerySizeLod:
1833 case spv::OpImageQuerySize:
1834 case spv::OpImageQueryLod:
1835 case spv::OpImageQueryLevels:
1836 case spv::OpImageQuerySamples:
1837 case spv::OpImageSparseSampleImplicitLod:
1838 case spv::OpImageSparseSampleExplicitLod:
1839 case spv::OpImageSparseSampleDrefImplicitLod:
1840 case spv::OpImageSparseSampleDrefExplicitLod:
1841 case spv::OpImageSparseSampleProjImplicitLod:
1842 case spv::OpImageSparseSampleProjExplicitLod:
1843 case spv::OpImageSparseSampleProjDrefImplicitLod:
1844 case spv::OpImageSparseSampleProjDrefExplicitLod:
1845 case spv::OpImageSparseFetch:
1846 case spv::OpImageSparseGather:
1847 case spv::OpImageSparseDrefGather:
1848 case spv::OpImageTexelPointer:
1849 worklist.insert(insn.word(3)); // Image or sampled image
1850 break;
1851 case spv::OpImageWrite:
1852 worklist.insert(insn.word(1)); // Image -- different operand order to above
1853 break;
1854 case spv::OpFunctionCall:
1855 for (uint32_t i = 3; i < insn.len(); i++) {
1856 worklist.insert(insn.word(i)); // fn itself, and all args
1857 }
1858 break;
1859
1860 case spv::OpExtInst:
1861 for (uint32_t i = 5; i < insn.len(); i++) {
1862 worklist.insert(insn.word(i)); // Operands to ext inst
1863 }
1864 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001865
1866 default: {
1867 if (AtomicOperation(insn.opcode())) {
1868 if (insn.opcode() == spv::OpAtomicStore) {
1869 worklist.insert(insn.word(1)); // ptr
1870 } else {
1871 worklist.insert(insn.word(3)); // ptr
1872 }
1873 }
1874 break;
1875 }
Chris Forbes47567b72017-06-09 12:09:45 -07001876 }
1877 }
1878 break;
1879 }
1880 }
1881
1882 return ids;
1883}
1884
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001885PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1886 const shader_struct_member &push_constant_used_in_shader,
1887 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001888 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001889 const auto used_bytes_size = used_bytes->size();
1890 if (used_bytes_size == 0) return PC_Byte_Updated;
1891
1892 const auto push_constant_data_update_size = push_constant_data_update.size();
1893 const auto *data = push_constant_data_update.data();
1894 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1895 if (used_bytes_size <= push_constant_data_update_size) {
1896 return PC_Byte_Updated;
1897 }
1898 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1899
1900 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1901 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1902 return PC_Byte_Updated;
1903 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001904 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001905
locke-lunargde3f0fa2020-09-10 11:55:31 -06001906 uint32_t i = 0;
1907 for (const auto used : *used_bytes) {
1908 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001909 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001910 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001911 return PC_Byte_Not_Set;
1912 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001913 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001914 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001915 }
1916 }
1917 ++i;
1918 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001919 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001920}
1921
1922bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
sfricke-samsung7699b912021-04-12 23:01:51 -07001923 VkPipelineShaderStageCreateInfo const *pStage, const std::string &vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001924 bool skip = false;
sfricke-samsung5c65b372021-03-25 05:39:57 -07001925 // Temp workaround to prevent false positive errors
1926 // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/2450
1927 if (src->multiple_entry_points) {
1928 return skip;
1929 }
1930
Chris Forbes47567b72017-06-09 12:09:45 -07001931 // 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 -06001932 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1933 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1934 return skip;
1935 }
1936 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001937
locke-lunargde3f0fa2020-09-10 11:55:31 -06001938 bool found_stage = false;
1939 for (auto const &range : *push_constant_ranges) {
1940 if (range.stageFlags & pStage->stage) {
1941 found_stage = true;
1942 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001943 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001944 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001945 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001946 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001947 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001948 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001949 const auto ret =
1950 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001951
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001952 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001953 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1954 LogObjectList objlist(src->vk_shader_module);
1955 objlist.add(pipeline.pipeline_layout->layout);
sfricke-samsung7699b912021-04-12 23:01:51 -07001956 skip |= LogError(objlist, vuid, "Push constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
locke-lunargde3f0fa2020-09-10 11:55:31 -06001957 string_VkShaderStageFlags(pStage->stage).c_str(),
1958 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1959 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001960 }
1961 }
1962 }
1963
locke-lunargde3f0fa2020-09-10 11:55:31 -06001964 if (!found_stage) {
1965 LogObjectList objlist(src->vk_shader_module);
1966 objlist.add(pipeline.pipeline_layout->layout);
sfricke-samsung7699b912021-04-12 23:01:51 -07001967 skip |= LogError(objlist, vuid, "Push constant is used in %s of %s. But %s doesn't set %s.",
1968 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1969 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(),
1970 string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001971 }
Chris Forbes47567b72017-06-09 12:09:45 -07001972 return skip;
1973}
1974
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001975bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const layer_data::unordered_set<uint32_t> &accessible_ids,
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001976 VkShaderStageFlagBits stage) const {
1977 bool skip = false;
1978
1979 // Currently all builtin tested are only found in fragment shaders
1980 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1981 return skip;
1982 }
1983
1984 for (const auto id : accessible_ids) {
1985 auto insn = src->get_def(id);
1986 const decoration_set decorations = src->get_decorations(insn.word(2));
1987
1988 // Built-ins are obtained from OpVariable
1989 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1990 auto type_pointer = src->get_def(insn.word(1));
1991 assert(type_pointer.opcode() == spv::OpTypePointer);
1992
1993 auto type = src->get_def(type_pointer.word(3));
1994 if (type.opcode() == spv::OpTypeArray) {
1995 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1996
1997 switch (decorations.builtin) {
1998 case spv::BuiltInSampleMask:
1999 // Handles both the input and output sampleMask
2000 if (length > phys_dev_props.limits.maxSampleMaskWords) {
2001 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
2002 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
2003 "maxSampleMaskWords of %u in %s.",
2004 length, phys_dev_props.limits.maxSampleMaskWords,
2005 report_data->FormatHandle(src->vk_shader_module).c_str());
2006 }
2007 break;
2008 }
2009 }
2010 }
2011 }
2012
2013 return skip;
2014}
2015
Chris Forbes47567b72017-06-09 12:09:45 -07002016// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002017bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002018 bool skip = false;
2019
2020 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2021
2022 if (spec) {
2023 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002024 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002025 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
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->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002030
2031 continue;
2032 }
Chris Forbes47567b72017-06-09 12:09:45 -07002033 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002034 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2035 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2036 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2037 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2038 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002039 }
2040 }
2041 }
2042
2043 return skip;
2044}
2045
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002046// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002047static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2048 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002049 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002050 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002051 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002052 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002053
2054 // 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 -05002055 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2056 if (type.opcode() == spv::OpTypeRuntimeArray) {
2057 descriptor_count = 0;
2058 type = module->get_def(type.word(2));
2059 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002060 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002061 type = module->get_def(type.word(2));
2062 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002063 if (type.word(2) == spv::StorageClassStorageBuffer) {
2064 is_storage_buffer = true;
2065 }
Chris Forbes47567b72017-06-09 12:09:45 -07002066 type = module->get_def(type.word(3));
2067 }
2068 }
2069
2070 switch (type.opcode()) {
2071 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002072 for (auto insn : module->decoration_inst) {
2073 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002074 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002075 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002076 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2077 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2078 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002079 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002080 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2081 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2082 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2083 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002084 }
Chris Forbes47567b72017-06-09 12:09:45 -07002085 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002086 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2087 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2088 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002089 }
2090 }
2091 }
2092
2093 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002094 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002095 }
2096
2097 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002098 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2099 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2100 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002101
Chris Forbes73c00bf2018-06-22 16:28:06 -07002102 case spv::OpTypeSampledImage: {
2103 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2104 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2105 auto image_type = module->get_def(type.word(2));
2106 auto dim = image_type.word(3);
2107 auto sampled = image_type.word(7);
2108 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002109 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2110 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002111 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002112 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002113 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2114 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002115
2116 case spv::OpTypeImage: {
2117 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2118 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2119 auto dim = type.word(3);
2120 auto sampled = type.word(7);
2121
2122 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002123 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2124 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002125 } else if (dim == spv::DimBuffer) {
2126 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002127 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2128 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002129 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002130 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2131 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002132 }
2133 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002134 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2135 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2136 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002137 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002138 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2139 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002140 }
2141 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002142 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002143 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2144 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002145 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002146
2147 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2148 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002149 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002150 }
2151}
2152
Jeff Bolze54ae892018-09-08 12:16:29 -05002153static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002154 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002155 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2156 if (ss.tellp()) ss << ", ";
2157 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002158 }
2159 return ss.str();
2160}
2161
sfricke-samsung0065ce02020-12-03 22:46:37 -08002162bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002163 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002164 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 -05002165 return true;
2166 }
2167 }
2168
2169 return false;
2170}
2171
sfricke-samsung0065ce02020-12-03 22:46:37 -08002172bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002173 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002174 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002175 return true;
2176 }
2177 }
2178
2179 return false;
2180}
2181
locke-lunarg63e4daf2020-08-17 17:53:25 -06002182bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2183 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002184 bool skip = false;
2185
locke-lunarg63e4daf2020-08-17 17:53:25 -06002186 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002187 switch (stage) {
2188 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002189 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2190 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2191 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2192 case VK_SHADER_STAGE_MISS_BIT_NV:
2193 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2194 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2195 case VK_SHADER_STAGE_TASK_BIT_NV:
2196 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002197 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002198 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002199 break;
2200 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002201 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2202 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002203 break;
2204 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002205 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2206 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002207 break;
2208 }
2209 }
2210
Chris Forbes47567b72017-06-09 12:09:45 -07002211 return skip;
2212}
2213
sfricke-samsung94167ca2021-02-26 04:14:59 -08002214bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2215 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002216 bool skip = false;
2217
sfricke-samsung94167ca2021-02-26 04:14:59 -08002218 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2219 if (GroupOperation(insn.opcode()) == true) {
2220 // Check the quad operations.
2221 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2222 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2223 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2224 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2225 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002226 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002227 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002228
sfricke-samsung94167ca2021-02-26 04:14:59 -08002229 uint32_t scope_type = spv::ScopeMax;
2230 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2231 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2232 scope_type = spv::ScopeSubgroup;
2233 } else {
2234 // "All <id> used for Scope <id> must be of an OpConstant"
2235 auto scope_id = module->get_def(insn.word(3));
2236 scope_type = scope_id.word(3);
2237 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002238
sfricke-samsung94167ca2021-02-26 04:14:59 -08002239 if (scope_type == spv::ScopeSubgroup) {
2240 // "Group operations with subgroup scope" must have stage support
2241 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2242 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002243 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002244 }
2245
2246 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2247 auto type = module->get_def(insn.word(1));
2248
2249 if (type.opcode() == spv::OpTypeVector) {
2250 // Get the element type
2251 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002252 }
2253
sfricke-samsung94167ca2021-02-26 04:14:59 -08002254 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002255 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2256 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002257
sfricke-samsung0065ce02020-12-03 22:46:37 -08002258 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2259 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2260 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2261 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2262 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002263 }
2264 }
2265 }
Jeff Bolzee743412019-06-20 22:24:32 -05002266 }
2267
2268 return skip;
2269}
2270
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002271bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002272 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002273 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2274 pStage->stage == VK_SHADER_STAGE_ALL) {
2275 return false;
2276 }
2277
2278 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002279 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002280
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002281 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002282 struct Variable {
2283 uint32_t baseTypePtrID;
2284 uint32_t ID;
2285 uint32_t storageClass;
2286 };
2287 std::vector<Variable> variables;
2288
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002289 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002290 bool is_iso_lines = false;
2291 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002292
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002293 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002294
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002295 for (auto insn : *src) {
2296 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002297 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002298 case spv::OpDecorate:
2299 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002300 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002301 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002302 break;
2303 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002304 default:
2305 break;
2306 }
2307 break;
2308 // Find all input and output variables
2309 case spv::OpVariable: {
2310 Variable var = {};
2311 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002312 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2313 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002314 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002315 var.baseTypePtrID = insn.word(1);
2316 var.ID = insn.word(2);
2317 variables.push_back(var);
2318 }
2319 break;
2320 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002321 case spv::OpExecutionMode:
2322 if (insn.word(1) == entrypoint.word(2)) {
2323 switch (insn.word(2)) {
2324 default:
2325 break;
2326 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002327 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002328 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002329 case spv::ExecutionModeIsolines:
2330 is_iso_lines = true;
2331 break;
2332 case spv::ExecutionModePointMode:
2333 is_point_mode = true;
2334 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002335 }
2336 }
2337 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002338 default:
2339 break;
2340 }
2341 }
2342
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002343 bool strip_output_array_level =
2344 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2345 bool strip_input_array_level =
2346 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2347 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2348
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002349 uint32_t num_comp_in = 0, num_comp_out = 0;
2350 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002351
2352 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2353 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2354
2355 // Find max component location used for input variables.
2356 for (auto &var : inputs) {
2357 int location = var.first.first;
2358 int component = var.first.second;
2359 interface_var &iv = var.second;
2360
2361 // Only need to look at the first location, since we use the type's whole size
2362 if (iv.offset != 0) {
2363 continue;
2364 }
2365
2366 if (iv.is_patch) {
2367 continue;
2368 }
2369
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002370 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2371 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002372 }
2373
2374 // Find max component location used for output variables.
2375 for (auto &var : outputs) {
2376 int location = var.first.first;
2377 int component = var.first.second;
2378 interface_var &iv = var.second;
2379
2380 // Only need to look at the first location, since we use the type's whole size
2381 if (iv.offset != 0) {
2382 continue;
2383 }
2384
2385 if (iv.is_patch) {
2386 continue;
2387 }
2388
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002389 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2390 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002391 }
2392
2393 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2394 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002395 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002396 // Check if the variable is a patch. Patches can also be members of blocks,
2397 // but if they are then the top-level arrayness has already been stripped
2398 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002399 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002400
2401 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002402 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002403 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002404 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002405 }
2406 }
2407
2408 switch (pStage->stage) {
2409 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002410 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002411 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2412 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2413 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2414 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002415 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002416 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002417 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002418 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2419 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2420 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2421 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002422 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002423 break;
2424
2425 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002426 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002427 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2428 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2429 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2430 "components by %u components",
2431 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002432 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002433 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002435 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002436 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2437 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2438 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2439 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002440 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002441 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002442 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2443 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2444 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2445 "components by %u components",
2446 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002447 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002448 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002449 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002450 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002451 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2452 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2453 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2454 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002455 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002456 break;
2457
2458 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002459 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002460 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2461 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2462 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2463 "components by %u components",
2464 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002465 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002466 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002467 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002468 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002469 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2470 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2471 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2472 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002473 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002474 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002475 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2476 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2477 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2478 "components by %u components",
2479 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002480 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002481 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002482 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002483 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002484 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2485 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2486 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2487 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002488 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002489 // Portability validation
2490 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2491 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2492 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2493 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2494 " is using abstract patch type IsoLines, but this is not supported on this platform");
2495 }
2496 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2497 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2498 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2499 " is using abstract patch type PointMode, but this is not supported on this platform");
2500 }
2501 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002502 break;
2503
2504 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002505 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002506 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2507 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2508 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2509 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002510 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002511 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002512 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002513 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2514 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2515 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2516 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002517 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002518 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002519 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2520 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2521 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2522 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002523 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002524 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002525 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002526 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2527 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2528 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2529 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002530 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002531 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002532 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2533 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2534 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2535 "components by %u components",
2536 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002537 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002538 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002539 break;
2540
2541 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002542 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002543 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2544 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2545 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2546 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002547 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002548 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002549 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002550 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2551 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2552 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2553 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002554 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002555 break;
2556
Jeff Bolz148d94e2018-12-13 21:25:56 -06002557 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2558 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2559 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2560 case VK_SHADER_STAGE_MISS_BIT_NV:
2561 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2562 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2563 case VK_SHADER_STAGE_TASK_BIT_NV:
2564 case VK_SHADER_STAGE_MESH_BIT_NV:
2565 break;
2566
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002567 default:
2568 assert(false); // This should never happen
2569 }
2570 return skip;
2571}
2572
sfricke-samsungdc96f302020-03-18 20:42:10 -07002573bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2574 bool skip = false;
2575 uint32_t total_resources = 0;
2576
2577 // Only currently testing for graphics and compute pipelines
2578 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2579 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2580 return false;
2581 }
2582
2583 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2584 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2585 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2586 }
2587
2588 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2589 // input from CreatePipeline and CreatePipelineLayout level
2590 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2591 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2592 continue;
2593 }
2594
2595 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2596 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2597 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2598 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2599 // Check only descriptor types listed in maxPerStageResources description in spec
2600 switch (binding->descriptorType) {
2601 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2602 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2603 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2604 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2605 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2606 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2607 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2608 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2609 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2610 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2611 total_resources += binding->descriptorCount;
2612 break;
2613 default:
2614 break;
2615 }
2616 }
2617 }
2618 }
2619
2620 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2621 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2622 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2623 skip |= LogError(pipeline->pipeline, vuid,
2624 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2625 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2626 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2627 }
2628
2629 return skip;
2630}
2631
Jeff Bolze4356752019-03-07 11:23:46 -06002632// copy the specialization constant value into buf, if it is present
2633void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2634 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2635
2636 if (spec && spec_id < spec->mapEntryCount) {
2637 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2638 }
2639}
2640
2641// Fill in value with the constant or specialization constant value, if available.
2642// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002643static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002644 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
Jeff Bolze4356752019-03-07 11:23:46 -06002645 auto type_id = src->get_def(insn.word(1));
2646 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2647 return false;
2648 }
2649 switch (insn.opcode()) {
2650 case spv::OpSpecConstant:
2651 *value = insn.word(3);
2652 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2653 return true;
2654 case spv::OpConstant:
2655 *value = insn.word(3);
2656 return true;
2657 default:
2658 return false;
2659 }
2660}
2661
2662// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002663VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002664 switch (insn.opcode()) {
2665 case spv::OpTypeInt:
2666 switch (insn.word(2)) {
2667 case 8:
2668 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2669 case 16:
2670 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2671 case 32:
2672 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2673 case 64:
2674 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2675 default:
2676 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2677 }
2678 case spv::OpTypeFloat:
2679 switch (insn.word(2)) {
2680 case 16:
2681 return VK_COMPONENT_TYPE_FLOAT16_NV;
2682 case 32:
2683 return VK_COMPONENT_TYPE_FLOAT32_NV;
2684 case 64:
2685 return VK_COMPONENT_TYPE_FLOAT64_NV;
2686 default:
2687 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2688 }
2689 default:
2690 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2691 }
2692}
2693
2694// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2695// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002696bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002697 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002698 bool skip = false;
2699
2700 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002701 layer_data::unordered_map<uint32_t, uint32_t> id_to_spec_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002702 // Map SPIR-V result ID to the ID of its type.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002703 layer_data::unordered_map<uint32_t, uint32_t> id_to_type_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002704
2705 struct CoopMatType {
2706 uint32_t scope, rows, cols;
2707 VkComponentTypeNV component_type;
2708 bool all_constant;
2709
2710 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2711
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002712 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002713 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
Jeff Bolze4356752019-03-07 11:23:46 -06002714 spirv_inst_iter insn = src->get_def(id);
2715 uint32_t component_type_id = insn.word(2);
2716 uint32_t scope_id = insn.word(3);
2717 uint32_t rows_id = insn.word(4);
2718 uint32_t cols_id = insn.word(5);
2719 auto component_type_iter = src->get_def(component_type_id);
2720 auto scope_iter = src->get_def(scope_id);
2721 auto rows_iter = src->get_def(rows_id);
2722 auto cols_iter = src->get_def(cols_id);
2723
2724 all_constant = true;
2725 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2726 all_constant = false;
2727 }
2728 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2729 all_constant = false;
2730 }
2731 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2732 all_constant = false;
2733 }
2734 component_type = GetComponentType(component_type_iter, src);
2735 }
2736 };
2737
2738 bool seen_coopmat_capability = false;
2739
2740 for (auto insn : *src) {
2741 // Whitelist instructions whose result can be a cooperative matrix type, and
2742 // keep track of their types. It would be nice if SPIRV-Headers generated code
2743 // to identify which instructions have a result type and result id. Lacking that,
2744 // this whitelist is based on the set of instructions that
2745 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2746 switch (insn.opcode()) {
2747 case spv::OpLoad:
2748 case spv::OpCooperativeMatrixLoadNV:
2749 case spv::OpCooperativeMatrixMulAddNV:
2750 case spv::OpSNegate:
2751 case spv::OpFNegate:
2752 case spv::OpIAdd:
2753 case spv::OpFAdd:
2754 case spv::OpISub:
2755 case spv::OpFSub:
2756 case spv::OpFDiv:
2757 case spv::OpSDiv:
2758 case spv::OpUDiv:
2759 case spv::OpMatrixTimesScalar:
2760 case spv::OpConstantComposite:
2761 case spv::OpCompositeConstruct:
2762 case spv::OpConvertFToU:
2763 case spv::OpConvertFToS:
2764 case spv::OpConvertSToF:
2765 case spv::OpConvertUToF:
2766 case spv::OpUConvert:
2767 case spv::OpSConvert:
2768 case spv::OpFConvert:
2769 id_to_type_id[insn.word(2)] = insn.word(1);
2770 break;
2771 default:
2772 break;
2773 }
2774
2775 switch (insn.opcode()) {
2776 case spv::OpDecorate:
2777 if (insn.word(2) == spv::DecorationSpecId) {
2778 id_to_spec_id[insn.word(1)] = insn.word(3);
2779 }
2780 break;
2781 case spv::OpCapability:
2782 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2783 seen_coopmat_capability = true;
2784
2785 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002786 skip |= LogError(
2787 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2788 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2789 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002790 }
2791 }
2792 break;
2793 case spv::OpMemoryModel:
2794 // If the capability isn't enabled, don't bother with the rest of this function.
2795 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2796 if (!seen_coopmat_capability) {
2797 return skip;
2798 }
2799 break;
2800 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002801 CoopMatType m;
2802 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002803
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002804 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002805 // Validate that the type parameters are all supported for one of the
2806 // operands of a cooperative matrix property.
2807 bool valid = false;
2808 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002809 if (cooperative_matrix_properties[i].AType == m.component_type &&
2810 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2811 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002812 valid = true;
2813 break;
2814 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002815 if (cooperative_matrix_properties[i].BType == m.component_type &&
2816 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2817 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002818 valid = true;
2819 break;
2820 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002821 if (cooperative_matrix_properties[i].CType == m.component_type &&
2822 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2823 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002824 valid = true;
2825 break;
2826 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002827 if (cooperative_matrix_properties[i].DType == m.component_type &&
2828 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2829 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002830 valid = true;
2831 break;
2832 }
2833 }
2834 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002835 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2836 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2837 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002838 }
2839 }
2840 break;
2841 }
2842 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002843 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002844 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2845 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2846 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2847 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002848 // Couldn't find type of matrix
2849 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002850 break;
2851 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002852 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2853 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2854 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2855 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002856
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002857 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002858 // Validate that the type parameters are all supported for the same
2859 // cooperative matrix property.
2860 bool valid = false;
2861 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002862 if (cooperative_matrix_properties[i].AType == a.component_type &&
2863 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2864 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002865
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002866 cooperative_matrix_properties[i].BType == b.component_type &&
2867 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2868 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002869
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002870 cooperative_matrix_properties[i].CType == c.component_type &&
2871 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2872 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002873
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002874 cooperative_matrix_properties[i].DType == d.component_type &&
2875 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2876 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002877 valid = true;
2878 break;
2879 }
2880 }
2881 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002882 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2883 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2884 "VkCooperativeMatrixPropertiesNV",
2885 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002886 }
2887 }
2888 break;
2889 }
2890 default:
2891 break;
2892 }
2893 }
2894
2895 return skip;
2896}
2897
John Zulaufac4c6e12019-07-01 16:05:58 -06002898bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002899 auto entrypoint_id = entrypoint.word(2);
2900
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002901 // The first denorm execution mode encountered, along with its bit width.
2902 // Used to check if SeparateDenormSettings is respected.
2903 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002904
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002905 // The first rounding mode encountered, along with its bit width.
2906 // Used to check if SeparateRoundingModeSettings is respected.
2907 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002908
2909 bool skip = false;
2910
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002911 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002912 uint32_t invocations = 0;
2913
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002914 auto it = src->execution_mode_inst.find(entrypoint_id);
2915 if (it != src->execution_mode_inst.end()) {
2916 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002917 auto mode = insn.word(2);
2918 switch (mode) {
2919 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2920 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002921 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2922 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2923 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002924 skip |= LogError(
2925 device, kVUID_Core_Shader_FeatureNotEnabled,
2926 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2927 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002928 }
2929 break;
2930 }
2931
2932 case spv::ExecutionModeDenormPreserve: {
2933 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002934 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2935 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2936 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002937 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2938 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2939 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002940 }
2941
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002942 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2943 // Register the first denorm execution mode found
2944 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002945 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002946 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002947 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002948 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002949 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2950 "Shader uses different denorm execution modes for 16 and 64-bit but "
2951 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002952 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002953 }
2954 break;
2955
Mike Schuchardt2df08912020-12-15 16:28:09 -08002956 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002957 break;
2958
Mike Schuchardt2df08912020-12-15 16:28:09 -08002959 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002960 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2961 "Shader uses different denorm execution modes for different bit widths but "
2962 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002963 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002964 break;
2965
2966 default:
2967 break;
2968 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002969 }
2970 break;
2971 }
2972
2973 case spv::ExecutionModeDenormFlushToZero: {
2974 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002975 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2976 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2977 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002978 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2979 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2980 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002981 }
2982
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002983 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2984 // Register the first denorm execution mode found
2985 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002986 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002987 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002988 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002989 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002990 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2991 "Shader uses different denorm execution modes for 16 and 64-bit but "
2992 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002993 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002994 }
2995 break;
2996
Mike Schuchardt2df08912020-12-15 16:28:09 -08002997 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002998 break;
2999
Mike Schuchardt2df08912020-12-15 16:28:09 -08003000 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003001 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3002 "Shader uses different denorm execution modes for different bit widths but "
3003 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003004 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003005 break;
3006
3007 default:
3008 break;
3009 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003010 }
3011 break;
3012 }
3013
3014 case spv::ExecutionModeRoundingModeRTE: {
3015 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003016 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3017 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3018 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003019 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3020 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3021 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003022 }
3023
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003024 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3025 // Register the first rounding mode found
3026 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003027 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003028 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003029 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003030 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003031 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3032 "Shader uses different rounding modes for 16 and 64-bit but "
3033 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003034 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003035 }
3036 break;
3037
Mike Schuchardt2df08912020-12-15 16:28:09 -08003038 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003039 break;
3040
Mike Schuchardt2df08912020-12-15 16:28:09 -08003041 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003042 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3043 "Shader uses different rounding modes for different bit widths but "
3044 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003045 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003046 break;
3047
3048 default:
3049 break;
3050 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003051 }
3052 break;
3053 }
3054
3055 case spv::ExecutionModeRoundingModeRTZ: {
3056 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003057 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3058 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3059 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003060 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3061 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3062 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003063 }
3064
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003065 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3066 // Register the first rounding mode found
3067 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003068 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003069 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003070 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003071 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003072 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3073 "Shader uses different rounding modes for 16 and 64-bit but "
3074 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003075 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003076 }
3077 break;
3078
Mike Schuchardt2df08912020-12-15 16:28:09 -08003079 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003080 break;
3081
Mike Schuchardt2df08912020-12-15 16:28:09 -08003082 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003083 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3084 "Shader uses different rounding modes for different bit widths but "
3085 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003086 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003087 break;
3088
3089 default:
3090 break;
3091 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003092 }
3093 break;
3094 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003095
3096 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003097 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003098 break;
3099 }
3100
3101 case spv::ExecutionModeInvocations: {
3102 invocations = insn.word(3);
3103 break;
3104 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003105 }
3106 }
3107 }
3108
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003109 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003110 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003111 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3112 "Geometry shader entry point must have an OpExecutionMode instruction that "
3113 "specifies a maximum output vertex count that is greater than 0 and less "
3114 "than or equal to maxGeometryOutputVertices. "
3115 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003116 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003117 }
3118
3119 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003120 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3121 "Geometry shader entry point must have an OpExecutionMode instruction that "
3122 "specifies an invocation count that is greater than 0 and less "
3123 "than or equal to maxGeometryShaderInvocations. "
3124 "Invocations=%d, maxGeometryShaderInvocations=%d",
3125 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003126 }
3127 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003128 return skip;
3129}
3130
locke-lunargd9a069d2019-09-17 01:50:19 -06003131uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003132 auto type = module->get_def(type_id);
3133
3134 while (true) {
3135 switch (type.opcode()) {
3136 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003137 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003138 case spv::OpTypeSampledImage:
3139 type = module->get_def(type.word(2));
3140 break;
3141 case spv::OpTypePointer:
3142 type = module->get_def(type.word(3));
3143 break;
3144 case spv::OpTypeImage: {
3145 auto dim = type.word(3);
3146 auto arrayed = type.word(5);
3147 auto msaa = type.word(6);
3148
Chris Forbes74ba2232018-08-27 15:19:27 -07003149 uint32_t bits = 0;
3150 switch (GetFundamentalType(module, type.word(2))) {
3151 case FORMAT_TYPE_FLOAT:
3152 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3153 break;
3154 case FORMAT_TYPE_UINT:
3155 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3156 break;
3157 case FORMAT_TYPE_SINT:
3158 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3159 break;
3160 default:
3161 break;
3162 }
3163
Chris Forbes47567b72017-06-09 12:09:45 -07003164 switch (dim) {
3165 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003166 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3167 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003168 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003169 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3170 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3171 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003172 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003173 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3174 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003175 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003176 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3177 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003178 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003179 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3180 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003181 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003182 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003183 }
3184 }
3185 default:
3186 return 0;
3187 }
3188 }
3189}
3190
3191// For given pipelineLayout verify that the set_layout_node at slot.first
3192// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003193static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003194 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003195 if (!pipelineLayout) return nullptr;
3196
3197 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3198
3199 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3200}
3201
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003202int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3203 if (module == nullptr) return -1;
3204
3205 auto type = module->get_def(resource.type_id);
3206 while (true) {
3207 switch (type.opcode()) {
3208 case spv::OpTypeSampledImage:
3209 type = module->get_def(type.word(2));
3210 break;
3211 case spv::OpTypePointer:
3212 type = module->get_def(type.word(3));
3213 break;
3214 case spv::OpTypeImage:
3215 return type.word(3);
3216 default:
3217 return -1;
3218 }
3219 }
3220}
3221
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003222// Because the following is legal, need the entry point
3223// OpEntryPoint GLCompute %main "name_a"
3224// OpEntryPoint GLCompute %main "name_b"
3225bool FindLocalSize(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, uint32_t &local_size_x,
3226 uint32_t &local_size_y, uint32_t &local_size_z) {
3227 auto entrypoint_id = entrypoint.word(2);
3228 auto it = src->execution_mode_inst.find(entrypoint_id);
3229 if (it != src->execution_mode_inst.end()) {
3230 for (auto insn : it->second) {
3231 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
3232 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
3233 assert(insn.opcode() == spv::OpExecutionMode);
3234 if (insn.word(2) == spv::ExecutionModeLocalSize) {
3235 local_size_x = insn.word(3);
3236 local_size_y = insn.word(4);
3237 local_size_z = insn.word(5);
3238 return true;
Locke1ec6d952019-04-02 11:57:21 -06003239 }
3240 }
3241 }
3242 return false;
3243}
3244
locke-lunargd9a069d2019-09-17 01:50:19 -06003245void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003246 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003247 bool is_point_mode = false;
3248
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003249 auto it = src->execution_mode_inst.find(entrypoint_id);
3250 if (it != src->execution_mode_inst.end()) {
3251 for (auto insn : it->second) {
Chris Forbes0771b672018-03-22 21:13:46 -07003252 switch (insn.word(2)) {
3253 case spv::ExecutionModePointMode:
3254 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3255 is_point_mode = true;
3256 break;
3257
3258 case spv::ExecutionModeOutputPoints:
3259 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3260 break;
3261
3262 case spv::ExecutionModeIsolines:
3263 case spv::ExecutionModeOutputLineStrip:
3264 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3265 break;
3266
3267 case spv::ExecutionModeTriangles:
3268 case spv::ExecutionModeQuads:
3269 case spv::ExecutionModeOutputTriangleStrip:
Nathaniel Cesariocd2972d2021-04-09 11:26:55 -06003270 case spv::ExecutionModeOutputTrianglesNV:
Chris Forbes0771b672018-03-22 21:13:46 -07003271 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3272 break;
3273 }
3274 }
3275 }
3276
3277 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3278}
3279
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003280// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3281// o If there is only a vertex shader : gl_PointSize must be written when using points
3282// o If there is a geometry or tessellation shader:
3283// - If shaderTessellationAndGeometryPointSize feature is enabled:
3284// * gl_PointSize must be written in the final geometry stage
3285// - If shaderTessellationAndGeometryPointSize feature is disabled:
3286// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003287bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003288 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003289 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3290 return false;
3291 }
3292
3293 bool pointsize_written = false;
3294 bool skip = false;
3295
3296 // Search for PointSize built-in decorations
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003297 for (auto set : src->builtin_decoration_list) {
3298 auto insn = src->at(set.offset);
3299 if (set.builtin == spv::BuiltInPointSize) {
3300 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
3301 if (pointsize_written) {
3302 break;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003303 }
3304 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003305 }
3306
3307 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003308 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003309 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003310 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3311 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3312 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003313 }
3314 } else if (!pointsize_written) {
3315 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003316 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3317 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3318 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003319 }
3320 return skip;
3321}
John Zulauf14c355b2019-06-27 16:09:37 -06003322
Tobias Hector6663c9b2020-11-05 10:18:02 +00003323bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3324 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3325 bool primitiverate_written = false;
3326 bool viewportindex_written = false;
3327 bool viewportmask_written = false;
3328 bool skip = false;
3329
3330 // Check if the primitive shading rate is written
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003331 for (auto set : src->builtin_decoration_list) {
3332 auto insn = src->at(set.offset);
3333 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3334 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3335 } else if (set.builtin == spv::BuiltInViewportIndex) {
3336 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3337 } else if (set.builtin == spv::BuiltInViewportMaskNV) {
3338 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003339 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003340 if (primitiverate_written && viewportindex_written && viewportmask_written) {
3341 break;
3342 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003343 }
3344
Tony-LunarGd44844c2021-01-22 13:24:37 -07003345 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3346 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003347 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3348 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003349 skip |= LogError(pipeline->pipeline,
3350 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3351 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3352 "multiple viewports "
3353 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3354 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003355 }
3356
3357 if (primitiverate_written && viewportindex_written) {
3358 skip |= LogError(pipeline->pipeline,
3359 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3360 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3361 "ViewportIndex built-ins,"
3362 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3363 string_VkShaderStageFlagBits(stage));
3364 }
3365
3366 if (primitiverate_written && viewportmask_written) {
3367 skip |= LogError(pipeline->pipeline,
3368 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3369 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3370 "ViewportMaskNV built-ins,"
3371 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3372 string_VkShaderStageFlagBits(stage));
3373 }
3374 }
3375 return skip;
3376}
3377
sfricke-samsung486a51e2021-01-02 00:10:15 -08003378// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003379bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003380 bool skip = false;
3381
sfricke-samsung94167ca2021-02-26 04:14:59 -08003382 switch (insn.opcode()) {
3383 case spv::OpReadClockKHR: {
3384 auto scope_id = module->get_def(insn.word(3));
3385 auto scope_type = scope_id.word(3);
3386 // if scope isn't Subgroup or Device, spirv-val will catch
3387 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3388 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3389 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3390 report_data->FormatHandle(module->vk_shader_module).c_str());
3391 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3392 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3393 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3394 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003395 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003396 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003397 }
3398 }
3399 return skip;
3400}
3401
John Zulauf14c355b2019-06-27 16:09:37 -06003402bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3403 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003404 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003405 bool skip = false;
3406
3407 // Check the module
3408 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003409 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3410 "%s does not contain valid spirv for stage %s.",
3411 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003412 }
3413
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003414 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3415 // specializations should be applied and validated.
3416 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3417 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3418 // Gather the specialization-constant values.
3419 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003420 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003421 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 -06003422 id_value_map.reserve(specialization_info->mapEntryCount);
3423 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3424 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003425
Jeremy Hayes521221d2020-01-15 16:48:49 -07003426 // Expect only scalar types.
3427 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3428 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3429 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003430 }
3431
3432 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003433 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003434 spvtools::Optimizer optimizer(spirv_environment);
3435 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3436 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003437 skip |= LogError(
3438 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003439 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3440 };
3441 optimizer.SetMessageConsumer(consumer);
3442 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3443 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3444 std::vector<uint32_t> specialized_spirv;
3445 auto const optimized =
3446 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3447 assert(optimized == true);
3448
3449 if (optimized) {
3450 spv_context ctx = spvContextCreate(spirv_environment);
3451 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3452 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003453 spvtools::ValidatorOptions options;
3454 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003455 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3456 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003457 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003458 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3459 report_data->FormatHandle(module->vk_shader_module).c_str(),
3460 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003461 }
3462
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003463 spvDiagnosticDestroy(diag);
3464 spvContextDestroy(ctx);
3465 }
3466 }
3467
John Zulauf14c355b2019-06-27 16:09:37 -06003468 // Check the entrypoint
3469 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003470 skip |=
3471 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3472 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003473 }
3474 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3475
3476 // Mark accessible ids
3477 auto &accessible_ids = stage_state.accessible_ids;
3478
Chris Forbes47567b72017-06-09 12:09:45 -07003479 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003480 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3481 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003482
sfricke-samsung94167ca2021-02-26 04:14:59 -08003483 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3484 // and mainly only checking the instruction in detail for a single operation
3485 for (auto insn : *module) {
3486 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3487 skip |= ValidatePropertiesAndFeatures(module, insn);
3488 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3489 }
3490
locke-lunarg63e4daf2020-08-17 17:53:25 -06003491 skip |=
3492 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003493 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003494 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003495 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003496 skip |= ValidateSpecializationOffsets(pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003497 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003498 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003499 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003500 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
sfricke-samsungd093e522021-02-26 04:17:45 -08003501 if (enabled_features.cooperative_matrix_features.cooperativeMatrix) {
3502 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
3503 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003504 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3505 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3506 }
Chris Forbes47567b72017-06-09 12:09:45 -07003507
sfricke-samsung7699b912021-04-12 23:01:51 -07003508 // "layout must be consistent with the layout of the * shader"
3509 // 'consistent' -> #descriptorsets-pipelinelayout-consistency
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003510 std::string vuid_layout_mismatch;
3511 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3512 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3513 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3514 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3515 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3516 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3517 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3518 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3519 }
3520
sfricke-samsung7699b912021-04-12 23:01:51 -07003521 // Validate Push Constants use
3522 skip |= ValidatePushConstantUsage(*pipeline, module, pStage, vuid_layout_mismatch);
3523
Chris Forbes47567b72017-06-09 12:09:45 -07003524 // Validate descriptor use
3525 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003526 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003527 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003528 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003529 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3530 std::set<uint32_t> descriptor_types =
3531 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003532
3533 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003534 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003535 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3536 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003537 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003538 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003539 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3540 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Tony-LunarGf563b362021-03-18 16:13:18 -06003541 } else if ((binding->descriptorType != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE) &&
3542 (descriptor_types.find(binding->descriptorType) == descriptor_types.end())) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003543 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003544 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3545 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3546 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003547 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003548 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003549 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3550 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003551 }
3552 }
3553
3554 // Validate use of input attachments against subpass structure
3555 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003556 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003557
Petr Krause91f7a12017-12-14 20:57:36 +01003558 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003559 auto subpass = pipeline->graphicsPipelineCI.subpass;
3560
3561 for (auto use : input_attachment_uses) {
3562 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3563 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003564 ? input_attachments[use.first].attachment
3565 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003566
3567 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003568 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3569 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003570 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003571 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003572 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3573 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3574 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003575 }
3576 }
3577 }
Lockeaa8fdc02019-04-02 11:59:20 -06003578 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003579 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06003580 }
Chris Forbes47567b72017-06-09 12:09:45 -07003581 return skip;
3582}
3583
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003584bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3585 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3586 spirv_inst_iter consumer_entrypoint,
3587 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003588 bool skip = false;
3589
3590 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003591 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3592 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003593
3594 auto a_it = outputs.begin();
3595 auto b_it = inputs.begin();
3596
3597 // Maps sorted by key (location); walk them together to find mismatches
3598 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3599 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3600 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3601 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3602 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3603
3604 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003605 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3606 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3607 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003608 a_it++;
3609 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003610 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3611 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3612 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003613 b_it++;
3614 } else {
3615 // subtleties of arrayed interfaces:
3616 // - if is_patch, then the member is not arrayed, even though the interface may be.
3617 // - if is_block_member, then the extra array level of an arrayed interface is not
3618 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003619 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3620 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3621 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003622 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3623 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3624 DescribeType(producer, a_it->second.type_id).c_str(),
3625 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003626 }
3627 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003628 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3629 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3630 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3631 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003632 }
3633 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003634 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3635 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3636 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003637 }
3638 a_it++;
3639 b_it++;
3640 }
3641 }
3642
Ari Suonpaa696b3432019-03-11 14:02:57 +02003643 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3644 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3645 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3646
3647 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3648 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003649 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3650 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003651 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3652 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003653 } else {
3654 auto it_producer = builtins_producer.begin();
3655 auto it_consumer = builtins_consumer.begin();
3656 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3657 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003658 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3659 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3660 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003661 break;
3662 }
3663 it_producer++;
3664 it_consumer++;
3665 }
3666 }
3667 }
3668 }
3669
Chris Forbes47567b72017-06-09 12:09:45 -07003670 return skip;
3671}
3672
John Zulauf14c355b2019-06-27 16:09:37 -06003673static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003674 uint32_t stage_mask = 0;
3675 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3676 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3677 stage_mask |= pCreateInfo->pStages[i].stage;
3678 }
3679 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003680 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3681 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3682 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003683 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3684 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3685 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3686 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3687 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003688 }
3689 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003690 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003691}
3692
Chris Forbes47567b72017-06-09 12:09:45 -07003693// Validate that the shaders used by the given pipeline and store the active_slots
3694// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003695bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003696 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003697 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3698 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003699
John Zulauf14c355b2019-06-27 16:09:37 -06003700 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003701 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003702 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003703 bool skip = false;
3704
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003705 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003706
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003707 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3708 auto stage = &create_info->pStages[i];
3709 auto stage_id = GetShaderStageId(stage->stage);
3710 shaders[stage_id] = GetShaderModuleState(stage->module);
3711 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3712 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3713 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003714 }
3715
3716 // if the shader stages are no good individually, cross-stage validation is pointless.
3717 if (skip) return true;
3718
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003719 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003720
3721 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003722 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003723 }
3724
3725 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003726 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003727 }
3728
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003729 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3730 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003731
3732 while (!shaders[producer] && producer != fragment_stage) {
3733 producer++;
3734 consumer++;
3735 }
3736
3737 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3738 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003739 if (shaders[consumer]) {
3740 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003741 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3742 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003743 }
Chris Forbes47567b72017-06-09 12:09:45 -07003744
3745 producer = consumer;
3746 }
3747 }
3748
3749 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003750 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003751 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003752 }
3753
3754 return skip;
3755}
3756
Tony-LunarGb2ded512021-02-02 16:03:30 -07003757void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3758 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3759
3760 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3761 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3762 return;
3763 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003764
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003765 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3766 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003767 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003768
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003769 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3770 auto stage = &create_info->pStages[i];
3771 auto stage_id = GetShaderStageId(stage->stage);
3772 shaders[stage_id] = GetShaderModuleState(stage->module);
3773 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003774
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003775 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3776 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003777 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003778
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003779 for (auto set : shaders[stage_id]->builtin_decoration_list) {
3780 auto insn = shaders[stage_id]->at(set.offset);
3781 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3782 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003783 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003784 if (primitiverate_written) {
3785 break;
3786 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003787 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003788
Tony-LunarGb2ded512021-02-02 16:03:30 -07003789 if (primitiverate_written) {
3790 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3791 }
3792 }
3793 }
3794}
3795
3796bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3797 const char *caller, const DrawDispatchVuid &vuid) const {
3798 auto create_info = pipeline->graphicsPipelineCI.ptr();
3799 bool skip = false;
3800
3801 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3802 auto stage = &create_info->pStages[i];
3803 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3804 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3805 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3806 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3807 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003808 skip |=
3809 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3810 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3811 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3812 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003813 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003814 }
3815 }
3816 }
3817 }
3818
3819 return skip;
3820}
3821
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003822bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003823 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003824
John Zulauf14c355b2019-06-27 16:09:37 -06003825 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3826 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003827
John Zulauf14c355b2019-06-27 16:09:37 -06003828 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003829}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003830
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003831uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3832 uint32_t total = 0;
3833
3834 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3835 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3836 if (stages[stage_index].stage == stageBit) {
3837 total++;
3838 }
3839 }
3840
3841 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3842 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3843 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3844 total += CalcShaderStageCount(library_pipeline, stageBit);
3845 }
3846 }
3847
3848 return total;
3849}
3850
sourav parmarcd5fb182020-07-17 12:58:44 -07003851bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003852 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003853
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003854 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003855 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3856 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3857 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3858 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3859 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3860 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3861 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003862 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003863 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3864 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003865 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003866 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003867 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003868 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3869 skip |= LogError(
3870 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3871 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3872 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003873 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003874 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3875 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003876 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3877 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003878 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003879 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003880 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3881 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3882 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3883 "member must have been created with values of the maxPipelineRayPayloadSize and "
3884 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3885 }
3886 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003887 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003888 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3889 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3890 "vkCreateRayTracingPipelinesKHR: If flags includes "
3891 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3892 "the pLibraries member of libraries must have been created with the "
3893 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3894 }
sourav parmar83c31b12020-05-06 12:30:54 -07003895 }
3896 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003897 } else {
3898 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003899 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3900 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3901 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003902 pipeline->raytracingPipelineCI.maxRecursionDepth,
3903 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3904 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003905 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003906 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3907 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3908
John Zulaufe4474e72019-07-01 17:28:27 -06003909 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003910 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003911
John Zulaufe4474e72019-07-01 17:28:27 -06003912 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3913 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003914
John Zulaufe4474e72019-07-01 17:28:27 -06003915 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003916 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003917
3918 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3919 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3920 if (raygen_stages_count == 0) {
3921 skip |= LogError(
3922 device,
3923 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3924 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3925 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003926 }
3927
3928 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3929 const auto &group = groups[group_index];
3930
3931 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3932 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3933 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3934 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3935 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003936 skip |= LogError(device,
3937 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3938 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3939 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003940 }
3941 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3942 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003943 skip |= LogError(device,
3944 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3945 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3946 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003947 }
3948 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3949 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3950 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003951 skip |= LogError(device,
3952 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3953 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3954 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003955 }
3956 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3957 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003958 skip |= LogError(device,
3959 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3960 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3961 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003962 }
3963 }
3964
3965 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3966 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3967 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3968 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003969 skip |= LogError(device,
3970 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3971 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3972 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003973 }
3974 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3975 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3976 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003977 skip |= LogError(device,
3978 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3979 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3980 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003981 }
3982 }
John Zulaufe4474e72019-07-01 17:28:27 -06003983 }
3984 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003985}
3986
Dave Houltona9df0ce2018-02-07 10:51:23 -07003987uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003988
Dave Houltona9df0ce2018-02-07 10:51:23 -07003989static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003990 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003991 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003992 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003993 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003994 return nullptr;
3995}
3996
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003997bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003998 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003999 bool skip = false;
4000 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004001
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06004002 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004003 return false;
4004 }
4005
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06004006 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004007
4008 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004009 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
4010 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
4011 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004012 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004013 auto cache = GetValidationCacheInfo(pCreateInfo);
4014 uint32_t hash = 0;
4015 if (cache) {
4016 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004017 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004018 }
4019
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004020 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4021 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004022 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004023 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004024 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004025 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004026 spvtools::ValidatorOptions options;
4027 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004028 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004029 if (spv_valid != SPV_SUCCESS) {
4030 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004031 if (spv_valid == SPV_WARNING) {
4032 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4033 diag && diag->error ? diag->error : "(no error text)");
4034 } else {
4035 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4036 diag && diag->error ? diag->error : "(no error text)");
4037 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004038 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004039 } else {
4040 if (cache) {
4041 cache->Insert(hash);
4042 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004043 }
4044
4045 spvDiagnosticDestroy(diag);
4046 spvContextDestroy(ctx);
4047 }
4048
Chris Forbes4ae55b32017-06-09 14:42:56 -07004049 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004050}
4051
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004052bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004053 bool skip = false;
4054 uint32_t local_size_x = 0;
4055 uint32_t local_size_y = 0;
4056 uint32_t local_size_z = 0;
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004057 if (FindLocalSize(shader, entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06004058 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004059 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4060 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4061 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4062 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004063 }
4064 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004065 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4066 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4067 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4068 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004069 }
4070 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004071 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4072 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4073 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4074 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004075 }
4076
4077 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4078 uint64_t invocations = local_size_x * local_size_y;
4079 // Prevent overflow.
4080 bool fail = false;
4081 if (invocations > UINT32_MAX || invocations > limit) {
4082 fail = true;
4083 }
4084 if (!fail) {
4085 invocations *= local_size_z;
4086 if (invocations > UINT32_MAX || invocations > limit) {
4087 fail = true;
4088 }
4089 }
4090 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004091 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4092 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4093 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4094 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4095 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004096 }
4097 }
4098 return skip;
4099}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004100
4101spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4102 if (api_version >= VK_API_VERSION_1_2) {
4103 return SPV_ENV_VULKAN_1_2;
4104 } else if (api_version >= VK_API_VERSION_1_1) {
4105 if (spirv_1_4) {
4106 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4107 } else {
4108 return SPV_ENV_VULKAN_1_1;
4109 }
4110 }
4111 return SPV_ENV_VULKAN_1_0;
4112}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004113
4114void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4115 spvtools::ValidatorOptions &options) {
4116 if (device_extensions.vk_khr_relaxed_block_layout) {
4117 options.SetRelaxBlockLayout(true);
4118 }
4119 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4120 options.SetUniformBufferStandardLayout(true);
4121 }
4122 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4123 options.SetScalarBlockLayout(true);
4124 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004125 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4126 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4127 options.SetWorkgroupScalarBlockLayout(true);
4128 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004129}